update to version 2.1.4
[gitweb.git] / index.cgi
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 5.008;
11 use strict;
12 use warnings;
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
19 use File::Basename qw(basename);
20 use Time::HiRes qw(gettimeofday tv_interval);
21 binmode STDOUT, ':utf8';
22
23 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
24 eval 'sub CGI::multi_param { CGI::param(@_) }'
25 }
26
27 our $t0 = [ gettimeofday() ];
28 our $number_of_git_cmds = 0;
29
30 BEGIN {
31 CGI->compile() if $ENV{'MOD_PERL'};
32 }
33
34 our $version = "2.1.4-Stricted";
35
36 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
37 sub evaluate_uri {
38 our $cgi;
39
40 our $my_url = $cgi->url();
41 our $my_uri = $cgi->url(-absolute => 1);
42
43 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
44 # needed and used only for URLs with nonempty PATH_INFO
45 our $base_url = $my_url;
46
47 # When the script is used as DirectoryIndex, the URL does not contain the name
48 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
49 # have to do it ourselves. We make $path_info global because it's also used
50 # later on.
51 #
52 # Another issue with the script being the DirectoryIndex is that the resulting
53 # $my_url data is not the full script URL: this is good, because we want
54 # generated links to keep implying the script name if it wasn't explicitly
55 # indicated in the URL we're handling, but it means that $my_url cannot be used
56 # as base URL.
57 # Therefore, if we needed to strip PATH_INFO, then we know that we have
58 # to build the base URL ourselves:
59 our $path_info = decode_utf8($ENV{"PATH_INFO"});
60 if ($path_info) {
61 # $path_info has already been URL-decoded by the web server, but
62 # $my_url and $my_uri have not. URL-decode them so we can properly
63 # strip $path_info.
64 $my_url = unescape($my_url);
65 $my_uri = unescape($my_uri);
66 if ($my_url =~ s,\Q$path_info\E$,, &&
67 $my_uri =~ s,\Q$path_info\E$,, &&
68 defined $ENV{'SCRIPT_NAME'}) {
69 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
70 }
71 }
72
73 # target of the home link on top of all pages
74 our $home_link = $my_uri || "/";
75 }
76
77 # core git executable to use
78 # this can just be "git" if your webserver has a sensible PATH
79 our $GIT = "/usr/bin/git";
80
81 # absolute fs-path which will be prepended to the project path
82 #our $projectroot = "/pub/scm";
83 our $projectroot = "/pub/git";
84
85 # fs traversing limit for getting project list
86 # the number is relative to the projectroot
87 our $project_maxdepth = 2007;
88
89 # string of the home link on top of all pages
90 our $home_link_str = "projects";
91
92 # extra breadcrumbs preceding the home link
93 our @extra_breadcrumbs = ();
94
95 # name of your site or organization to appear in page titles
96 # replace this with something more descriptive for clearer bookmarks
97 our $site_name = ""
98 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
99
100 # html snippet to include in the <head> section of each page
101 our $site_html_head_string = "";
102 # filename of html text to include at top of each page
103 our $site_header = "";
104 # html text to include at home page
105 our $home_text = "indextext.html";
106 # filename of html text to include at bottom of each page
107 our $site_footer = "";
108
109 # URI of stylesheets
110 our @stylesheets = ("static/gitweb.css");
111 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
112 our $stylesheet = undef;
113 # URI of GIT logo (72x27 size)
114 our $logo = "static/git-logo.png";
115 # URI of GIT favicon, assumed to be image/png type
116 our $favicon = "static/git-favicon.png";
117 # URI of gitweb.js (JavaScript code for gitweb)
118 our $javascript = "static/gitweb.js";
119
120 # URI and label (title) of GIT logo link
121 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
122 #our $logo_label = "git documentation";
123 our $logo_url = "http://git-scm.com/";
124 our $logo_label = "git homepage";
125
126 # URI and label (title) of footer
127 our $footer_url = "http://git-scm.com/";
128 our $footer_label = "git homepage";
129
130 # source of projects list
131 our $projects_list = "";
132
133 # the width (in characters) of the projects list "Description" column
134 our $projects_list_description_width = 25;
135
136 # group projects by category on the projects list
137 # (enabled if this variable evaluates to true)
138 our $projects_list_group_categories = 0;
139
140 # default category if none specified
141 # (leave the empty string for no category)
142 our $project_list_default_category = "";
143
144 # default order of projects list
145 # valid values are none, project, descr, owner, and age
146 our $default_projects_order = "project";
147
148 # show repository only if this file exists
149 # (only effective if this variable evaluates to true)
150 our $export_ok = "";
151
152 # don't generate age column on the projects list page
153 our $omit_age_column = 0;
154
155 # don't generate information about owners of repositories
156 our $omit_owner=0;
157
158 # show repository only if this subroutine returns true
159 # when given the path to the project, for example:
160 # sub { return -e "$_[0]/git-daemon-export-ok"; }
161 our $export_auth_hook = undef;
162
163 # only allow viewing of repositories also shown on the overview page
164 our $strict_export = "";
165
166 # list of git base URLs used for URL to where fetch project from,
167 # i.e. full URL is "$git_base_url/$project"
168 our @git_base_url_list = grep { $_ ne '' } ("");
169
170 # default blob_plain mimetype and default charset for text/plain blob
171 our $default_blob_plain_mimetype = 'text/plain';
172 our $default_text_plain_charset = undef;
173
174 # file to use for guessing MIME types before trying /etc/mime.types
175 # (relative to the current git repository)
176 our $mimetypes_file = undef;
177
178 # assume this charset if line contains non-UTF-8 characters;
179 # it should be valid encoding (see Encoding::Supported(3pm) for list),
180 # for which encoding all byte sequences are valid, for example
181 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
182 # could be even 'utf-8' for the old behavior)
183 our $fallback_encoding = 'latin1';
184
185 # rename detection options for git-diff and git-diff-tree
186 # - default is '-M', with the cost proportional to
187 # (number of removed files) * (number of new files).
188 # - more costly is '-C' (which implies '-M'), with the cost proportional to
189 # (number of changed files + number of removed files) * (number of new files)
190 # - even more costly is '-C', '--find-copies-harder' with cost
191 # (number of files in the original tree) * (number of new files)
192 # - one might want to include '-B' option, e.g. '-B', '-M'
193 our @diff_opts = ('-M'); # taken from git_commit
194
195 # Disables features that would allow repository owners to inject script into
196 # the gitweb domain.
197 our $prevent_xss = 0;
198
199 # Path to the highlight executable to use (must be the one from
200 # http://www.andre-simon.de due to assumptions about parameters and output).
201 # Useful if highlight is not installed on your webserver's PATH.
202 # [Default: highlight]
203 our $highlight_bin = "highlight";
204
205 # information about snapshot formats that gitweb is capable of serving
206 our %known_snapshot_formats = (
207 # name => {
208 # 'display' => display name,
209 # 'type' => mime type,
210 # 'suffix' => filename suffix,
211 # 'format' => --format for git-archive,
212 # 'compressor' => [compressor command and arguments]
213 # (array reference, optional)
214 # 'disabled' => boolean (optional)}
215 #
216 'tgz' => {
217 'display' => 'tar.gz',
218 'type' => 'application/x-gzip',
219 'suffix' => '.tar.gz',
220 'format' => 'tar',
221 'compressor' => ['gzip', '-n']},
222
223 'tbz2' => {
224 'display' => 'tar.bz2',
225 'type' => 'application/x-bzip2',
226 'suffix' => '.tar.bz2',
227 'format' => 'tar',
228 'compressor' => ['bzip2']},
229
230 'txz' => {
231 'display' => 'tar.xz',
232 'type' => 'application/x-xz',
233 'suffix' => '.tar.xz',
234 'format' => 'tar',
235 'compressor' => ['xz'],
236 'disabled' => 1},
237
238 'zip' => {
239 'display' => 'zip',
240 'type' => 'application/x-zip',
241 'suffix' => '.zip',
242 'format' => 'zip'},
243 );
244
245 # Aliases so we understand old gitweb.snapshot values in repository
246 # configuration.
247 our %known_snapshot_format_aliases = (
248 'gzip' => 'tgz',
249 'bzip2' => 'tbz2',
250 'xz' => 'txz',
251
252 # backward compatibility: legacy gitweb config support
253 'x-gzip' => undef, 'gz' => undef,
254 'x-bzip2' => undef, 'bz2' => undef,
255 'x-zip' => undef, '' => undef,
256 );
257
258 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
259 # are changed, it may be appropriate to change these values too via
260 # $GITWEB_CONFIG.
261 our %avatar_size = (
262 'default' => 16,
263 'double' => 32
264 );
265
266 # Used to set the maximum load that we will still respond to gitweb queries.
267 # If server load exceed this value then return "503 server busy" error.
268 # If gitweb cannot determined server load, it is taken to be 0.
269 # Leave it undefined (or set to 'undef') to turn off load checking.
270 our $maxload = 300;
271
272 # configuration for 'highlight' (http://www.andre-simon.de/)
273 # match by basename
274 our %highlight_basename = (
275 #'Program' => 'py',
276 #'Library' => 'py',
277 'SConstruct' => 'py', # SCons equivalent of Makefile
278 'Makefile' => 'make',
279 );
280 # match by extension
281 our %highlight_ext = (
282 # main extensions, defining name of syntax;
283 # see files in /usr/share/highlight/langDefs/ directory
284 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
285 # alternate extensions, see /etc/highlight/filetypes.conf
286 (map { $_ => 'c' } qw(c h)),
287 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
288 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
289 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
290 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
291 (map { $_ => 'make'} qw(make mak mk)),
292 (map { $_ => 'xml' } qw(xml xhtml html htm)),
293 );
294
295 # You define site-wide feature defaults here; override them with
296 # $GITWEB_CONFIG as necessary.
297 our %feature = (
298 # feature => {
299 # 'sub' => feature-sub (subroutine),
300 # 'override' => allow-override (boolean),
301 # 'default' => [ default options...] (array reference)}
302 #
303 # if feature is overridable (it means that allow-override has true value),
304 # then feature-sub will be called with default options as parameters;
305 # return value of feature-sub indicates if to enable specified feature
306 #
307 # if there is no 'sub' key (no feature-sub), then feature cannot be
308 # overridden
309 #
310 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
311 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
312 # is enabled
313
314 # Enable the 'blame' blob view, showing the last commit that modified
315 # each line in the file. This can be very CPU-intensive.
316
317 # To enable system wide have in $GITWEB_CONFIG
318 # $feature{'blame'}{'default'} = [1];
319 # To have project specific config enable override in $GITWEB_CONFIG
320 # $feature{'blame'}{'override'} = 1;
321 # and in project config gitweb.blame = 0|1;
322 'blame' => {
323 'sub' => sub { feature_bool('blame', @_) },
324 'override' => 0,
325 'default' => [0]},
326
327 # Enable the 'snapshot' link, providing a compressed archive of any
328 # tree. This can potentially generate high traffic if you have large
329 # project.
330
331 # Value is a list of formats defined in %known_snapshot_formats that
332 # you wish to offer.
333 # To disable system wide have in $GITWEB_CONFIG
334 # $feature{'snapshot'}{'default'} = [];
335 # To have project specific config enable override in $GITWEB_CONFIG
336 # $feature{'snapshot'}{'override'} = 1;
337 # and in project config, a comma-separated list of formats or "none"
338 # to disable. Example: gitweb.snapshot = tbz2,zip;
339 'snapshot' => {
340 'sub' => \&feature_snapshot,
341 'override' => 0,
342 'default' => ['tgz']},
343
344 # Enable text search, which will list the commits which match author,
345 # committer or commit text to a given string. Enabled by default.
346 # Project specific override is not supported.
347 #
348 # Note that this controls all search features, which means that if
349 # it is disabled, then 'grep' and 'pickaxe' search would also be
350 # disabled.
351 'search' => {
352 'override' => 0,
353 'default' => [1]},
354
355 # Enable grep search, which will list the files in currently selected
356 # tree containing the given string. Enabled by default. This can be
357 # potentially CPU-intensive, of course.
358 # Note that you need to have 'search' feature enabled too.
359
360 # To enable system wide have in $GITWEB_CONFIG
361 # $feature{'grep'}{'default'} = [1];
362 # To have project specific config enable override in $GITWEB_CONFIG
363 # $feature{'grep'}{'override'} = 1;
364 # and in project config gitweb.grep = 0|1;
365 'grep' => {
366 'sub' => sub { feature_bool('grep', @_) },
367 'override' => 0,
368 'default' => [1]},
369
370 # Enable the pickaxe search, which will list the commits that modified
371 # a given string in a file. This can be practical and quite faster
372 # alternative to 'blame', but still potentially CPU-intensive.
373 # Note that you need to have 'search' feature enabled too.
374
375 # To enable system wide have in $GITWEB_CONFIG
376 # $feature{'pickaxe'}{'default'} = [1];
377 # To have project specific config enable override in $GITWEB_CONFIG
378 # $feature{'pickaxe'}{'override'} = 1;
379 # and in project config gitweb.pickaxe = 0|1;
380 'pickaxe' => {
381 'sub' => sub { feature_bool('pickaxe', @_) },
382 'override' => 0,
383 'default' => [1]},
384
385 # Enable showing size of blobs in a 'tree' view, in a separate
386 # column, similar to what 'ls -l' does. This cost a bit of IO.
387
388 # To disable system wide have in $GITWEB_CONFIG
389 # $feature{'show-sizes'}{'default'} = [0];
390 # To have project specific config enable override in $GITWEB_CONFIG
391 # $feature{'show-sizes'}{'override'} = 1;
392 # and in project config gitweb.showsizes = 0|1;
393 'show-sizes' => {
394 'sub' => sub { feature_bool('showsizes', @_) },
395 'override' => 0,
396 'default' => [1]},
397
398 # Make gitweb use an alternative format of the URLs which can be
399 # more readable and natural-looking: project name is embedded
400 # directly in the path and the query string contains other
401 # auxiliary information. All gitweb installations recognize
402 # URL in either format; this configures in which formats gitweb
403 # generates links.
404
405 # To enable system wide have in $GITWEB_CONFIG
406 # $feature{'pathinfo'}{'default'} = [1];
407 # Project specific override is not supported.
408
409 # Note that you will need to change the default location of CSS,
410 # favicon, logo and possibly other files to an absolute URL. Also,
411 # if gitweb.cgi serves as your indexfile, you will need to force
412 # $my_uri to contain the script name in your $GITWEB_CONFIG.
413 'pathinfo' => {
414 'override' => 0,
415 'default' => [0]},
416
417 # Make gitweb consider projects in project root subdirectories
418 # to be forks of existing projects. Given project $projname.git,
419 # projects matching $projname/*.git will not be shown in the main
420 # projects list, instead a '+' mark will be added to $projname
421 # there and a 'forks' view will be enabled for the project, listing
422 # all the forks. If project list is taken from a file, forks have
423 # to be listed after the main project.
424
425 # To enable system wide have in $GITWEB_CONFIG
426 # $feature{'forks'}{'default'} = [1];
427 # Project specific override is not supported.
428 'forks' => {
429 'override' => 0,
430 'default' => [0]},
431
432 # Insert custom links to the action bar of all project pages.
433 # This enables you mainly to link to third-party scripts integrating
434 # into gitweb; e.g. git-browser for graphical history representation
435 # or custom web-based repository administration interface.
436
437 # The 'default' value consists of a list of triplets in the form
438 # (label, link, position) where position is the label after which
439 # to insert the link and link is a format string where %n expands
440 # to the project name, %f to the project path within the filesystem,
441 # %h to the current hash (h gitweb parameter) and %b to the current
442 # hash base (hb gitweb parameter); %% expands to %.
443
444 # To enable system wide have in $GITWEB_CONFIG e.g.
445 # $feature{'actions'}{'default'} = [('graphiclog',
446 # '/git-browser/by-commit.html?r=%n', 'summary')];
447 # Project specific override is not supported.
448 'actions' => {
449 'override' => 0,
450 'default' => []},
451
452 # Allow gitweb scan project content tags of project repository,
453 # and display the popular Web 2.0-ish "tag cloud" near the projects
454 # list. Note that this is something COMPLETELY different from the
455 # normal Git tags.
456
457 # gitweb by itself can show existing tags, but it does not handle
458 # tagging itself; you need to do it externally, outside gitweb.
459 # The format is described in git_get_project_ctags() subroutine.
460 # You may want to install the HTML::TagCloud Perl module to get
461 # a pretty tag cloud instead of just a list of tags.
462
463 # To enable system wide have in $GITWEB_CONFIG
464 # $feature{'ctags'}{'default'} = [1];
465 # Project specific override is not supported.
466
467 # In the future whether ctags editing is enabled might depend
468 # on the value, but using 1 should always mean no editing of ctags.
469 'ctags' => {
470 'override' => 0,
471 'default' => [0]},
472
473 # The maximum number of patches in a patchset generated in patch
474 # view. Set this to 0 or undef to disable patch view, or to a
475 # negative number to remove any limit.
476
477 # To disable system wide have in $GITWEB_CONFIG
478 # $feature{'patches'}{'default'} = [0];
479 # To have project specific config enable override in $GITWEB_CONFIG
480 # $feature{'patches'}{'override'} = 1;
481 # and in project config gitweb.patches = 0|n;
482 # where n is the maximum number of patches allowed in a patchset.
483 'patches' => {
484 'sub' => \&feature_patches,
485 'override' => 0,
486 'default' => [16]},
487
488 # Avatar support. When this feature is enabled, views such as
489 # shortlog or commit will display an avatar associated with
490 # the email of the committer(s) and/or author(s).
491
492 # Currently available providers are gravatar and picon.
493 # If an unknown provider is specified, the feature is disabled.
494
495 # Gravatar depends on Digest::MD5.
496 # Picon currently relies on the indiana.edu database.
497
498 # To enable system wide have in $GITWEB_CONFIG
499 # $feature{'avatar'}{'default'} = ['<provider>'];
500 # where <provider> is either gravatar or picon.
501 # To have project specific config enable override in $GITWEB_CONFIG
502 # $feature{'avatar'}{'override'} = 1;
503 # and in project config gitweb.avatar = <provider>;
504 'avatar' => {
505 'sub' => \&feature_avatar,
506 'override' => 0,
507 'default' => ['']},
508
509 # Enable displaying how much time and how many git commands
510 # it took to generate and display page. Disabled by default.
511 # Project specific override is not supported.
512 'timed' => {
513 'override' => 0,
514 'default' => [0]},
515
516 # Enable turning some links into links to actions which require
517 # JavaScript to run (like 'blame_incremental'). Not enabled by
518 # default. Project specific override is currently not supported.
519 'javascript-actions' => {
520 'override' => 0,
521 'default' => [0]},
522
523 # Enable and configure ability to change common timezone for dates
524 # in gitweb output via JavaScript. Enabled by default.
525 # Project specific override is not supported.
526 'javascript-timezone' => {
527 'override' => 0,
528 'default' => [
529 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
530 # or undef to turn off this feature
531 'gitweb_tz', # name of cookie where to store selected timezone
532 'datetime', # CSS class used to mark up dates for manipulation
533 ]},
534
535 # Syntax highlighting support. This is based on Daniel Svensson's
536 # and Sham Chukoury's work in gitweb-xmms2.git.
537 # It requires the 'highlight' program present in $PATH,
538 # and therefore is disabled by default.
539
540 # To enable system wide have in $GITWEB_CONFIG
541 # $feature{'highlight'}{'default'} = [1];
542
543 'highlight' => {
544 'sub' => sub { feature_bool('highlight', @_) },
545 'override' => 0,
546 'default' => [0]},
547
548 # Enable displaying of remote heads in the heads list
549
550 # To enable system wide have in $GITWEB_CONFIG
551 # $feature{'remote_heads'}{'default'} = [1];
552 # To have project specific config enable override in $GITWEB_CONFIG
553 # $feature{'remote_heads'}{'override'} = 1;
554 # and in project config gitweb.remoteheads = 0|1;
555 'remote_heads' => {
556 'sub' => sub { feature_bool('remote_heads', @_) },
557 'override' => 0,
558 'default' => [0]},
559
560 # Enable showing branches under other refs in addition to heads
561
562 # To set system wide extra branch refs have in $GITWEB_CONFIG
563 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
564 # To have project specific config enable override in $GITWEB_CONFIG
565 # $feature{'extra-branch-refs'}{'override'} = 1;
566 # and in project config gitweb.extrabranchrefs = dirs of choice
567 # Every directory is separated with whitespace.
568
569 'extra-branch-refs' => {
570 'sub' => \&feature_extra_branch_refs,
571 'override' => 0,
572 'default' => []},
573 );
574
575 sub gitweb_get_feature {
576 my ($name) = @_;
577 return unless exists $feature{$name};
578 my ($sub, $override, @defaults) = (
579 $feature{$name}{'sub'},
580 $feature{$name}{'override'},
581 @{$feature{$name}{'default'}});
582 # project specific override is possible only if we have project
583 our $git_dir; # global variable, declared later
584 if (!$override || !defined $git_dir) {
585 return @defaults;
586 }
587 if (!defined $sub) {
588 warn "feature $name is not overridable";
589 return @defaults;
590 }
591 return $sub->(@defaults);
592 }
593
594 # A wrapper to check if a given feature is enabled.
595 # With this, you can say
596 #
597 # my $bool_feat = gitweb_check_feature('bool_feat');
598 # gitweb_check_feature('bool_feat') or somecode;
599 #
600 # instead of
601 #
602 # my ($bool_feat) = gitweb_get_feature('bool_feat');
603 # (gitweb_get_feature('bool_feat'))[0] or somecode;
604 #
605 sub gitweb_check_feature {
606 return (gitweb_get_feature(@_))[0];
607 }
608
609
610 sub feature_bool {
611 my $key = shift;
612 my ($val) = git_get_project_config($key, '--bool');
613
614 if (!defined $val) {
615 return ($_[0]);
616 } elsif ($val eq 'true') {
617 return (1);
618 } elsif ($val eq 'false') {
619 return (0);
620 }
621 }
622
623 sub feature_snapshot {
624 my (@fmts) = @_;
625
626 my ($val) = git_get_project_config('snapshot');
627
628 if ($val) {
629 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
630 }
631
632 return @fmts;
633 }
634
635 sub feature_patches {
636 my @val = (git_get_project_config('patches', '--int'));
637
638 if (@val) {
639 return @val;
640 }
641
642 return ($_[0]);
643 }
644
645 sub feature_avatar {
646 my @val = (git_get_project_config('avatar'));
647
648 return @val ? @val : @_;
649 }
650
651 sub feature_extra_branch_refs {
652 my (@branch_refs) = @_;
653 my $values = git_get_project_config('extrabranchrefs');
654
655 if ($values) {
656 $values = config_to_multi ($values);
657 @branch_refs = ();
658 foreach my $value (@{$values}) {
659 push @branch_refs, split /\s+/, $value;
660 }
661 }
662
663 return @branch_refs;
664 }
665
666 # checking HEAD file with -e is fragile if the repository was
667 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
668 # and then pruned.
669 sub check_head_link {
670 my ($dir) = @_;
671 my $headfile = "$dir/HEAD";
672 return ((-e $headfile) ||
673 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
674 }
675
676 sub check_export_ok {
677 my ($dir) = @_;
678 return (check_head_link($dir) &&
679 (!$export_ok || -e "$dir/$export_ok") &&
680 (!$export_auth_hook || $export_auth_hook->($dir)));
681 }
682
683 # process alternate names for backward compatibility
684 # filter out unsupported (unknown) snapshot formats
685 sub filter_snapshot_fmts {
686 my @fmts = @_;
687
688 @fmts = map {
689 exists $known_snapshot_format_aliases{$_} ?
690 $known_snapshot_format_aliases{$_} : $_} @fmts;
691 @fmts = grep {
692 exists $known_snapshot_formats{$_} &&
693 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
694 }
695
696 sub filter_and_validate_refs {
697 my @refs = @_;
698 my %unique_refs = ();
699
700 foreach my $ref (@refs) {
701 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
702 # 'heads' are added implicitly in get_branch_refs().
703 $unique_refs{$ref} = 1 if ($ref ne 'heads');
704 }
705 return sort keys %unique_refs;
706 }
707
708 # If it is set to code reference, it is code that it is to be run once per
709 # request, allowing updating configurations that change with each request,
710 # while running other code in config file only once.
711 #
712 # Otherwise, if it is false then gitweb would process config file only once;
713 # if it is true then gitweb config would be run for each request.
714 our $per_request_config = 1;
715
716 # read and parse gitweb config file given by its parameter.
717 # returns true on success, false on recoverable error, allowing
718 # to chain this subroutine, using first file that exists.
719 # dies on errors during parsing config file, as it is unrecoverable.
720 sub read_config_file {
721 my $filename = shift;
722 return unless defined $filename;
723 # die if there are errors parsing config file
724 if (-e $filename) {
725 do $filename;
726 die $@ if $@;
727 return 1;
728 }
729 return;
730 }
731
732 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
733 sub evaluate_gitweb_config {
734 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "gitweb_config.perl";
735 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "/etc/gitweb.conf";
736 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "/etc/gitweb-common.conf";
737
738 # Protect against duplications of file names, to not read config twice.
739 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
740 # there possibility of duplication of filename there doesn't matter.
741 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
742 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
743
744 # Common system-wide settings for convenience.
745 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
746 read_config_file($GITWEB_CONFIG_COMMON);
747
748 # Use first config file that exists. This means use the per-instance
749 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
750 read_config_file($GITWEB_CONFIG) and return;
751 read_config_file($GITWEB_CONFIG_SYSTEM);
752 }
753
754 # Get loadavg of system, to compare against $maxload.
755 # Currently it requires '/proc/loadavg' present to get loadavg;
756 # if it is not present it returns 0, which means no load checking.
757 sub get_loadavg {
758 if( -e '/proc/loadavg' ){
759 open my $fd, '<', '/proc/loadavg'
760 or return 0;
761 my @load = split(/\s+/, scalar <$fd>);
762 close $fd;
763
764 # The first three columns measure CPU and IO utilization of the last one,
765 # five, and 10 minute periods. The fourth column shows the number of
766 # currently running processes and the total number of processes in the m/n
767 # format. The last column displays the last process ID used.
768 return $load[0] || 0;
769 }
770 # additional checks for load average should go here for things that don't export
771 # /proc/loadavg
772
773 return 0;
774 }
775
776 # version of the core git binary
777 our $git_version;
778 sub evaluate_git_version {
779 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
780 $number_of_git_cmds++;
781 }
782
783 sub check_loadavg {
784 if (defined $maxload && get_loadavg() > $maxload) {
785 die_error(503, "The load average on the server is too high");
786 }
787 }
788
789 # ======================================================================
790 # input validation and dispatch
791
792 # input parameters can be collected from a variety of sources (presently, CGI
793 # and PATH_INFO), so we define an %input_params hash that collects them all
794 # together during validation: this allows subsequent uses (e.g. href()) to be
795 # agnostic of the parameter origin
796
797 our %input_params = ();
798
799 # input parameters are stored with the long parameter name as key. This will
800 # also be used in the href subroutine to convert parameters to their CGI
801 # equivalent, and since the href() usage is the most frequent one, we store
802 # the name -> CGI key mapping here, instead of the reverse.
803 #
804 # XXX: Warning: If you touch this, check the search form for updating,
805 # too.
806
807 our @cgi_param_mapping = (
808 project => "p",
809 action => "a",
810 file_name => "f",
811 file_parent => "fp",
812 hash => "h",
813 hash_parent => "hp",
814 hash_base => "hb",
815 hash_parent_base => "hpb",
816 page => "pg",
817 order => "o",
818 searchtext => "s",
819 searchtype => "st",
820 snapshot_format => "sf",
821 extra_options => "opt",
822 search_use_regexp => "sr",
823 ctag => "by_tag",
824 diff_style => "ds",
825 project_filter => "pf",
826 # this must be last entry (for manipulation from JavaScript)
827 javascript => "js"
828 );
829 our %cgi_param_mapping = @cgi_param_mapping;
830
831 # we will also need to know the possible actions, for validation
832 our %actions = (
833 "blame" => \&git_blame,
834 "blame_incremental" => \&git_blame_incremental,
835 "blame_data" => \&git_blame_data,
836 "blobdiff" => \&git_blobdiff,
837 "blobdiff_plain" => \&git_blobdiff_plain,
838 "blob" => \&git_blob,
839 "blob_plain" => \&git_blob_plain,
840 "commitdiff" => \&git_commitdiff,
841 "commitdiff_plain" => \&git_commitdiff_plain,
842 "commit" => \&git_commit,
843 "forks" => \&git_forks,
844 "heads" => \&git_heads,
845 "history" => \&git_history,
846 "log" => \&git_log,
847 "patch" => \&git_patch,
848 "patches" => \&git_patches,
849 "remotes" => \&git_remotes,
850 "rss" => \&git_rss,
851 "atom" => \&git_atom,
852 "search" => \&git_search,
853 "search_help" => \&git_search_help,
854 "shortlog" => \&git_shortlog,
855 "summary" => \&git_summary,
856 "tag" => \&git_tag,
857 "tags" => \&git_tags,
858 "tree" => \&git_tree,
859 "snapshot" => \&git_snapshot,
860 "object" => \&git_object,
861 # those below don't need $project
862 "opml" => \&git_opml,
863 "project_list" => \&git_project_list,
864 "project_index" => \&git_project_index,
865 );
866
867 # finally, we have the hash of allowed extra_options for the commands that
868 # allow them
869 our %allowed_options = (
870 "--no-merges" => [ qw(rss atom log shortlog history) ],
871 );
872
873 # fill %input_params with the CGI parameters. All values except for 'opt'
874 # should be single values, but opt can be an array. We should probably
875 # build an array of parameters that can be multi-valued, but since for the time
876 # being it's only this one, we just single it out
877 sub evaluate_query_params {
878 our $cgi;
879
880 while (my ($name, $symbol) = each %cgi_param_mapping) {
881 if ($symbol eq 'opt') {
882 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
883 } else {
884 $input_params{$name} = decode_utf8($cgi->param($symbol));
885 }
886 }
887 }
888
889 # now read PATH_INFO and update the parameter list for missing parameters
890 sub evaluate_path_info {
891 return if defined $input_params{'project'};
892 return if !$path_info;
893 $path_info =~ s,^/+,,;
894 return if !$path_info;
895
896 # find which part of PATH_INFO is project
897 my $project = $path_info;
898 $project =~ s,/+$,,;
899 while ($project && !check_head_link("$projectroot/$project")) {
900 $project =~ s,/*[^/]*$,,;
901 }
902 return unless $project;
903 $input_params{'project'} = $project;
904
905 # do not change any parameters if an action is given using the query string
906 return if $input_params{'action'};
907 $path_info =~ s,^\Q$project\E/*,,;
908
909 # next, check if we have an action
910 my $action = $path_info;
911 $action =~ s,/.*$,,;
912 if (exists $actions{$action}) {
913 $path_info =~ s,^$action/*,,;
914 $input_params{'action'} = $action;
915 }
916
917 # list of actions that want hash_base instead of hash, but can have no
918 # pathname (f) parameter
919 my @wants_base = (
920 'tree',
921 'history',
922 );
923
924 # we want to catch, among others
925 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
926 my ($parentrefname, $parentpathname, $refname, $pathname) =
927 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
928
929 # first, analyze the 'current' part
930 if (defined $pathname) {
931 # we got "branch:filename" or "branch:dir/"
932 # we could use git_get_type(branch:pathname), but:
933 # - it needs $git_dir
934 # - it does a git() call
935 # - the convention of terminating directories with a slash
936 # makes it superfluous
937 # - embedding the action in the PATH_INFO would make it even
938 # more superfluous
939 $pathname =~ s,^/+,,;
940 if (!$pathname || substr($pathname, -1) eq "/") {
941 $input_params{'action'} ||= "tree";
942 $pathname =~ s,/$,,;
943 } else {
944 # the default action depends on whether we had parent info
945 # or not
946 if ($parentrefname) {
947 $input_params{'action'} ||= "blobdiff_plain";
948 } else {
949 $input_params{'action'} ||= "blob_plain";
950 }
951 }
952 $input_params{'hash_base'} ||= $refname;
953 $input_params{'file_name'} ||= $pathname;
954 } elsif (defined $refname) {
955 # we got "branch". In this case we have to choose if we have to
956 # set hash or hash_base.
957 #
958 # Most of the actions without a pathname only want hash to be
959 # set, except for the ones specified in @wants_base that want
960 # hash_base instead. It should also be noted that hand-crafted
961 # links having 'history' as an action and no pathname or hash
962 # set will fail, but that happens regardless of PATH_INFO.
963 if (defined $parentrefname) {
964 # if there is parent let the default be 'shortlog' action
965 # (for http://git.example.com/repo.git/A..B links); if there
966 # is no parent, dispatch will detect type of object and set
967 # action appropriately if required (if action is not set)
968 $input_params{'action'} ||= "shortlog";
969 }
970 if ($input_params{'action'} &&
971 grep { $_ eq $input_params{'action'} } @wants_base) {
972 $input_params{'hash_base'} ||= $refname;
973 } else {
974 $input_params{'hash'} ||= $refname;
975 }
976 }
977
978 # next, handle the 'parent' part, if present
979 if (defined $parentrefname) {
980 # a missing pathspec defaults to the 'current' filename, allowing e.g.
981 # someproject/blobdiff/oldrev..newrev:/filename
982 if ($parentpathname) {
983 $parentpathname =~ s,^/+,,;
984 $parentpathname =~ s,/$,,;
985 $input_params{'file_parent'} ||= $parentpathname;
986 } else {
987 $input_params{'file_parent'} ||= $input_params{'file_name'};
988 }
989 # we assume that hash_parent_base is wanted if a path was specified,
990 # or if the action wants hash_base instead of hash
991 if (defined $input_params{'file_parent'} ||
992 grep { $_ eq $input_params{'action'} } @wants_base) {
993 $input_params{'hash_parent_base'} ||= $parentrefname;
994 } else {
995 $input_params{'hash_parent'} ||= $parentrefname;
996 }
997 }
998
999 # for the snapshot action, we allow URLs in the form
1000 # $project/snapshot/$hash.ext
1001 # where .ext determines the snapshot and gets removed from the
1002 # passed $refname to provide the $hash.
1003 #
1004 # To be able to tell that $refname includes the format extension, we
1005 # require the following two conditions to be satisfied:
1006 # - the hash input parameter MUST have been set from the $refname part
1007 # of the URL (i.e. they must be equal)
1008 # - the snapshot format MUST NOT have been defined already (e.g. from
1009 # CGI parameter sf)
1010 # It's also useless to try any matching unless $refname has a dot,
1011 # so we check for that too
1012 if (defined $input_params{'action'} &&
1013 $input_params{'action'} eq 'snapshot' &&
1014 defined $refname && index($refname, '.') != -1 &&
1015 $refname eq $input_params{'hash'} &&
1016 !defined $input_params{'snapshot_format'}) {
1017 # We loop over the known snapshot formats, checking for
1018 # extensions. Allowed extensions are both the defined suffix
1019 # (which includes the initial dot already) and the snapshot
1020 # format key itself, with a prepended dot
1021 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1022 my $hash = $refname;
1023 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1024 next;
1025 }
1026 my $sfx = $1;
1027 # a valid suffix was found, so set the snapshot format
1028 # and reset the hash parameter
1029 $input_params{'snapshot_format'} = $fmt;
1030 $input_params{'hash'} = $hash;
1031 # we also set the format suffix to the one requested
1032 # in the URL: this way a request for e.g. .tgz returns
1033 # a .tgz instead of a .tar.gz
1034 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1035 last;
1036 }
1037 }
1038 }
1039
1040 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1041 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1042 $searchtext, $search_regexp, $project_filter);
1043 sub evaluate_and_validate_params {
1044 our $action = $input_params{'action'};
1045 if (defined $action) {
1046 if (!is_valid_action($action)) {
1047 die_error(400, "Invalid action parameter");
1048 }
1049 }
1050
1051 # parameters which are pathnames
1052 our $project = $input_params{'project'};
1053 if (defined $project) {
1054 if (!is_valid_project($project)) {
1055 undef $project;
1056 die_error(404, "No such project");
1057 }
1058 }
1059
1060 our $project_filter = $input_params{'project_filter'};
1061 if (defined $project_filter) {
1062 if (!is_valid_pathname($project_filter)) {
1063 die_error(404, "Invalid project_filter parameter");
1064 }
1065 }
1066
1067 our $file_name = $input_params{'file_name'};
1068 if (defined $file_name) {
1069 if (!is_valid_pathname($file_name)) {
1070 die_error(400, "Invalid file parameter");
1071 }
1072 }
1073
1074 our $file_parent = $input_params{'file_parent'};
1075 if (defined $file_parent) {
1076 if (!is_valid_pathname($file_parent)) {
1077 die_error(400, "Invalid file parent parameter");
1078 }
1079 }
1080
1081 # parameters which are refnames
1082 our $hash = $input_params{'hash'};
1083 if (defined $hash) {
1084 if (!is_valid_refname($hash)) {
1085 die_error(400, "Invalid hash parameter");
1086 }
1087 }
1088
1089 our $hash_parent = $input_params{'hash_parent'};
1090 if (defined $hash_parent) {
1091 if (!is_valid_refname($hash_parent)) {
1092 die_error(400, "Invalid hash parent parameter");
1093 }
1094 }
1095
1096 our $hash_base = $input_params{'hash_base'};
1097 if (defined $hash_base) {
1098 if (!is_valid_refname($hash_base)) {
1099 die_error(400, "Invalid hash base parameter");
1100 }
1101 }
1102
1103 our @extra_options = @{$input_params{'extra_options'}};
1104 # @extra_options is always defined, since it can only be (currently) set from
1105 # CGI, and $cgi->param() returns the empty array in array context if the param
1106 # is not set
1107 foreach my $opt (@extra_options) {
1108 if (not exists $allowed_options{$opt}) {
1109 die_error(400, "Invalid option parameter");
1110 }
1111 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1112 die_error(400, "Invalid option parameter for this action");
1113 }
1114 }
1115
1116 our $hash_parent_base = $input_params{'hash_parent_base'};
1117 if (defined $hash_parent_base) {
1118 if (!is_valid_refname($hash_parent_base)) {
1119 die_error(400, "Invalid hash parent base parameter");
1120 }
1121 }
1122
1123 # other parameters
1124 our $page = $input_params{'page'};
1125 if (defined $page) {
1126 if ($page =~ m/[^0-9]/) {
1127 die_error(400, "Invalid page parameter");
1128 }
1129 }
1130
1131 our $searchtype = $input_params{'searchtype'};
1132 if (defined $searchtype) {
1133 if ($searchtype =~ m/[^a-z]/) {
1134 die_error(400, "Invalid searchtype parameter");
1135 }
1136 }
1137
1138 our $search_use_regexp = $input_params{'search_use_regexp'};
1139
1140 our $searchtext = $input_params{'searchtext'};
1141 our $search_regexp = undef;
1142 if (defined $searchtext) {
1143 if (length($searchtext) < 2) {
1144 die_error(403, "At least two characters are required for search parameter");
1145 }
1146 if ($search_use_regexp) {
1147 $search_regexp = $searchtext;
1148 if (!eval { qr/$search_regexp/; 1; }) {
1149 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1150 die_error(400, "Invalid search regexp '$search_regexp'",
1151 esc_html($error));
1152 }
1153 } else {
1154 $search_regexp = quotemeta $searchtext;
1155 }
1156 }
1157 }
1158
1159 # path to the current git repository
1160 our $git_dir;
1161 sub evaluate_git_dir {
1162 our $git_dir = "$projectroot/$project" if $project;
1163 }
1164
1165 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1166 sub configure_gitweb_features {
1167 # list of supported snapshot formats
1168 our @snapshot_fmts = gitweb_get_feature('snapshot');
1169 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1170
1171 # check that the avatar feature is set to a known provider name,
1172 # and for each provider check if the dependencies are satisfied.
1173 # if the provider name is invalid or the dependencies are not met,
1174 # reset $git_avatar to the empty string.
1175 our ($git_avatar) = gitweb_get_feature('avatar');
1176 if ($git_avatar eq 'gravatar') {
1177 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1178 } elsif ($git_avatar eq 'picon') {
1179 # no dependencies
1180 } else {
1181 $git_avatar = '';
1182 }
1183
1184 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1185 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1186 }
1187
1188 sub get_branch_refs {
1189 return ('heads', @extra_branch_refs);
1190 }
1191
1192 # custom error handler: 'die <message>' is Internal Server Error
1193 sub handle_errors_html {
1194 my $msg = shift; # it is already HTML escaped
1195
1196 # to avoid infinite loop where error occurs in die_error,
1197 # change handler to default handler, disabling handle_errors_html
1198 set_message("Error occurred when inside die_error:\n$msg");
1199
1200 # you cannot jump out of die_error when called as error handler;
1201 # the subroutine set via CGI::Carp::set_message is called _after_
1202 # HTTP headers are already written, so it cannot write them itself
1203 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1204 }
1205 set_message(\&handle_errors_html);
1206
1207 # dispatch
1208 sub dispatch {
1209 if (!defined $action) {
1210 if (defined $hash) {
1211 $action = git_get_type($hash);
1212 $action or die_error(404, "Object does not exist");
1213 } elsif (defined $hash_base && defined $file_name) {
1214 $action = git_get_type("$hash_base:$file_name");
1215 $action or die_error(404, "File or directory does not exist");
1216 } elsif (defined $project) {
1217 $action = 'summary';
1218 } else {
1219 $action = 'project_list';
1220 }
1221 }
1222 if (!defined($actions{$action})) {
1223 die_error(400, "Unknown action");
1224 }
1225 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1226 !$project) {
1227 die_error(400, "Project needed");
1228 }
1229 $actions{$action}->();
1230 }
1231
1232 sub reset_timer {
1233 our $t0 = [ gettimeofday() ]
1234 if defined $t0;
1235 our $number_of_git_cmds = 0;
1236 }
1237
1238 our $first_request = 1;
1239 sub run_request {
1240 reset_timer();
1241
1242 evaluate_uri();
1243 if ($first_request) {
1244 evaluate_gitweb_config();
1245 evaluate_git_version();
1246 }
1247 if ($per_request_config) {
1248 if (ref($per_request_config) eq 'CODE') {
1249 $per_request_config->();
1250 } elsif (!$first_request) {
1251 evaluate_gitweb_config();
1252 }
1253 }
1254 check_loadavg();
1255
1256 # $projectroot and $projects_list might be set in gitweb config file
1257 $projects_list ||= $projectroot;
1258
1259 evaluate_query_params();
1260 evaluate_path_info();
1261 evaluate_and_validate_params();
1262 evaluate_git_dir();
1263
1264 configure_gitweb_features();
1265
1266 dispatch();
1267 }
1268
1269 our $is_last_request = sub { 1 };
1270 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1271 our $CGI = 'CGI';
1272 our $cgi;
1273 sub configure_as_fcgi {
1274 require CGI::Fast;
1275 our $CGI = 'CGI::Fast';
1276
1277 my $request_number = 0;
1278 # let each child service 100 requests
1279 our $is_last_request = sub { ++$request_number > 100 };
1280 }
1281 sub evaluate_argv {
1282 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1283 configure_as_fcgi()
1284 if $script_name =~ /\.fcgi$/;
1285
1286 return unless (@ARGV);
1287
1288 require Getopt::Long;
1289 Getopt::Long::GetOptions(
1290 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1291 'nproc|n=i' => sub {
1292 my ($arg, $val) = @_;
1293 return unless eval { require FCGI::ProcManager; 1; };
1294 my $proc_manager = FCGI::ProcManager->new({
1295 n_processes => $val,
1296 });
1297 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1298 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1299 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1300 },
1301 );
1302 }
1303
1304 sub run {
1305 evaluate_argv();
1306
1307 $first_request = 1;
1308 $pre_listen_hook->()
1309 if $pre_listen_hook;
1310
1311 REQUEST:
1312 while ($cgi = $CGI->new()) {
1313 $pre_dispatch_hook->()
1314 if $pre_dispatch_hook;
1315
1316 run_request();
1317
1318 $post_dispatch_hook->()
1319 if $post_dispatch_hook;
1320 $first_request = 0;
1321
1322 last REQUEST if ($is_last_request->());
1323 }
1324
1325 DONE_GITWEB:
1326 1;
1327 }
1328
1329 run();
1330
1331 if (defined caller) {
1332 # wrapped in a subroutine processing requests,
1333 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1334 return;
1335 } else {
1336 # pure CGI script, serving single request
1337 exit;
1338 }
1339
1340 ## ======================================================================
1341 ## action links
1342
1343 # possible values of extra options
1344 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1345 # -replay => 1 - start from a current view (replay with modifications)
1346 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1347 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1348 sub href {
1349 my %params = @_;
1350 # default is to use -absolute url() i.e. $my_uri
1351 my $href = $params{-full} ? $my_url : $my_uri;
1352
1353 # implicit -replay, must be first of implicit params
1354 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1355
1356 $params{'project'} = $project unless exists $params{'project'};
1357
1358 if ($params{-replay}) {
1359 while (my ($name, $symbol) = each %cgi_param_mapping) {
1360 if (!exists $params{$name}) {
1361 $params{$name} = $input_params{$name};
1362 }
1363 }
1364 }
1365
1366 my $use_pathinfo = gitweb_check_feature('pathinfo');
1367 if (defined $params{'project'} &&
1368 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1369 # try to put as many parameters as possible in PATH_INFO:
1370 # - project name
1371 # - action
1372 # - hash_parent or hash_parent_base:/file_parent
1373 # - hash or hash_base:/filename
1374 # - the snapshot_format as an appropriate suffix
1375
1376 # When the script is the root DirectoryIndex for the domain,
1377 # $href here would be something like http://gitweb.example.com/
1378 # Thus, we strip any trailing / from $href, to spare us double
1379 # slashes in the final URL
1380 $href =~ s,/$,,;
1381
1382 # Then add the project name, if present
1383 $href .= "/".esc_path_info($params{'project'});
1384 delete $params{'project'};
1385
1386 # since we destructively absorb parameters, we keep this
1387 # boolean that remembers if we're handling a snapshot
1388 my $is_snapshot = $params{'action'} eq 'snapshot';
1389
1390 # Summary just uses the project path URL, any other action is
1391 # added to the URL
1392 if (defined $params{'action'}) {
1393 $href .= "/".esc_path_info($params{'action'})
1394 unless $params{'action'} eq 'summary';
1395 delete $params{'action'};
1396 }
1397
1398 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1399 # stripping nonexistent or useless pieces
1400 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1401 || $params{'hash_parent'} || $params{'hash'});
1402 if (defined $params{'hash_base'}) {
1403 if (defined $params{'hash_parent_base'}) {
1404 $href .= esc_path_info($params{'hash_parent_base'});
1405 # skip the file_parent if it's the same as the file_name
1406 if (defined $params{'file_parent'}) {
1407 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1408 delete $params{'file_parent'};
1409 } elsif ($params{'file_parent'} !~ /\.\./) {
1410 $href .= ":/".esc_path_info($params{'file_parent'});
1411 delete $params{'file_parent'};
1412 }
1413 }
1414 $href .= "..";
1415 delete $params{'hash_parent'};
1416 delete $params{'hash_parent_base'};
1417 } elsif (defined $params{'hash_parent'}) {
1418 $href .= esc_path_info($params{'hash_parent'}). "..";
1419 delete $params{'hash_parent'};
1420 }
1421
1422 $href .= esc_path_info($params{'hash_base'});
1423 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1424 $href .= ":/".esc_path_info($params{'file_name'});
1425 delete $params{'file_name'};
1426 }
1427 delete $params{'hash'};
1428 delete $params{'hash_base'};
1429 } elsif (defined $params{'hash'}) {
1430 $href .= esc_path_info($params{'hash'});
1431 delete $params{'hash'};
1432 }
1433
1434 # If the action was a snapshot, we can absorb the
1435 # snapshot_format parameter too
1436 if ($is_snapshot) {
1437 my $fmt = $params{'snapshot_format'};
1438 # snapshot_format should always be defined when href()
1439 # is called, but just in case some code forgets, we
1440 # fall back to the default
1441 $fmt ||= $snapshot_fmts[0];
1442 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1443 delete $params{'snapshot_format'};
1444 }
1445 }
1446
1447 # now encode the parameters explicitly
1448 my @result = ();
1449 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1450 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1451 if (defined $params{$name}) {
1452 if (ref($params{$name}) eq "ARRAY") {
1453 foreach my $par (@{$params{$name}}) {
1454 push @result, $symbol . "=" . esc_param($par);
1455 }
1456 } else {
1457 push @result, $symbol . "=" . esc_param($params{$name});
1458 }
1459 }
1460 }
1461 $href .= "?" . join(';', @result) if scalar @result;
1462
1463 # final transformation: trailing spaces must be escaped (URI-encoded)
1464 $href =~ s/(\s+)$/CGI::escape($1)/e;
1465
1466 if ($params{-anchor}) {
1467 $href .= "#".esc_param($params{-anchor});
1468 }
1469
1470 return $href;
1471 }
1472
1473
1474 ## ======================================================================
1475 ## validation, quoting/unquoting and escaping
1476
1477 sub is_valid_action {
1478 my $input = shift;
1479 return undef unless exists $actions{$input};
1480 return 1;
1481 }
1482
1483 sub is_valid_project {
1484 my $input = shift;
1485
1486 return unless defined $input;
1487 if (!is_valid_pathname($input) ||
1488 !(-d "$projectroot/$input") ||
1489 !check_export_ok("$projectroot/$input") ||
1490 ($strict_export && !project_in_list($input))) {
1491 return undef;
1492 } else {
1493 return 1;
1494 }
1495 }
1496
1497 sub is_valid_pathname {
1498 my $input = shift;
1499
1500 return undef unless defined $input;
1501 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1502 # at the beginning, at the end, and between slashes.
1503 # also this catches doubled slashes
1504 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1505 return undef;
1506 }
1507 # no null characters
1508 if ($input =~ m!\0!) {
1509 return undef;
1510 }
1511 return 1;
1512 }
1513
1514 sub is_valid_ref_format {
1515 my $input = shift;
1516
1517 return undef unless defined $input;
1518 # restrictions on ref name according to git-check-ref-format
1519 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1520 return undef;
1521 }
1522 return 1;
1523 }
1524
1525 sub is_valid_refname {
1526 my $input = shift;
1527
1528 return undef unless defined $input;
1529 # textual hashes are O.K.
1530 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1531 return 1;
1532 }
1533 # it must be correct pathname
1534 is_valid_pathname($input) or return undef;
1535 # check git-check-ref-format restrictions
1536 is_valid_ref_format($input) or return undef;
1537 return 1;
1538 }
1539
1540 # decode sequences of octets in utf8 into Perl's internal form,
1541 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1542 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1543 sub to_utf8 {
1544 my $str = shift;
1545 return undef unless defined $str;
1546
1547 if (utf8::is_utf8($str) || utf8::decode($str)) {
1548 return $str;
1549 } else {
1550 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1551 }
1552 }
1553
1554 # quote unsafe chars, but keep the slash, even when it's not
1555 # correct, but quoted slashes look too horrible in bookmarks
1556 sub esc_param {
1557 my $str = shift;
1558 return undef unless defined $str;
1559 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1560 $str =~ s/ /\+/g;
1561 return $str;
1562 }
1563
1564 # the quoting rules for path_info fragment are slightly different
1565 sub esc_path_info {
1566 my $str = shift;
1567 return undef unless defined $str;
1568
1569 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1570 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1571
1572 return $str;
1573 }
1574
1575 # quote unsafe chars in whole URL, so some characters cannot be quoted
1576 sub esc_url {
1577 my $str = shift;
1578 return undef unless defined $str;
1579 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1580 $str =~ s/ /\+/g;
1581 return $str;
1582 }
1583
1584 # quote unsafe characters in HTML attributes
1585 sub esc_attr {
1586
1587 # for XHTML conformance escaping '"' to '&quot;' is not enough
1588 return esc_html(@_);
1589 }
1590
1591 # replace invalid utf8 character with SUBSTITUTION sequence
1592 sub esc_html {
1593 my $str = shift;
1594 my %opts = @_;
1595
1596 return undef unless defined $str;
1597
1598 $str = to_utf8($str);
1599 $str = $cgi->escapeHTML($str);
1600 if ($opts{'-nbsp'}) {
1601 $str =~ s/ /&nbsp;/g;
1602 }
1603 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1604 return $str;
1605 }
1606
1607 # quote control characters and escape filename to HTML
1608 sub esc_path {
1609 my $str = shift;
1610 my %opts = @_;
1611
1612 return undef unless defined $str;
1613
1614 $str = to_utf8($str);
1615 $str = $cgi->escapeHTML($str);
1616 if ($opts{'-nbsp'}) {
1617 $str =~ s/ /&nbsp;/g;
1618 }
1619 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1620 return $str;
1621 }
1622
1623 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1624 sub sanitize {
1625 my $str = shift;
1626
1627 return undef unless defined $str;
1628
1629 $str = to_utf8($str);
1630 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1631 return $str;
1632 }
1633
1634 # Make control characters "printable", using character escape codes (CEC)
1635 sub quot_cec {
1636 my $cntrl = shift;
1637 my %opts = @_;
1638 my %es = ( # character escape codes, aka escape sequences
1639 "\t" => '\t', # tab (HT)
1640 "\n" => '\n', # line feed (LF)
1641 "\r" => '\r', # carrige return (CR)
1642 "\f" => '\f', # form feed (FF)
1643 "\b" => '\b', # backspace (BS)
1644 "\a" => '\a', # alarm (bell) (BEL)
1645 "\e" => '\e', # escape (ESC)
1646 "\013" => '\v', # vertical tab (VT)
1647 "\000" => '\0', # nul character (NUL)
1648 );
1649 my $chr = ( (exists $es{$cntrl})
1650 ? $es{$cntrl}
1651 : sprintf('\%2x', ord($cntrl)) );
1652 if ($opts{-nohtml}) {
1653 return $chr;
1654 } else {
1655 return "<span class=\"cntrl\">$chr</span>";
1656 }
1657 }
1658
1659 # Alternatively use unicode control pictures codepoints,
1660 # Unicode "printable representation" (PR)
1661 sub quot_upr {
1662 my $cntrl = shift;
1663 my %opts = @_;
1664
1665 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1666 if ($opts{-nohtml}) {
1667 return $chr;
1668 } else {
1669 return "<span class=\"cntrl\">$chr</span>";
1670 }
1671 }
1672
1673 # git may return quoted and escaped filenames
1674 sub unquote {
1675 my $str = shift;
1676
1677 sub unq {
1678 my $seq = shift;
1679 my %es = ( # character escape codes, aka escape sequences
1680 't' => "\t", # tab (HT, TAB)
1681 'n' => "\n", # newline (NL)
1682 'r' => "\r", # return (CR)
1683 'f' => "\f", # form feed (FF)
1684 'b' => "\b", # backspace (BS)
1685 'a' => "\a", # alarm (bell) (BEL)
1686 'e' => "\e", # escape (ESC)
1687 'v' => "\013", # vertical tab (VT)
1688 );
1689
1690 if ($seq =~ m/^[0-7]{1,3}$/) {
1691 # octal char sequence
1692 return chr(oct($seq));
1693 } elsif (exists $es{$seq}) {
1694 # C escape sequence, aka character escape code
1695 return $es{$seq};
1696 }
1697 # quoted ordinary character
1698 return $seq;
1699 }
1700
1701 if ($str =~ m/^"(.*)"$/) {
1702 # needs unquoting
1703 $str = $1;
1704 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1705 }
1706 return $str;
1707 }
1708
1709 # escape tabs (convert tabs to spaces)
1710 sub untabify {
1711 my $line = shift;
1712
1713 while ((my $pos = index($line, "\t")) != -1) {
1714 if (my $count = (8 - ($pos % 8))) {
1715 my $spaces = ' ' x $count;
1716 $line =~ s/\t/$spaces/;
1717 }
1718 }
1719
1720 return $line;
1721 }
1722
1723 sub project_in_list {
1724 my $project = shift;
1725 my @list = git_get_projects_list();
1726 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1727 }
1728
1729 ## ----------------------------------------------------------------------
1730 ## HTML aware string manipulation
1731
1732 # Try to chop given string on a word boundary between position
1733 # $len and $len+$add_len. If there is no word boundary there,
1734 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1735 # (marking chopped part) would be longer than given string.
1736 sub chop_str {
1737 my $str = shift;
1738 my $len = shift;
1739 my $add_len = shift || 10;
1740 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1741
1742 # Make sure perl knows it is utf8 encoded so we don't
1743 # cut in the middle of a utf8 multibyte char.
1744 $str = to_utf8($str);
1745
1746 # allow only $len chars, but don't cut a word if it would fit in $add_len
1747 # if it doesn't fit, cut it if it's still longer than the dots we would add
1748 # remove chopped character entities entirely
1749
1750 # when chopping in the middle, distribute $len into left and right part
1751 # return early if chopping wouldn't make string shorter
1752 if ($where eq 'center') {
1753 return $str if ($len + 5 >= length($str)); # filler is length 5
1754 $len = int($len/2);
1755 } else {
1756 return $str if ($len + 4 >= length($str)); # filler is length 4
1757 }
1758
1759 # regexps: ending and beginning with word part up to $add_len
1760 my $endre = qr/.{$len}\w{0,$add_len}/;
1761 my $begre = qr/\w{0,$add_len}.{$len}/;
1762
1763 if ($where eq 'left') {
1764 $str =~ m/^(.*?)($begre)$/;
1765 my ($lead, $body) = ($1, $2);
1766 if (length($lead) > 4) {
1767 $lead = " ...";
1768 }
1769 return "$lead$body";
1770
1771 } elsif ($where eq 'center') {
1772 $str =~ m/^($endre)(.*)$/;
1773 my ($left, $str) = ($1, $2);
1774 $str =~ m/^(.*?)($begre)$/;
1775 my ($mid, $right) = ($1, $2);
1776 if (length($mid) > 5) {
1777 $mid = " ... ";
1778 }
1779 return "$left$mid$right";
1780
1781 } else {
1782 $str =~ m/^($endre)(.*)$/;
1783 my $body = $1;
1784 my $tail = $2;
1785 if (length($tail) > 4) {
1786 $tail = "... ";
1787 }
1788 return "$body$tail";
1789 }
1790 }
1791
1792 # takes the same arguments as chop_str, but also wraps a <span> around the
1793 # result with a title attribute if it does get chopped. Additionally, the
1794 # string is HTML-escaped.
1795 sub chop_and_escape_str {
1796 my ($str) = @_;
1797
1798 my $chopped = chop_str(@_);
1799 $str = to_utf8($str);
1800 if ($chopped eq $str) {
1801 return esc_html($chopped);
1802 } else {
1803 $str =~ s/[[:cntrl:]]/?/g;
1804 return $cgi->span({-title=>$str}, esc_html($chopped));
1805 }
1806 }
1807
1808 # Highlight selected fragments of string, using given CSS class,
1809 # and escape HTML. It is assumed that fragments do not overlap.
1810 # Regions are passed as list of pairs (array references).
1811 #
1812 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1813 # '<span class="mark">foo</span>bar'
1814 sub esc_html_hl_regions {
1815 my ($str, $css_class, @sel) = @_;
1816 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1817 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1818 return esc_html($str, %opts) unless @sel;
1819
1820 my $out = '';
1821 my $pos = 0;
1822
1823 for my $s (@sel) {
1824 my ($begin, $end) = @$s;
1825
1826 # Don't create empty <span> elements.
1827 next if $end <= $begin;
1828
1829 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1830 %opts);
1831
1832 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1833 if ($begin - $pos > 0);
1834 $out .= $cgi->span({-class => $css_class}, $escaped);
1835
1836 $pos = $end;
1837 }
1838 $out .= esc_html(substr($str, $pos), %opts)
1839 if ($pos < length($str));
1840
1841 return $out;
1842 }
1843
1844 # return positions of beginning and end of each match
1845 sub matchpos_list {
1846 my ($str, $regexp) = @_;
1847 return unless (defined $str && defined $regexp);
1848
1849 my @matches;
1850 while ($str =~ /$regexp/g) {
1851 push @matches, [$-[0], $+[0]];
1852 }
1853 return @matches;
1854 }
1855
1856 # highlight match (if any), and escape HTML
1857 sub esc_html_match_hl {
1858 my ($str, $regexp) = @_;
1859 return esc_html($str) unless defined $regexp;
1860
1861 my @matches = matchpos_list($str, $regexp);
1862 return esc_html($str) unless @matches;
1863
1864 return esc_html_hl_regions($str, 'match', @matches);
1865 }
1866
1867
1868 # highlight match (if any) of shortened string, and escape HTML
1869 sub esc_html_match_hl_chopped {
1870 my ($str, $chopped, $regexp) = @_;
1871 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1872
1873 my @matches = matchpos_list($str, $regexp);
1874 return esc_html($chopped) unless @matches;
1875
1876 # filter matches so that we mark chopped string
1877 my $tail = "... "; # see chop_str
1878 unless ($chopped =~ s/\Q$tail\E$//) {
1879 $tail = '';
1880 }
1881 my $chop_len = length($chopped);
1882 my $tail_len = length($tail);
1883 my @filtered;
1884
1885 for my $m (@matches) {
1886 if ($m->[0] > $chop_len) {
1887 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1888 last;
1889 } elsif ($m->[1] > $chop_len) {
1890 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1891 last;
1892 }
1893 push @filtered, $m;
1894 }
1895
1896 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1897 }
1898
1899 ## ----------------------------------------------------------------------
1900 ## functions returning short strings
1901
1902 # CSS class for given age value (in seconds)
1903 sub age_class {
1904 my $age = shift;
1905
1906 if (!defined $age) {
1907 return "noage";
1908 } elsif ($age < 60*60*2) {
1909 return "age0";
1910 } elsif ($age < 60*60*24*2) {
1911 return "age1";
1912 } else {
1913 return "age2";
1914 }
1915 }
1916
1917 # convert age in seconds to "nn units ago" string
1918 sub age_string {
1919 my $age = shift;
1920 my $age_str;
1921
1922 if ($age > 60*60*24*365*2) {
1923 $age_str = (int $age/60/60/24/365);
1924 $age_str .= " years ago";
1925 } elsif ($age > 60*60*24*(365/12)*2) {
1926 $age_str = int $age/60/60/24/(365/12);
1927 $age_str .= " months ago";
1928 } elsif ($age > 60*60*24*7*2) {
1929 $age_str = int $age/60/60/24/7;
1930 $age_str .= " weeks ago";
1931 } elsif ($age > 60*60*24*2) {
1932 $age_str = int $age/60/60/24;
1933 $age_str .= " days ago";
1934 } elsif ($age > 60*60*2) {
1935 $age_str = int $age/60/60;
1936 $age_str .= " hours ago";
1937 } elsif ($age > 60*2) {
1938 $age_str = int $age/60;
1939 $age_str .= " min ago";
1940 } elsif ($age > 2) {
1941 $age_str = int $age;
1942 $age_str .= " sec ago";
1943 } else {
1944 $age_str .= " right now";
1945 }
1946 return $age_str;
1947 }
1948
1949 use constant {
1950 S_IFINVALID => 0030000,
1951 S_IFGITLINK => 0160000,
1952 };
1953
1954 # submodule/subproject, a commit object reference
1955 sub S_ISGITLINK {
1956 my $mode = shift;
1957
1958 return (($mode & S_IFMT) == S_IFGITLINK)
1959 }
1960
1961 # convert file mode in octal to symbolic file mode string
1962 sub mode_str {
1963 my $mode = oct shift;
1964
1965 if (S_ISGITLINK($mode)) {
1966 return 'm---------';
1967 } elsif (S_ISDIR($mode & S_IFMT)) {
1968 return 'drwxr-xr-x';
1969 } elsif (S_ISLNK($mode)) {
1970 return 'lrwxrwxrwx';
1971 } elsif (S_ISREG($mode)) {
1972 # git cares only about the executable bit
1973 if ($mode & S_IXUSR) {
1974 return '-rwxr-xr-x';
1975 } else {
1976 return '-rw-r--r--';
1977 };
1978 } else {
1979 return '----------';
1980 }
1981 }
1982
1983 # convert file mode in octal to file type string
1984 sub file_type {
1985 my $mode = shift;
1986
1987 if ($mode !~ m/^[0-7]+$/) {
1988 return $mode;
1989 } else {
1990 $mode = oct $mode;
1991 }
1992
1993 if (S_ISGITLINK($mode)) {
1994 return "submodule";
1995 } elsif (S_ISDIR($mode & S_IFMT)) {
1996 return "directory";
1997 } elsif (S_ISLNK($mode)) {
1998 return "symlink";
1999 } elsif (S_ISREG($mode)) {
2000 return "file";
2001 } else {
2002 return "unknown";
2003 }
2004 }
2005
2006 # convert file mode in octal to file type description string
2007 sub file_type_long {
2008 my $mode = shift;
2009
2010 if ($mode !~ m/^[0-7]+$/) {
2011 return $mode;
2012 } else {
2013 $mode = oct $mode;
2014 }
2015
2016 if (S_ISGITLINK($mode)) {
2017 return "submodule";
2018 } elsif (S_ISDIR($mode & S_IFMT)) {
2019 return "directory";
2020 } elsif (S_ISLNK($mode)) {
2021 return "symlink";
2022 } elsif (S_ISREG($mode)) {
2023 if ($mode & S_IXUSR) {
2024 return "executable";
2025 } else {
2026 return "file";
2027 };
2028 } else {
2029 return "unknown";
2030 }
2031 }
2032
2033
2034 ## ----------------------------------------------------------------------
2035 ## functions returning short HTML fragments, or transforming HTML fragments
2036 ## which don't belong to other sections
2037
2038 # format line of commit message.
2039 sub format_log_line_html {
2040 my $line = shift;
2041
2042 $line = esc_html($line, -nbsp=>1);
2043 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2044 $cgi->a({-href => href(action=>"object", hash=>$1),
2045 -class => "text"}, $1);
2046 }eg;
2047
2048 return $line;
2049 }
2050
2051 # format marker of refs pointing to given object
2052
2053 # the destination action is chosen based on object type and current context:
2054 # - for annotated tags, we choose the tag view unless it's the current view
2055 # already, in which case we go to shortlog view
2056 # - for other refs, we keep the current view if we're in history, shortlog or
2057 # log view, and select shortlog otherwise
2058 sub format_ref_marker {
2059 my ($refs, $id) = @_;
2060 my $markers = '';
2061
2062 if (defined $refs->{$id}) {
2063 foreach my $ref (@{$refs->{$id}}) {
2064 # this code exploits the fact that non-lightweight tags are the
2065 # only indirect objects, and that they are the only objects for which
2066 # we want to use tag instead of shortlog as action
2067 my ($type, $name) = qw();
2068 my $indirect = ($ref =~ s/\^\{\}$//);
2069 # e.g. tags/v2.6.11 or heads/next
2070 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2071 $type = $1;
2072 $name = $2;
2073 } else {
2074 $type = "ref";
2075 $name = $ref;
2076 }
2077
2078 my $class = $type;
2079 $class .= " indirect" if $indirect;
2080
2081 my $dest_action = "shortlog";
2082
2083 if ($indirect) {
2084 $dest_action = "tag" unless $action eq "tag";
2085 } elsif ($action =~ /^(history|(short)?log)$/) {
2086 $dest_action = $action;
2087 }
2088
2089 my $dest = "";
2090 $dest .= "refs/" unless $ref =~ m!^refs/!;
2091 $dest .= $ref;
2092
2093 my $link = $cgi->a({
2094 -href => href(
2095 action=>$dest_action,
2096 hash=>$dest
2097 )}, $name);
2098
2099 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2100 $link . "</span>";
2101 }
2102 }
2103
2104 if ($markers) {
2105 return ' <span class="refs">'. $markers . '</span>';
2106 } else {
2107 return "";
2108 }
2109 }
2110
2111 # format, perhaps shortened and with markers, title line
2112 sub format_subject_html {
2113 my ($long, $short, $href, $extra) = @_;
2114 $extra = '' unless defined($extra);
2115
2116 if (length($short) < length($long)) {
2117 $long =~ s/[[:cntrl:]]/?/g;
2118 return $cgi->a({-href => $href, -class => "list subject",
2119 -title => to_utf8($long)},
2120 esc_html($short)) . $extra;
2121 } else {
2122 return $cgi->a({-href => $href, -class => "list subject"},
2123 esc_html($long)) . $extra;
2124 }
2125 }
2126
2127 # Rather than recomputing the url for an email multiple times, we cache it
2128 # after the first hit. This gives a visible benefit in views where the avatar
2129 # for the same email is used repeatedly (e.g. shortlog).
2130 # The cache is shared by all avatar engines (currently gravatar only), which
2131 # are free to use it as preferred. Since only one avatar engine is used for any
2132 # given page, there's no risk for cache conflicts.
2133 our %avatar_cache = ();
2134
2135 # Compute the picon url for a given email, by using the picon search service over at
2136 # http://www.cs.indiana.edu/picons/search.html
2137 sub picon_url {
2138 my $email = lc shift;
2139 if (!$avatar_cache{$email}) {
2140 my ($user, $domain) = split('@', $email);
2141 $avatar_cache{$email} =
2142 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2143 "$domain/$user/" .
2144 "users+domains+unknown/up/single";
2145 }
2146 return $avatar_cache{$email};
2147 }
2148
2149 # Compute the gravatar url for a given email, if it's not in the cache already.
2150 # Gravatar stores only the part of the URL before the size, since that's the
2151 # one computationally more expensive. This also allows reuse of the cache for
2152 # different sizes (for this particular engine).
2153 sub gravatar_url {
2154 my $email = lc shift;
2155 my $size = shift;
2156 $avatar_cache{$email} ||=
2157 "//www.gravatar.com/avatar/" .
2158 Digest::MD5::md5_hex($email) . "?s=";
2159 return $avatar_cache{$email} . $size;
2160 }
2161
2162 # Insert an avatar for the given $email at the given $size if the feature
2163 # is enabled.
2164 sub git_get_avatar {
2165 my ($email, %opts) = @_;
2166 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2167 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2168 $opts{-size} ||= 'default';
2169 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2170 my $url = "";
2171 if ($git_avatar eq 'gravatar') {
2172 $url = gravatar_url($email, $size);
2173 } elsif ($git_avatar eq 'picon') {
2174 $url = picon_url($email);
2175 }
2176 # Other providers can be added by extending the if chain, defining $url
2177 # as needed. If no variant puts something in $url, we assume avatars
2178 # are completely disabled/unavailable.
2179 if ($url) {
2180 return $pre_white .
2181 "<img width=\"$size\" " .
2182 "class=\"avatar\" " .
2183 "src=\"".esc_url($url)."\" " .
2184 "alt=\"\" " .
2185 "/>" . $post_white;
2186 } else {
2187 return "";
2188 }
2189 }
2190
2191 sub format_search_author {
2192 my ($author, $searchtype, $displaytext) = @_;
2193 my $have_search = gitweb_check_feature('search');
2194
2195 if ($have_search) {
2196 my $performed = "";
2197 if ($searchtype eq 'author') {
2198 $performed = "authored";
2199 } elsif ($searchtype eq 'committer') {
2200 $performed = "committed";
2201 }
2202
2203 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2204 searchtext=>$author,
2205 searchtype=>$searchtype), class=>"list",
2206 title=>"Search for commits $performed by $author"},
2207 $displaytext);
2208
2209 } else {
2210 return $displaytext;
2211 }
2212 }
2213
2214 # format the author name of the given commit with the given tag
2215 # the author name is chopped and escaped according to the other
2216 # optional parameters (see chop_str).
2217 sub format_author_html {
2218 my $tag = shift;
2219 my $co = shift;
2220 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2221 return "<$tag class=\"author\">" .
2222 format_search_author($co->{'author_name'}, "author",
2223 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2224 $author) .
2225 "</$tag>";
2226 }
2227
2228 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2229 sub format_git_diff_header_line {
2230 my $line = shift;
2231 my $diffinfo = shift;
2232 my ($from, $to) = @_;
2233
2234 if ($diffinfo->{'nparents'}) {
2235 # combined diff
2236 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2237 if ($to->{'href'}) {
2238 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2239 esc_path($to->{'file'}));
2240 } else { # file was deleted (no href)
2241 $line .= esc_path($to->{'file'});
2242 }
2243 } else {
2244 # "ordinary" diff
2245 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2246 if ($from->{'href'}) {
2247 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2248 'a/' . esc_path($from->{'file'}));
2249 } else { # file was added (no href)
2250 $line .= 'a/' . esc_path($from->{'file'});
2251 }
2252 $line .= ' ';
2253 if ($to->{'href'}) {
2254 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2255 'b/' . esc_path($to->{'file'}));
2256 } else { # file was deleted
2257 $line .= 'b/' . esc_path($to->{'file'});
2258 }
2259 }
2260
2261 return "<div class=\"diff header\">$line</div>\n";
2262 }
2263
2264 # format extended diff header line, before patch itself
2265 sub format_extended_diff_header_line {
2266 my $line = shift;
2267 my $diffinfo = shift;
2268 my ($from, $to) = @_;
2269
2270 # match <path>
2271 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2272 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2273 esc_path($from->{'file'}));
2274 }
2275 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2276 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2277 esc_path($to->{'file'}));
2278 }
2279 # match single <mode>
2280 if ($line =~ m/\s(\d{6})$/) {
2281 $line .= '<span class="info"> (' .
2282 file_type_long($1) .
2283 ')</span>';
2284 }
2285 # match <hash>
2286 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2287 # can match only for combined diff
2288 $line = 'index ';
2289 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2290 if ($from->{'href'}[$i]) {
2291 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2292 -class=>"hash"},
2293 substr($diffinfo->{'from_id'}[$i],0,7));
2294 } else {
2295 $line .= '0' x 7;
2296 }
2297 # separator
2298 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2299 }
2300 $line .= '..';
2301 if ($to->{'href'}) {
2302 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2303 substr($diffinfo->{'to_id'},0,7));
2304 } else {
2305 $line .= '0' x 7;
2306 }
2307
2308 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2309 # can match only for ordinary diff
2310 my ($from_link, $to_link);
2311 if ($from->{'href'}) {
2312 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2313 substr($diffinfo->{'from_id'},0,7));
2314 } else {
2315 $from_link = '0' x 7;
2316 }
2317 if ($to->{'href'}) {
2318 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2319 substr($diffinfo->{'to_id'},0,7));
2320 } else {
2321 $to_link = '0' x 7;
2322 }
2323 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2324 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2325 }
2326
2327 return $line . "<br/>\n";
2328 }
2329
2330 # format from-file/to-file diff header
2331 sub format_diff_from_to_header {
2332 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2333 my $line;
2334 my $result = '';
2335
2336 $line = $from_line;
2337 #assert($line =~ m/^---/) if DEBUG;
2338 # no extra formatting for "^--- /dev/null"
2339 if (! $diffinfo->{'nparents'}) {
2340 # ordinary (single parent) diff
2341 if ($line =~ m!^--- "?a/!) {
2342 if ($from->{'href'}) {
2343 $line = '--- a/' .
2344 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2345 esc_path($from->{'file'}));
2346 } else {
2347 $line = '--- a/' .
2348 esc_path($from->{'file'});
2349 }
2350 }
2351 $result .= qq!<div class="diff from_file">$line</div>\n!;
2352
2353 } else {
2354 # combined diff (merge commit)
2355 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2356 if ($from->{'href'}[$i]) {
2357 $line = '--- ' .
2358 $cgi->a({-href=>href(action=>"blobdiff",
2359 hash_parent=>$diffinfo->{'from_id'}[$i],
2360 hash_parent_base=>$parents[$i],
2361 file_parent=>$from->{'file'}[$i],
2362 hash=>$diffinfo->{'to_id'},
2363 hash_base=>$hash,
2364 file_name=>$to->{'file'}),
2365 -class=>"path",
2366 -title=>"diff" . ($i+1)},
2367 $i+1) .
2368 '/' .
2369 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2370 esc_path($from->{'file'}[$i]));
2371 } else {
2372 $line = '--- /dev/null';
2373 }
2374 $result .= qq!<div class="diff from_file">$line</div>\n!;
2375 }
2376 }
2377
2378 $line = $to_line;
2379 #assert($line =~ m/^\+\+\+/) if DEBUG;
2380 # no extra formatting for "^+++ /dev/null"
2381 if ($line =~ m!^\+\+\+ "?b/!) {
2382 if ($to->{'href'}) {
2383 $line = '+++ b/' .
2384 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2385 esc_path($to->{'file'}));
2386 } else {
2387 $line = '+++ b/' .
2388 esc_path($to->{'file'});
2389 }
2390 }
2391 $result .= qq!<div class="diff to_file">$line</div>\n!;
2392
2393 return $result;
2394 }
2395
2396 # create note for patch simplified by combined diff
2397 sub format_diff_cc_simplified {
2398 my ($diffinfo, @parents) = @_;
2399 my $result = '';
2400
2401 $result .= "<div class=\"diff header\">" .
2402 "diff --cc ";
2403 if (!is_deleted($diffinfo)) {
2404 $result .= $cgi->a({-href => href(action=>"blob",
2405 hash_base=>$hash,
2406 hash=>$diffinfo->{'to_id'},
2407 file_name=>$diffinfo->{'to_file'}),
2408 -class => "path"},
2409 esc_path($diffinfo->{'to_file'}));
2410 } else {
2411 $result .= esc_path($diffinfo->{'to_file'});
2412 }
2413 $result .= "</div>\n" . # class="diff header"
2414 "<div class=\"diff nodifferences\">" .
2415 "Simple merge" .
2416 "</div>\n"; # class="diff nodifferences"
2417
2418 return $result;
2419 }
2420
2421 sub diff_line_class {
2422 my ($line, $from, $to) = @_;
2423
2424 # ordinary diff
2425 my $num_sign = 1;
2426 # combined diff
2427 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2428 $num_sign = scalar @{$from->{'href'}};
2429 }
2430
2431 my @diff_line_classifier = (
2432 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2433 { regexp => qr/^\\/, class => "incomplete" },
2434 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2435 # classifier for context must come before classifier add/rem,
2436 # or we would have to use more complicated regexp, for example
2437 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2438 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2439 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2440 );
2441 for my $clsfy (@diff_line_classifier) {
2442 return $clsfy->{'class'}
2443 if ($line =~ $clsfy->{'regexp'});
2444 }
2445
2446 # fallback
2447 return "";
2448 }
2449
2450 # assumes that $from and $to are defined and correctly filled,
2451 # and that $line holds a line of chunk header for unified diff
2452 sub format_unidiff_chunk_header {
2453 my ($line, $from, $to) = @_;
2454
2455 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2456 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2457
2458 $from_lines = 0 unless defined $from_lines;
2459 $to_lines = 0 unless defined $to_lines;
2460
2461 if ($from->{'href'}) {
2462 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2463 -class=>"list"}, $from_text);
2464 }
2465 if ($to->{'href'}) {
2466 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2467 -class=>"list"}, $to_text);
2468 }
2469 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2470 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2471 return $line;
2472 }
2473
2474 # assumes that $from and $to are defined and correctly filled,
2475 # and that $line holds a line of chunk header for combined diff
2476 sub format_cc_diff_chunk_header {
2477 my ($line, $from, $to) = @_;
2478
2479 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2480 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2481
2482 @from_text = split(' ', $ranges);
2483 for (my $i = 0; $i < @from_text; ++$i) {
2484 ($from_start[$i], $from_nlines[$i]) =
2485 (split(',', substr($from_text[$i], 1)), 0);
2486 }
2487
2488 $to_text = pop @from_text;
2489 $to_start = pop @from_start;
2490 $to_nlines = pop @from_nlines;
2491
2492 $line = "<span class=\"chunk_info\">$prefix ";
2493 for (my $i = 0; $i < @from_text; ++$i) {
2494 if ($from->{'href'}[$i]) {
2495 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2496 -class=>"list"}, $from_text[$i]);
2497 } else {
2498 $line .= $from_text[$i];
2499 }
2500 $line .= " ";
2501 }
2502 if ($to->{'href'}) {
2503 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2504 -class=>"list"}, $to_text);
2505 } else {
2506 $line .= $to_text;
2507 }
2508 $line .= " $prefix</span>" .
2509 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2510 return $line;
2511 }
2512
2513 # process patch (diff) line (not to be used for diff headers),
2514 # returning HTML-formatted (but not wrapped) line.
2515 # If the line is passed as a reference, it is treated as HTML and not
2516 # esc_html()'ed.
2517 sub format_diff_line {
2518 my ($line, $diff_class, $from, $to) = @_;
2519
2520 if (ref($line)) {
2521 $line = $$line;
2522 } else {
2523 chomp $line;
2524 $line = untabify($line);
2525
2526 if ($from && $to && $line =~ m/^\@{2} /) {
2527 $line = format_unidiff_chunk_header($line, $from, $to);
2528 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2529 $line = format_cc_diff_chunk_header($line, $from, $to);
2530 } else {
2531 $line = esc_html($line, -nbsp=>1);
2532 }
2533 }
2534
2535 my $diff_classes = "diff";
2536 $diff_classes .= " $diff_class" if ($diff_class);
2537 $line = "<div class=\"$diff_classes\">$line</div>\n";
2538
2539 return $line;
2540 }
2541
2542 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2543 # linked. Pass the hash of the tree/commit to snapshot.
2544 sub format_snapshot_links {
2545 my ($hash) = @_;
2546 my $num_fmts = @snapshot_fmts;
2547 if ($num_fmts > 1) {
2548 # A parenthesized list of links bearing format names.
2549 # e.g. "snapshot (_tar.gz_ _zip_)"
2550 return "snapshot (" . join(' ', map
2551 $cgi->a({
2552 -href => href(
2553 action=>"snapshot",
2554 hash=>$hash,
2555 snapshot_format=>$_
2556 )
2557 }, $known_snapshot_formats{$_}{'display'})
2558 , @snapshot_fmts) . ")";
2559 } elsif ($num_fmts == 1) {
2560 # A single "snapshot" link whose tooltip bears the format name.
2561 # i.e. "_snapshot_"
2562 my ($fmt) = @snapshot_fmts;
2563 return
2564 $cgi->a({
2565 -href => href(
2566 action=>"snapshot",
2567 hash=>$hash,
2568 snapshot_format=>$fmt
2569 ),
2570 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2571 }, "snapshot");
2572 } else { # $num_fmts == 0
2573 return undef;
2574 }
2575 }
2576
2577 ## ......................................................................
2578 ## functions returning values to be passed, perhaps after some
2579 ## transformation, to other functions; e.g. returning arguments to href()
2580
2581 # returns hash to be passed to href to generate gitweb URL
2582 # in -title key it returns description of link
2583 sub get_feed_info {
2584 my $format = shift || 'Atom';
2585 my %res = (action => lc($format));
2586 my $matched_ref = 0;
2587
2588 # feed links are possible only for project views
2589 return unless (defined $project);
2590 # some views should link to OPML, or to generic project feed,
2591 # or don't have specific feed yet (so they should use generic)
2592 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2593
2594 my $branch = undef;
2595 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2596 # (fullname) to differentiate from tag links; this also makes
2597 # possible to detect branch links
2598 for my $ref (get_branch_refs()) {
2599 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2600 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2601 $branch = $1;
2602 $matched_ref = $ref;
2603 last;
2604 }
2605 }
2606 # find log type for feed description (title)
2607 my $type = 'log';
2608 if (defined $file_name) {
2609 $type = "history of $file_name";
2610 $type .= "/" if ($action eq 'tree');
2611 $type .= " on '$branch'" if (defined $branch);
2612 } else {
2613 $type = "log of $branch" if (defined $branch);
2614 }
2615
2616 $res{-title} = $type;
2617 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2618 $res{'file_name'} = $file_name;
2619
2620 return %res;
2621 }
2622
2623 ## ----------------------------------------------------------------------
2624 ## git utility subroutines, invoking git commands
2625
2626 # returns path to the core git executable and the --git-dir parameter as list
2627 sub git_cmd {
2628 $number_of_git_cmds++;
2629 return $GIT, '--git-dir='.$git_dir;
2630 }
2631
2632 # quote the given arguments for passing them to the shell
2633 # quote_command("command", "arg 1", "arg with ' and ! characters")
2634 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2635 # Try to avoid using this function wherever possible.
2636 sub quote_command {
2637 return join(' ',
2638 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2639 }
2640
2641 # get HEAD ref of given project as hash
2642 sub git_get_head_hash {
2643 return git_get_full_hash(shift, 'HEAD');
2644 }
2645
2646 sub git_get_full_hash {
2647 return git_get_hash(@_);
2648 }
2649
2650 sub git_get_short_hash {
2651 return git_get_hash(@_, '--short=7');
2652 }
2653
2654 sub git_get_hash {
2655 my ($project, $hash, @options) = @_;
2656 my $o_git_dir = $git_dir;
2657 my $retval = undef;
2658 $git_dir = "$projectroot/$project";
2659 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2660 '--verify', '-q', @options, $hash) {
2661 $retval = <$fd>;
2662 chomp $retval if defined $retval;
2663 close $fd;
2664 }
2665 if (defined $o_git_dir) {
2666 $git_dir = $o_git_dir;
2667 }
2668 return $retval;
2669 }
2670
2671 # get type of given object
2672 sub git_get_type {
2673 my $hash = shift;
2674
2675 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2676 my $type = <$fd>;
2677 close $fd or return;
2678 chomp $type;
2679 return $type;
2680 }
2681
2682 # repository configuration
2683 our $config_file = '';
2684 our %config;
2685
2686 # store multiple values for single key as anonymous array reference
2687 # single values stored directly in the hash, not as [ <value> ]
2688 sub hash_set_multi {
2689 my ($hash, $key, $value) = @_;
2690
2691 if (!exists $hash->{$key}) {
2692 $hash->{$key} = $value;
2693 } elsif (!ref $hash->{$key}) {
2694 $hash->{$key} = [ $hash->{$key}, $value ];
2695 } else {
2696 push @{$hash->{$key}}, $value;
2697 }
2698 }
2699
2700 # return hash of git project configuration
2701 # optionally limited to some section, e.g. 'gitweb'
2702 sub git_parse_project_config {
2703 my $section_regexp = shift;
2704 my %config;
2705
2706 local $/ = "\0";
2707
2708 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2709 or return;
2710
2711 while (my $keyval = <$fh>) {
2712 chomp $keyval;
2713 my ($key, $value) = split(/\n/, $keyval, 2);
2714
2715 hash_set_multi(\%config, $key, $value)
2716 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2717 }
2718 close $fh;
2719
2720 return %config;
2721 }
2722
2723 # convert config value to boolean: 'true' or 'false'
2724 # no value, number > 0, 'true' and 'yes' values are true
2725 # rest of values are treated as false (never as error)
2726 sub config_to_bool {
2727 my $val = shift;
2728
2729 return 1 if !defined $val; # section.key
2730
2731 # strip leading and trailing whitespace
2732 $val =~ s/^\s+//;
2733 $val =~ s/\s+$//;
2734
2735 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2736 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2737 }
2738
2739 # convert config value to simple decimal number
2740 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2741 # to be multiplied by 1024, 1048576, or 1073741824
2742 sub config_to_int {
2743 my $val = shift;
2744
2745 # strip leading and trailing whitespace
2746 $val =~ s/^\s+//;
2747 $val =~ s/\s+$//;
2748
2749 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2750 $unit = lc($unit);
2751 # unknown unit is treated as 1
2752 return $num * ($unit eq 'g' ? 1073741824 :
2753 $unit eq 'm' ? 1048576 :
2754 $unit eq 'k' ? 1024 : 1);
2755 }
2756 return $val;
2757 }
2758
2759 # convert config value to array reference, if needed
2760 sub config_to_multi {
2761 my $val = shift;
2762
2763 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2764 }
2765
2766 sub git_get_project_config {
2767 my ($key, $type) = @_;
2768
2769 return unless defined $git_dir;
2770
2771 # key sanity check
2772 return unless ($key);
2773 # only subsection, if exists, is case sensitive,
2774 # and not lowercased by 'git config -z -l'
2775 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2776 $lo =~ s/_//g;
2777 $key = join(".", lc($hi), $mi, lc($lo));
2778 return if ($lo =~ /\W/ || $hi =~ /\W/);
2779 } else {
2780 $key = lc($key);
2781 $key =~ s/_//g;
2782 return if ($key =~ /\W/);
2783 }
2784 $key =~ s/^gitweb\.//;
2785
2786 # type sanity check
2787 if (defined $type) {
2788 $type =~ s/^--//;
2789 $type = undef
2790 unless ($type eq 'bool' || $type eq 'int');
2791 }
2792
2793 # get config
2794 if (!defined $config_file ||
2795 $config_file ne "$git_dir/config") {
2796 %config = git_parse_project_config('gitweb');
2797 $config_file = "$git_dir/config";
2798 }
2799
2800 # check if config variable (key) exists
2801 return unless exists $config{"gitweb.$key"};
2802
2803 # ensure given type
2804 if (!defined $type) {
2805 return $config{"gitweb.$key"};
2806 } elsif ($type eq 'bool') {
2807 # backward compatibility: 'git config --bool' returns true/false
2808 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2809 } elsif ($type eq 'int') {
2810 return config_to_int($config{"gitweb.$key"});
2811 }
2812 return $config{"gitweb.$key"};
2813 }
2814
2815 # get hash of given path at given ref
2816 sub git_get_hash_by_path {
2817 my $base = shift;
2818 my $path = shift || return undef;
2819 my $type = shift;
2820
2821 $path =~ s,/+$,,;
2822
2823 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2824 or die_error(500, "Open git-ls-tree failed");
2825 my $line = <$fd>;
2826 close $fd or return undef;
2827
2828 if (!defined $line) {
2829 # there is no tree or hash given by $path at $base
2830 return undef;
2831 }
2832
2833 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2834 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2835 if (defined $type && $type ne $2) {
2836 # type doesn't match
2837 return undef;
2838 }
2839 return $3;
2840 }
2841
2842 # get path of entry with given hash at given tree-ish (ref)
2843 # used to get 'from' filename for combined diff (merge commit) for renames
2844 sub git_get_path_by_hash {
2845 my $base = shift || return;
2846 my $hash = shift || return;
2847
2848 local $/ = "\0";
2849
2850 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2851 or return undef;
2852 while (my $line = <$fd>) {
2853 chomp $line;
2854
2855 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2856 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2857 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2858 close $fd;
2859 return $1;
2860 }
2861 }
2862 close $fd;
2863 return undef;
2864 }
2865
2866 ## ......................................................................
2867 ## git utility functions, directly accessing git repository
2868
2869 # get the value of config variable either from file named as the variable
2870 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2871 # configuration variable in the repository config file.
2872 sub git_get_file_or_project_config {
2873 my ($path, $name) = @_;
2874
2875 $git_dir = "$projectroot/$path";
2876 open my $fd, '<', "$git_dir/$name"
2877 or return git_get_project_config($name);
2878 my $conf = <$fd>;
2879 close $fd;
2880 if (defined $conf) {
2881 chomp $conf;
2882 }
2883 return $conf;
2884 }
2885
2886 sub git_get_project_description {
2887 my $path = shift;
2888 return git_get_file_or_project_config($path, 'description');
2889 }
2890
2891 sub git_get_project_category {
2892 my $path = shift;
2893 return git_get_file_or_project_config($path, 'category');
2894 }
2895
2896
2897 # supported formats:
2898 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2899 # - if its contents is a number, use it as tag weight,
2900 # - otherwise add a tag with weight 1
2901 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2902 # the same value multiple times increases tag weight
2903 # * `gitweb.ctag' multi-valued repo config variable
2904 sub git_get_project_ctags {
2905 my $project = shift;
2906 my $ctags = {};
2907
2908 $git_dir = "$projectroot/$project";
2909 if (opendir my $dh, "$git_dir/ctags") {
2910 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2911 foreach my $tagfile (@files) {
2912 open my $ct, '<', $tagfile
2913 or next;
2914 my $val = <$ct>;
2915 chomp $val if $val;
2916 close $ct;
2917
2918 (my $ctag = $tagfile) =~ s#.*/##;
2919 if ($val =~ /^\d+$/) {
2920 $ctags->{$ctag} = $val;
2921 } else {
2922 $ctags->{$ctag} = 1;
2923 }
2924 }
2925 closedir $dh;
2926
2927 } elsif (open my $fh, '<', "$git_dir/ctags") {
2928 while (my $line = <$fh>) {
2929 chomp $line;
2930 $ctags->{$line}++ if $line;
2931 }
2932 close $fh;
2933
2934 } else {
2935 my $taglist = config_to_multi(git_get_project_config('ctag'));
2936 foreach my $tag (@$taglist) {
2937 $ctags->{$tag}++;
2938 }
2939 }
2940
2941 return $ctags;
2942 }
2943
2944 # return hash, where keys are content tags ('ctags'),
2945 # and values are sum of weights of given tag in every project
2946 sub git_gather_all_ctags {
2947 my $projects = shift;
2948 my $ctags = {};
2949
2950 foreach my $p (@$projects) {
2951 foreach my $ct (keys %{$p->{'ctags'}}) {
2952 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2953 }
2954 }
2955
2956 return $ctags;
2957 }
2958
2959 sub git_populate_project_tagcloud {
2960 my $ctags = shift;
2961
2962 # First, merge different-cased tags; tags vote on casing
2963 my %ctags_lc;
2964 foreach (keys %$ctags) {
2965 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2966 if (not $ctags_lc{lc $_}->{topcount}
2967 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2968 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2969 $ctags_lc{lc $_}->{topname} = $_;
2970 }
2971 }
2972
2973 my $cloud;
2974 my $matched = $input_params{'ctag'};
2975 if (eval { require HTML::TagCloud; 1; }) {
2976 $cloud = HTML::TagCloud->new;
2977 foreach my $ctag (sort keys %ctags_lc) {
2978 # Pad the title with spaces so that the cloud looks
2979 # less crammed.
2980 my $title = esc_html($ctags_lc{$ctag}->{topname});
2981 $title =~ s/ /&nbsp;/g;
2982 $title =~ s/^/&nbsp;/g;
2983 $title =~ s/$/&nbsp;/g;
2984 if (defined $matched && $matched eq $ctag) {
2985 $title = qq(<span class="match">$title</span>);
2986 }
2987 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2988 $ctags_lc{$ctag}->{count});
2989 }
2990 } else {
2991 $cloud = {};
2992 foreach my $ctag (keys %ctags_lc) {
2993 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
2994 if (defined $matched && $matched eq $ctag) {
2995 $title = qq(<span class="match">$title</span>);
2996 }
2997 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
2998 $cloud->{$ctag}{ctag} =
2999 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3000 }
3001 }
3002 return $cloud;
3003 }
3004
3005 sub git_show_project_tagcloud {
3006 my ($cloud, $count) = @_;
3007 if (ref $cloud eq 'HTML::TagCloud') {
3008 return $cloud->html_and_css($count);
3009 } else {
3010 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3011 return
3012 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3013 join (', ', map {
3014 $cloud->{$_}->{'ctag'}
3015 } splice(@tags, 0, $count)) .
3016 '</div>';
3017 }
3018 }
3019
3020 sub git_get_project_url_list {
3021 my $path = shift;
3022
3023 $git_dir = "$projectroot/$path";
3024 open my $fd, '<', "$git_dir/cloneurl"
3025 or return wantarray ?
3026 @{ config_to_multi(git_get_project_config('url')) } :
3027 config_to_multi(git_get_project_config('url'));
3028 my @git_project_url_list = map { chomp; $_ } <$fd>;
3029 close $fd;
3030
3031 return wantarray ? @git_project_url_list : \@git_project_url_list;
3032 }
3033
3034 sub git_get_projects_list {
3035 my $filter = shift || '';
3036 my $paranoid = shift;
3037 my @list;
3038
3039 if (-d $projects_list) {
3040 # search in directory
3041 my $dir = $projects_list;
3042 # remove the trailing "/"
3043 $dir =~ s!/+$!!;
3044 my $pfxlen = length("$dir");
3045 my $pfxdepth = ($dir =~ tr!/!!);
3046 # when filtering, search only given subdirectory
3047 if ($filter && !$paranoid) {
3048 $dir .= "/$filter";
3049 $dir =~ s!/+$!!;
3050 }
3051
3052 File::Find::find({
3053 follow_fast => 1, # follow symbolic links
3054 follow_skip => 2, # ignore duplicates
3055 dangling_symlinks => 0, # ignore dangling symlinks, silently
3056 wanted => sub {
3057 # global variables
3058 our $project_maxdepth;
3059 our $projectroot;
3060 # skip project-list toplevel, if we get it.
3061 return if (m!^[/.]$!);
3062 # only directories can be git repositories
3063 return unless (-d $_);
3064 # don't traverse too deep (Find is super slow on os x)
3065 # $project_maxdepth excludes depth of $projectroot
3066 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3067 $File::Find::prune = 1;
3068 return;
3069 }
3070
3071 my $path = substr($File::Find::name, $pfxlen + 1);
3072 # paranoidly only filter here
3073 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3074 next;
3075 }
3076 # we check related file in $projectroot
3077 if (check_export_ok("$projectroot/$path")) {
3078 push @list, { path => $path };
3079 $File::Find::prune = 1;
3080 }
3081 },
3082 }, "$dir");
3083
3084 } elsif (-f $projects_list) {
3085 # read from file(url-encoded):
3086 # 'git%2Fgit.git Linus+Torvalds'
3087 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3088 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3089 open my $fd, '<', $projects_list or return;
3090 PROJECT:
3091 while (my $line = <$fd>) {
3092 chomp $line;
3093 my ($path, $owner) = split ' ', $line;
3094 $path = unescape($path);
3095 $owner = unescape($owner);
3096 if (!defined $path) {
3097 next;
3098 }
3099 # if $filter is rpovided, check if $path begins with $filter
3100 if ($filter && $path !~ m!^\Q$filter\E/!) {
3101 next;
3102 }
3103 if (check_export_ok("$projectroot/$path")) {
3104 my $pr = {
3105 path => $path
3106 };
3107 if ($owner) {
3108 $pr->{'owner'} = to_utf8($owner);
3109 }
3110 push @list, $pr;
3111 }
3112 }
3113 close $fd;
3114 }
3115 return @list;
3116 }
3117
3118 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3119 # as side effects it sets 'forks' field to list of forks for forked projects
3120 sub filter_forks_from_projects_list {
3121 my $projects = shift;
3122
3123 my %trie; # prefix tree of directories (path components)
3124 # generate trie out of those directories that might contain forks
3125 foreach my $pr (@$projects) {
3126 my $path = $pr->{'path'};
3127 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3128 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3129 next unless ($path); # skip '.git' repository: tests, git-instaweb
3130 next unless (-d "$projectroot/$path"); # containing directory exists
3131 $pr->{'forks'} = []; # there can be 0 or more forks of project
3132
3133 # add to trie
3134 my @dirs = split('/', $path);
3135 # walk the trie, until either runs out of components or out of trie
3136 my $ref = \%trie;
3137 while (scalar @dirs &&
3138 exists($ref->{$dirs[0]})) {
3139 $ref = $ref->{shift @dirs};
3140 }
3141 # create rest of trie structure from rest of components
3142 foreach my $dir (@dirs) {
3143 $ref = $ref->{$dir} = {};
3144 }
3145 # create end marker, store $pr as a data
3146 $ref->{''} = $pr if (!exists $ref->{''});
3147 }
3148
3149 # filter out forks, by finding shortest prefix match for paths
3150 my @filtered;
3151 PROJECT:
3152 foreach my $pr (@$projects) {
3153 # trie lookup
3154 my $ref = \%trie;
3155 DIR:
3156 foreach my $dir (split('/', $pr->{'path'})) {
3157 if (exists $ref->{''}) {
3158 # found [shortest] prefix, is a fork - skip it
3159 push @{$ref->{''}{'forks'}}, $pr;
3160 next PROJECT;
3161 }
3162 if (!exists $ref->{$dir}) {
3163 # not in trie, cannot have prefix, not a fork
3164 push @filtered, $pr;
3165 next PROJECT;
3166 }
3167 # If the dir is there, we just walk one step down the trie.
3168 $ref = $ref->{$dir};
3169 }
3170 # we ran out of trie
3171 # (shouldn't happen: it's either no match, or end marker)
3172 push @filtered, $pr;
3173 }
3174
3175 return @filtered;
3176 }
3177
3178 # note: fill_project_list_info must be run first,
3179 # for 'descr_long' and 'ctags' to be filled
3180 sub search_projects_list {
3181 my ($projlist, %opts) = @_;
3182 my $tagfilter = $opts{'tagfilter'};
3183 my $search_re = $opts{'search_regexp'};
3184
3185 return @$projlist
3186 unless ($tagfilter || $search_re);
3187
3188 # searching projects require filling to be run before it;
3189 fill_project_list_info($projlist,
3190 $tagfilter ? 'ctags' : (),
3191 $search_re ? ('path', 'descr') : ());
3192 my @projects;
3193 PROJECT:
3194 foreach my $pr (@$projlist) {
3195
3196 if ($tagfilter) {
3197 next unless ref($pr->{'ctags'}) eq 'HASH';
3198 next unless
3199 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3200 }
3201
3202 if ($search_re) {
3203 next unless
3204 $pr->{'path'} =~ /$search_re/ ||
3205 $pr->{'descr_long'} =~ /$search_re/;
3206 }
3207
3208 push @projects, $pr;
3209 }
3210
3211 return @projects;
3212 }
3213
3214 our $gitweb_project_owner = undef;
3215 sub git_get_project_list_from_file {
3216
3217 return if (defined $gitweb_project_owner);
3218
3219 $gitweb_project_owner = {};
3220 # read from file (url-encoded):
3221 # 'git%2Fgit.git Linus+Torvalds'
3222 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3223 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3224 if (-f $projects_list) {
3225 open(my $fd, '<', $projects_list);
3226 while (my $line = <$fd>) {
3227 chomp $line;
3228 my ($pr, $ow) = split ' ', $line;
3229 $pr = unescape($pr);
3230 $ow = unescape($ow);
3231 $gitweb_project_owner->{$pr} = to_utf8($ow);
3232 }
3233 close $fd;
3234 }
3235 }
3236
3237 sub git_get_project_owner {
3238 my $project = shift;
3239 my $owner;
3240
3241 return undef unless $project;
3242 $git_dir = "$projectroot/$project";
3243
3244 if (!defined $gitweb_project_owner) {
3245 git_get_project_list_from_file();
3246 }
3247
3248 if (exists $gitweb_project_owner->{$project}) {
3249 $owner = $gitweb_project_owner->{$project};
3250 }
3251 if (!defined $owner){
3252 $owner = git_get_project_config('owner');
3253 }
3254 if (!defined $owner) {
3255 $owner = get_file_owner("$git_dir");
3256 }
3257
3258 return $owner;
3259 }
3260
3261 sub git_get_last_activity {
3262 my ($path) = @_;
3263 my $fd;
3264
3265 $git_dir = "$projectroot/$path";
3266 open($fd, "-|", git_cmd(), 'for-each-ref',
3267 '--format=%(committer)',
3268 '--sort=-committerdate',
3269 '--count=1',
3270 map { "refs/$_" } get_branch_refs ()) or return;
3271 my $most_recent = <$fd>;
3272 close $fd or return;
3273 if (defined $most_recent &&
3274 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3275 my $timestamp = $1;
3276 my $age = time - $timestamp;
3277 return ($age, age_string($age));
3278 }
3279 return (undef, undef);
3280 }
3281
3282 # Implementation note: when a single remote is wanted, we cannot use 'git
3283 # remote show -n' because that command always work (assuming it's a remote URL
3284 # if it's not defined), and we cannot use 'git remote show' because that would
3285 # try to make a network roundtrip. So the only way to find if that particular
3286 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3287 # and when we find what we want.
3288 sub git_get_remotes_list {
3289 my $wanted = shift;
3290 my %remotes = ();
3291
3292 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3293 return unless $fd;
3294 while (my $remote = <$fd>) {
3295 chomp $remote;
3296 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3297 next if $wanted and not $remote eq $wanted;
3298 my ($url, $key) = ($1, $2);
3299
3300 $remotes{$remote} ||= { 'heads' => () };
3301 $remotes{$remote}{$key} = $url;
3302 }
3303 close $fd or return;
3304 return wantarray ? %remotes : \%remotes;
3305 }
3306
3307 # Takes a hash of remotes as first parameter and fills it by adding the
3308 # available remote heads for each of the indicated remotes.
3309 sub fill_remote_heads {
3310 my $remotes = shift;
3311 my @heads = map { "remotes/$_" } keys %$remotes;
3312 my @remoteheads = git_get_heads_list(undef, @heads);
3313 foreach my $remote (keys %$remotes) {
3314 $remotes->{$remote}{'heads'} = [ grep {
3315 $_->{'name'} =~ s!^$remote/!!
3316 } @remoteheads ];
3317 }
3318 }
3319
3320 sub git_get_references {
3321 my $type = shift || "";
3322 my %refs;
3323 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3324 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3325 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3326 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3327 or return;
3328
3329 while (my $line = <$fd>) {
3330 chomp $line;
3331 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3332 if (defined $refs{$1}) {
3333 push @{$refs{$1}}, $2;
3334 } else {
3335 $refs{$1} = [ $2 ];
3336 }
3337 }
3338 }
3339 close $fd or return;
3340 return \%refs;
3341 }
3342
3343 sub git_get_rev_name_tags {
3344 my $hash = shift || return undef;
3345
3346 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3347 or return;
3348 my $name_rev = <$fd>;
3349 close $fd;
3350
3351 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3352 return $1;
3353 } else {
3354 # catches also '$hash undefined' output
3355 return undef;
3356 }
3357 }
3358
3359 ## ----------------------------------------------------------------------
3360 ## parse to hash functions
3361
3362 sub parse_date {
3363 my $epoch = shift;
3364 my $tz = shift || "-0000";
3365
3366 my %date;
3367 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3368 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3369 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3370 $date{'hour'} = $hour;
3371 $date{'minute'} = $min;
3372 $date{'mday'} = $mday;
3373 $date{'day'} = $days[$wday];
3374 $date{'month'} = $months[$mon];
3375 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3376 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3377 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3378 $mday, $months[$mon], $hour ,$min;
3379 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3380 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3381
3382 my ($tz_sign, $tz_hour, $tz_min) =
3383 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3384 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3385 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3386 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3387 $date{'hour_local'} = $hour;
3388 $date{'minute_local'} = $min;
3389 $date{'tz_local'} = $tz;
3390 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3391 1900+$year, $mon+1, $mday,
3392 $hour, $min, $sec, $tz);
3393 return %date;
3394 }
3395
3396 sub parse_tag {
3397 my $tag_id = shift;
3398 my %tag;
3399 my @comment;
3400
3401 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3402 $tag{'id'} = $tag_id;
3403 while (my $line = <$fd>) {
3404 chomp $line;
3405 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3406 $tag{'object'} = $1;
3407 } elsif ($line =~ m/^type (.+)$/) {
3408 $tag{'type'} = $1;
3409 } elsif ($line =~ m/^tag (.+)$/) {
3410 $tag{'name'} = $1;
3411 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3412 $tag{'author'} = $1;
3413 $tag{'author_epoch'} = $2;
3414 $tag{'author_tz'} = $3;
3415 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3416 $tag{'author_name'} = $1;
3417 $tag{'author_email'} = $2;
3418 } else {
3419 $tag{'author_name'} = $tag{'author'};
3420 }
3421 } elsif ($line =~ m/--BEGIN/) {
3422 push @comment, $line;
3423 last;
3424 } elsif ($line eq "") {
3425 last;
3426 }
3427 }
3428 push @comment, <$fd>;
3429 $tag{'comment'} = \@comment;
3430 close $fd or return;
3431 if (!defined $tag{'name'}) {
3432 return
3433 };
3434 return %tag
3435 }
3436
3437 sub parse_commit_text {
3438 my ($commit_text, $withparents) = @_;
3439 my @commit_lines = split '\n', $commit_text;
3440 my %co;
3441
3442 pop @commit_lines; # Remove '\0'
3443
3444 if (! @commit_lines) {
3445 return;
3446 }
3447
3448 my $header = shift @commit_lines;
3449 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3450 return;
3451 }
3452 ($co{'id'}, my @parents) = split ' ', $header;
3453 while (my $line = shift @commit_lines) {
3454 last if $line eq "\n";
3455 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3456 $co{'tree'} = $1;
3457 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3458 push @parents, $1;
3459 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3460 $co{'author'} = to_utf8($1);
3461 $co{'author_epoch'} = $2;
3462 $co{'author_tz'} = $3;
3463 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3464 $co{'author_name'} = $1;
3465 $co{'author_email'} = $2;
3466 } else {
3467 $co{'author_name'} = $co{'author'};
3468 }
3469 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3470 $co{'committer'} = to_utf8($1);
3471 $co{'committer_epoch'} = $2;
3472 $co{'committer_tz'} = $3;
3473 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3474 $co{'committer_name'} = $1;
3475 $co{'committer_email'} = $2;
3476 } else {
3477 $co{'committer_name'} = $co{'committer'};
3478 }
3479 }
3480 }
3481 if (!defined $co{'tree'}) {
3482 return;
3483 };
3484 $co{'parents'} = \@parents;
3485 $co{'parent'} = $parents[0];
3486
3487 foreach my $title (@commit_lines) {
3488 $title =~ s/^ //;
3489 if ($title ne "") {
3490 $co{'title'} = chop_str($title, 80, 5);
3491 # remove leading stuff of merges to make the interesting part visible
3492 if (length($title) > 50) {
3493 $title =~ s/^Automatic //;
3494 $title =~ s/^merge (of|with) /Merge ... /i;
3495 if (length($title) > 50) {
3496 $title =~ s/(http|rsync):\/\///;
3497 }
3498 if (length($title) > 50) {
3499 $title =~ s/(master|www|rsync)\.//;
3500 }
3501 if (length($title) > 50) {
3502 $title =~ s/kernel.org:?//;
3503 }
3504 if (length($title) > 50) {
3505 $title =~ s/\/pub\/scm//;
3506 }
3507 }
3508 $co{'title_short'} = chop_str($title, 50, 5);
3509 last;
3510 }
3511 }
3512 if (! defined $co{'title'} || $co{'title'} eq "") {
3513 $co{'title'} = $co{'title_short'} = '(no commit message)';
3514 }
3515 # remove added spaces
3516 foreach my $line (@commit_lines) {
3517 $line =~ s/^ //;
3518 }
3519 $co{'comment'} = \@commit_lines;
3520
3521 my $age = time - $co{'committer_epoch'};
3522 $co{'age'} = $age;
3523 $co{'age_string'} = age_string($age);
3524 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3525 if ($age > 60*60*24*7*2) {
3526 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3527 $co{'age_string_age'} = $co{'age_string'};
3528 } else {
3529 $co{'age_string_date'} = $co{'age_string'};
3530 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3531 }
3532 return %co;
3533 }
3534
3535 sub parse_commit {
3536 my ($commit_id) = @_;
3537 my %co;
3538
3539 local $/ = "\0";
3540
3541 open my $fd, "-|", git_cmd(), "rev-list",
3542 "--parents",
3543 "--header",
3544 "--max-count=1",
3545 $commit_id,
3546 "--",
3547 or die_error(500, "Open git-rev-list failed");
3548 %co = parse_commit_text(<$fd>, 1);
3549 close $fd;
3550
3551 return %co;
3552 }
3553
3554 sub parse_commits {
3555 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3556 my @cos;
3557
3558 $maxcount ||= 1;
3559 $skip ||= 0;
3560
3561 local $/ = "\0";
3562
3563 open my $fd, "-|", git_cmd(), "rev-list",
3564 "--header",
3565 @args,
3566 ("--max-count=" . $maxcount),
3567 ("--skip=" . $skip),
3568 @extra_options,
3569 $commit_id,
3570 "--",
3571 ($filename ? ($filename) : ())
3572 or die_error(500, "Open git-rev-list failed");
3573 while (my $line = <$fd>) {
3574 my %co = parse_commit_text($line);
3575 push @cos, \%co;
3576 }
3577 close $fd;
3578
3579 return wantarray ? @cos : \@cos;
3580 }
3581
3582 # parse line of git-diff-tree "raw" output
3583 sub parse_difftree_raw_line {
3584 my $line = shift;
3585 my %res;
3586
3587 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3588 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3589 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3590 $res{'from_mode'} = $1;
3591 $res{'to_mode'} = $2;
3592 $res{'from_id'} = $3;
3593 $res{'to_id'} = $4;
3594 $res{'status'} = $5;
3595 $res{'similarity'} = $6;
3596 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3597 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3598 } else {
3599 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3600 }
3601 }
3602 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3603 # combined diff (for merge commit)
3604 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3605 $res{'nparents'} = length($1);
3606 $res{'from_mode'} = [ split(' ', $2) ];
3607 $res{'to_mode'} = pop @{$res{'from_mode'}};
3608 $res{'from_id'} = [ split(' ', $3) ];
3609 $res{'to_id'} = pop @{$res{'from_id'}};
3610 $res{'status'} = [ split('', $4) ];
3611 $res{'to_file'} = unquote($5);
3612 }
3613 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3614 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3615 $res{'commit'} = $1;
3616 }
3617
3618 return wantarray ? %res : \%res;
3619 }
3620
3621 # wrapper: return parsed line of git-diff-tree "raw" output
3622 # (the argument might be raw line, or parsed info)
3623 sub parsed_difftree_line {
3624 my $line_or_ref = shift;
3625
3626 if (ref($line_or_ref) eq "HASH") {
3627 # pre-parsed (or generated by hand)
3628 return $line_or_ref;
3629 } else {
3630 return parse_difftree_raw_line($line_or_ref);
3631 }
3632 }
3633
3634 # parse line of git-ls-tree output
3635 sub parse_ls_tree_line {
3636 my $line = shift;
3637 my %opts = @_;
3638 my %res;
3639
3640 if ($opts{'-l'}) {
3641 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3642 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3643
3644 $res{'mode'} = $1;
3645 $res{'type'} = $2;
3646 $res{'hash'} = $3;
3647 $res{'size'} = $4;
3648 if ($opts{'-z'}) {
3649 $res{'name'} = $5;
3650 } else {
3651 $res{'name'} = unquote($5);
3652 }
3653 } else {
3654 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3655 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3656
3657 $res{'mode'} = $1;
3658 $res{'type'} = $2;
3659 $res{'hash'} = $3;
3660 if ($opts{'-z'}) {
3661 $res{'name'} = $4;
3662 } else {
3663 $res{'name'} = unquote($4);
3664 }
3665 }
3666
3667 return wantarray ? %res : \%res;
3668 }
3669
3670 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3671 sub parse_from_to_diffinfo {
3672 my ($diffinfo, $from, $to, @parents) = @_;
3673
3674 if ($diffinfo->{'nparents'}) {
3675 # combined diff
3676 $from->{'file'} = [];
3677 $from->{'href'} = [];
3678 fill_from_file_info($diffinfo, @parents)
3679 unless exists $diffinfo->{'from_file'};
3680 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3681 $from->{'file'}[$i] =
3682 defined $diffinfo->{'from_file'}[$i] ?
3683 $diffinfo->{'from_file'}[$i] :
3684 $diffinfo->{'to_file'};
3685 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3686 $from->{'href'}[$i] = href(action=>"blob",
3687 hash_base=>$parents[$i],
3688 hash=>$diffinfo->{'from_id'}[$i],
3689 file_name=>$from->{'file'}[$i]);
3690 } else {
3691 $from->{'href'}[$i] = undef;
3692 }
3693 }
3694 } else {
3695 # ordinary (not combined) diff
3696 $from->{'file'} = $diffinfo->{'from_file'};
3697 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3698 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3699 hash=>$diffinfo->{'from_id'},
3700 file_name=>$from->{'file'});
3701 } else {
3702 delete $from->{'href'};
3703 }
3704 }
3705
3706 $to->{'file'} = $diffinfo->{'to_file'};
3707 if (!is_deleted($diffinfo)) { # file exists in result
3708 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3709 hash=>$diffinfo->{'to_id'},
3710 file_name=>$to->{'file'});
3711 } else {
3712 delete $to->{'href'};
3713 }
3714 }
3715
3716 ## ......................................................................
3717 ## parse to array of hashes functions
3718
3719 sub git_get_heads_list {
3720 my ($limit, @classes) = @_;
3721 @classes = get_branch_refs() unless @classes;
3722 my @patterns = map { "refs/$_" } @classes;
3723 my @headslist;
3724
3725 open my $fd, '-|', git_cmd(), 'for-each-ref',
3726 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3727 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3728 @patterns
3729 or return;
3730 while (my $line = <$fd>) {
3731 my %ref_item;
3732
3733 chomp $line;
3734 my ($refinfo, $committerinfo) = split(/\0/, $line);
3735 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3736 my ($committer, $epoch, $tz) =
3737 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3738 $ref_item{'fullname'} = $name;
3739 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3740 $name =~ s!^refs/($strip_refs|remotes)/!!;
3741 $ref_item{'name'} = $name;
3742 # for refs neither in 'heads' nor 'remotes' we want to
3743 # show their ref dir
3744 my $ref_dir = (defined $1) ? $1 : '';
3745 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3746 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3747 }
3748
3749 $ref_item{'id'} = $hash;
3750 $ref_item{'title'} = $title || '(no commit message)';
3751 $ref_item{'epoch'} = $epoch;
3752 if ($epoch) {
3753 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3754 } else {
3755 $ref_item{'age'} = "unknown";
3756 }
3757
3758 push @headslist, \%ref_item;
3759 }
3760 close $fd;
3761
3762 return wantarray ? @headslist : \@headslist;
3763 }
3764
3765 sub git_get_tags_list {
3766 my $limit = shift;
3767 my @tagslist;
3768
3769 open my $fd, '-|', git_cmd(), 'for-each-ref',
3770 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3771 '--format=%(objectname) %(objecttype) %(refname) '.
3772 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3773 'refs/tags'
3774 or return;
3775 while (my $line = <$fd>) {
3776 my %ref_item;
3777
3778 chomp $line;
3779 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3780 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3781 my ($creator, $epoch, $tz) =
3782 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3783 $ref_item{'fullname'} = $name;
3784 $name =~ s!^refs/tags/!!;
3785
3786 $ref_item{'type'} = $type;
3787 $ref_item{'id'} = $id;
3788 $ref_item{'name'} = $name;
3789 if ($type eq "tag") {
3790 $ref_item{'subject'} = $title;
3791 $ref_item{'reftype'} = $reftype;
3792 $ref_item{'refid'} = $refid;
3793 } else {
3794 $ref_item{'reftype'} = $type;
3795 $ref_item{'refid'} = $id;
3796 }
3797
3798 if ($type eq "tag" || $type eq "commit") {
3799 $ref_item{'epoch'} = $epoch;
3800 if ($epoch) {
3801 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3802 } else {
3803 $ref_item{'age'} = "unknown";
3804 }
3805 }
3806
3807 push @tagslist, \%ref_item;
3808 }
3809 close $fd;
3810
3811 return wantarray ? @tagslist : \@tagslist;
3812 }
3813
3814 ## ----------------------------------------------------------------------
3815 ## filesystem-related functions
3816
3817 sub get_file_owner {
3818 my $path = shift;
3819
3820 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3821 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3822 if (!defined $gcos) {
3823 return undef;
3824 }
3825 my $owner = $gcos;
3826 $owner =~ s/[,;].*$//;
3827 return to_utf8($owner);
3828 }
3829
3830 # assume that file exists
3831 sub insert_file {
3832 my $filename = shift;
3833
3834 open my $fd, '<', $filename;
3835 print map { to_utf8($_) } <$fd>;
3836 close $fd;
3837 }
3838
3839 ## ......................................................................
3840 ## mimetype related functions
3841
3842 sub mimetype_guess_file {
3843 my $filename = shift;
3844 my $mimemap = shift;
3845 -r $mimemap or return undef;
3846
3847 my %mimemap;
3848 open(my $mh, '<', $mimemap) or return undef;
3849 while (<$mh>) {
3850 next if m/^#/; # skip comments
3851 my ($mimetype, @exts) = split(/\s+/);
3852 foreach my $ext (@exts) {
3853 $mimemap{$ext} = $mimetype;
3854 }
3855 }
3856 close($mh);
3857
3858 $filename =~ /\.([^.]*)$/;
3859 return $mimemap{$1};
3860 }
3861
3862 sub mimetype_guess {
3863 my $filename = shift;
3864 my $mime;
3865 $filename =~ /\./ or return undef;
3866
3867 if ($mimetypes_file) {
3868 my $file = $mimetypes_file;
3869 if ($file !~ m!^/!) { # if it is relative path
3870 # it is relative to project
3871 $file = "$projectroot/$project/$file";
3872 }
3873 $mime = mimetype_guess_file($filename, $file);
3874 }
3875 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3876 return $mime;
3877 }
3878
3879 sub blob_mimetype {
3880 my $fd = shift;
3881 my $filename = shift;
3882
3883 if ($filename) {
3884 my $mime = mimetype_guess($filename);
3885 $mime and return $mime;
3886 }
3887
3888 # just in case
3889 return $default_blob_plain_mimetype unless $fd;
3890
3891 if (-T $fd) {
3892 return 'text/plain';
3893 } elsif (! $filename) {
3894 return 'application/octet-stream';
3895 } elsif ($filename =~ m/\.png$/i) {
3896 return 'image/png';
3897 } elsif ($filename =~ m/\.gif$/i) {
3898 return 'image/gif';
3899 } elsif ($filename =~ m/\.jpe?g$/i) {
3900 return 'image/jpeg';
3901 } else {
3902 return 'application/octet-stream';
3903 }
3904 }
3905
3906 sub blob_contenttype {
3907 my ($fd, $file_name, $type) = @_;
3908
3909 $type ||= blob_mimetype($fd, $file_name);
3910 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3911 $type .= "; charset=$default_text_plain_charset";
3912 }
3913
3914 return $type;
3915 }
3916
3917 # guess file syntax for syntax highlighting; return undef if no highlighting
3918 # the name of syntax can (in the future) depend on syntax highlighter used
3919 sub guess_file_syntax {
3920 my ($highlight, $mimetype, $file_name) = @_;
3921 return undef unless ($highlight && defined $file_name);
3922 my $basename = basename($file_name, '.in');
3923 return $highlight_basename{$basename}
3924 if exists $highlight_basename{$basename};
3925
3926 $basename =~ /\.([^.]*)$/;
3927 my $ext = $1 or return undef;
3928 return $highlight_ext{$ext}
3929 if exists $highlight_ext{$ext};
3930
3931 return undef;
3932 }
3933
3934 # run highlighter and return FD of its output,
3935 # or return original FD if no highlighting
3936 sub run_highlighter {
3937 my ($fd, $highlight, $syntax) = @_;
3938 return $fd unless ($highlight && defined $syntax);
3939
3940 close $fd;
3941 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3942 quote_command($highlight_bin).
3943 " --replace-tabs=8 --fragment --syntax $syntax |"
3944 or die_error(500, "Couldn't open file or run syntax highlighter");
3945 return $fd;
3946 }
3947
3948 ## ======================================================================
3949 ## functions printing HTML: header, footer, error page
3950
3951 sub get_page_title {
3952 my $title = to_utf8($site_name);
3953
3954 unless (defined $project) {
3955 if (defined $project_filter) {
3956 $title .= " - projects in '" . esc_path($project_filter) . "'";
3957 }
3958 return $title;
3959 }
3960 $title .= " - " . to_utf8($project);
3961
3962 return $title unless (defined $action);
3963 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3964
3965 return $title unless (defined $file_name);
3966 $title .= " - " . esc_path($file_name);
3967 if ($action eq "tree" && $file_name !~ m|/$|) {
3968 $title .= "/";
3969 }
3970
3971 return $title;
3972 }
3973
3974 sub get_content_type_html {
3975 # require explicit support from the UA if we are to send the page as
3976 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3977 # we have to do this because MSIE sometimes globs '*/*', pretending to
3978 # support xhtml+xml but choking when it gets what it asked for.
3979 if (defined $cgi->http('HTTP_ACCEPT') &&
3980 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3981 $cgi->Accept('application/xhtml+xml') != 0) {
3982 return 'application/xhtml+xml';
3983 } else {
3984 return 'text/html';
3985 }
3986 }
3987
3988 sub print_feed_meta {
3989 if (defined $project) {
3990 my %href_params = get_feed_info();
3991 if (!exists $href_params{'-title'}) {
3992 $href_params{'-title'} = 'log';
3993 }
3994
3995 foreach my $format (qw(RSS Atom)) {
3996 my $type = lc($format);
3997 my %link_attr = (
3998 '-rel' => 'alternate',
3999 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4000 '-type' => "application/$type+xml"
4001 );
4002
4003 $href_params{'extra_options'} = undef;
4004 $href_params{'action'} = $type;
4005 $link_attr{'-href'} = href(%href_params);
4006 print "<link ".
4007 "rel=\"$link_attr{'-rel'}\" ".
4008 "title=\"$link_attr{'-title'}\" ".
4009 "href=\"$link_attr{'-href'}\" ".
4010 "type=\"$link_attr{'-type'}\" ".
4011 "/>\n";
4012
4013 $href_params{'extra_options'} = '--no-merges';
4014 $link_attr{'-href'} = href(%href_params);
4015 $link_attr{'-title'} .= ' (no merges)';
4016 print "<link ".
4017 "rel=\"$link_attr{'-rel'}\" ".
4018 "title=\"$link_attr{'-title'}\" ".
4019 "href=\"$link_attr{'-href'}\" ".
4020 "type=\"$link_attr{'-type'}\" ".
4021 "/>\n";
4022 }
4023
4024 } else {
4025 printf('<link rel="alternate" title="%s projects list" '.
4026 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4027 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4028 printf('<link rel="alternate" title="%s projects feeds" '.
4029 'href="%s" type="text/x-opml" />'."\n",
4030 esc_attr($site_name), href(project=>undef, action=>"opml"));
4031 }
4032 }
4033
4034 sub print_header_links {
4035 my $status = shift;
4036
4037 # print out each stylesheet that exist, providing backwards capability
4038 # for those people who defined $stylesheet in a config file
4039 if (defined $stylesheet) {
4040 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4041 } else {
4042 foreach my $stylesheet (@stylesheets) {
4043 next unless $stylesheet;
4044 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4045 }
4046 }
4047 print_feed_meta()
4048 if ($status eq '200 OK');
4049 if (defined $favicon) {
4050 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4051 }
4052 }
4053
4054 sub print_nav_breadcrumbs_path {
4055 my $dirprefix = undef;
4056 while (my $part = shift) {
4057 $dirprefix .= "/" if defined $dirprefix;
4058 $dirprefix .= $part;
4059 print $cgi->a({-href => href(project => undef,
4060 project_filter => $dirprefix,
4061 action => "project_list")},
4062 esc_html($part)) . " / ";
4063 }
4064 }
4065
4066 sub print_nav_breadcrumbs {
4067 my %opts = @_;
4068
4069 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4070 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4071 }
4072 if (defined $project) {
4073 my @dirname = split '/', $project;
4074 my $projectbasename = pop @dirname;
4075 print_nav_breadcrumbs_path(@dirname);
4076 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4077 if (defined $action) {
4078 my $action_print = $action ;
4079 if (defined $opts{-action_extra}) {
4080 $action_print = $cgi->a({-href => href(action=>$action)},
4081 $action);
4082 }
4083 print " / $action_print";
4084 }
4085 if (defined $opts{-action_extra}) {
4086 print " / $opts{-action_extra}";
4087 }
4088 print "\n";
4089 } elsif (defined $project_filter) {
4090 print_nav_breadcrumbs_path(split '/', $project_filter);
4091 }
4092 }
4093
4094 sub print_search_form {
4095 if (!defined $searchtext) {
4096 $searchtext = "";
4097 }
4098 my $search_hash;
4099 if (defined $hash_base) {
4100 $search_hash = $hash_base;
4101 } elsif (defined $hash) {
4102 $search_hash = $hash;
4103 } else {
4104 $search_hash = "HEAD";
4105 }
4106 my $action = $my_uri;
4107 my $use_pathinfo = gitweb_check_feature('pathinfo');
4108 if ($use_pathinfo) {
4109 $action .= "/".esc_url($project);
4110 }
4111 print $cgi->start_form(-method => "get", -action => $action) .
4112 "<div class=\"search\">\n" .
4113 (!$use_pathinfo &&
4114 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4115 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4116 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4117 $cgi->popup_menu(-name => 'st', -default => 'commit',
4118 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4119 " " . $cgi->a({-href => href(action=>"search_help"),
4120 -title => "search help" }, "?") . " search:\n",
4121 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4122 "<span title=\"Extended regular expression\">" .
4123 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4124 -checked => $search_use_regexp) .
4125 "</span>" .
4126 "</div>" .
4127 $cgi->end_form() . "\n";
4128 }
4129
4130 sub git_header_html {
4131 my $status = shift || "200 OK";
4132 my $expires = shift;
4133 my %opts = @_;
4134
4135 my $title = get_page_title();
4136 my $content_type = get_content_type_html();
4137 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4138 -status=> $status, -expires => $expires)
4139 unless ($opts{'-no_http_header'});
4140 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4141 print <<EOF;
4142 <?xml version="1.0" encoding="utf-8"?>
4143 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4144 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4145 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4146 <!-- git core binaries version $git_version -->
4147 <head>
4148 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4149 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4150 <meta name="robots" content="index, nofollow"/>
4151 <title>$title</title>
4152 EOF
4153 # the stylesheet, favicon etc urls won't work correctly with path_info
4154 # unless we set the appropriate base URL
4155 if ($ENV{'PATH_INFO'}) {
4156 print "<base href=\"".esc_url($base_url)."\" />\n";
4157 }
4158 print_header_links($status);
4159
4160 if (defined $site_html_head_string) {
4161 print to_utf8($site_html_head_string);
4162 }
4163
4164 print "</head>\n" .
4165 "<body>\n";
4166
4167 if (defined $site_header && -f $site_header) {
4168 insert_file($site_header);
4169 }
4170
4171 print "<div class=\"page_header\">\n";
4172 if (defined $logo) {
4173 print $cgi->a({-href => esc_url($logo_url),
4174 -title => $logo_label},
4175 $cgi->img({-src => esc_url($logo),
4176 -width => 72, -height => 27,
4177 -alt => "git",
4178 -class => "logo"}));
4179 }
4180 print_nav_breadcrumbs(%opts);
4181 print "</div>\n";
4182
4183 my $have_search = gitweb_check_feature('search');
4184 if (defined $project && $have_search) {
4185 print_search_form();
4186 }
4187 }
4188
4189 sub git_footer_html {
4190 my $feed_class = 'rss_logo';
4191
4192 print "<div class=\"page_footer\">\n";
4193 if (defined $project) {
4194 my $descr = git_get_project_description($project);
4195 if (defined $descr) {
4196 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4197 }
4198
4199 my %href_params = get_feed_info();
4200 if (!%href_params) {
4201 $feed_class .= ' generic';
4202 }
4203 $href_params{'-title'} ||= 'log';
4204
4205 foreach my $format (qw(RSS Atom)) {
4206 $href_params{'action'} = lc($format);
4207 print $cgi->a({-href => href(%href_params),
4208 -title => "$href_params{'-title'} $format feed",
4209 -class => $feed_class}, $format)."\n";
4210 }
4211
4212 } else {
4213 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
4214 $year += 1900;
4215 print "<div class=\"page_footer_text\">Copyright &copy; $year, <a href=\"$footer_url\">$footer_label</a></div>\n";
4216
4217 print $cgi->a({-href => href(project=>undef, action=>"opml",
4218 project_filter => $project_filter),
4219 -class => $feed_class}, "OPML") . " ";
4220 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4221 project_filter => $project_filter),
4222 -class => $feed_class}, "TXT") . "\n";
4223 }
4224 print "</div>\n"; # class="page_footer"
4225
4226 if (defined $t0 && gitweb_check_feature('timed')) {
4227 print "<div id=\"generating_info\">\n";
4228 print 'This page took '.
4229 '<span id="generating_time" class="time_span">'.
4230 tv_interval($t0, [ gettimeofday() ]).
4231 ' seconds </span>'.
4232 ' and '.
4233 '<span id="generating_cmd">'.
4234 $number_of_git_cmds.
4235 '</span> git commands '.
4236 " to generate.\n";
4237 print "</div>\n"; # class="page_footer"
4238 }
4239
4240 if (defined $site_footer && -f $site_footer) {
4241 insert_file($site_footer);
4242 }
4243
4244 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4245 if (defined $action &&
4246 $action eq 'blame_incremental') {
4247 print qq!<script type="text/javascript">\n!.
4248 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4249 qq! "!. href() .qq!");\n!.
4250 qq!</script>\n!;
4251 } else {
4252 my ($jstimezone, $tz_cookie, $datetime_class) =
4253 gitweb_get_feature('javascript-timezone');
4254
4255 print qq!<script type="text/javascript">\n!.
4256 qq!window.onload = function () {\n!;
4257 if (gitweb_check_feature('javascript-actions')) {
4258 print qq! fixLinks();\n!;
4259 }
4260 if ($jstimezone && $tz_cookie && $datetime_class) {
4261 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4262 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4263 }
4264 print qq!};\n!.
4265 qq!</script>\n!;
4266 }
4267
4268 print "</body>\n" .
4269 "</html>";
4270 }
4271
4272 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4273 # Example: die_error(404, 'Hash not found')
4274 # By convention, use the following status codes (as defined in RFC 2616):
4275 # 400: Invalid or missing CGI parameters, or
4276 # requested object exists but has wrong type.
4277 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4278 # this server or project.
4279 # 404: Requested object/revision/project doesn't exist.
4280 # 500: The server isn't configured properly, or
4281 # an internal error occurred (e.g. failed assertions caused by bugs), or
4282 # an unknown error occurred (e.g. the git binary died unexpectedly).
4283 # 503: The server is currently unavailable (because it is overloaded,
4284 # or down for maintenance). Generally, this is a temporary state.
4285 sub die_error {
4286 my $status = shift || 500;
4287 my $error = esc_html(shift) || "Internal Server Error";
4288 my $extra = shift;
4289 my %opts = @_;
4290
4291 my %http_responses = (
4292 400 => '400 Bad Request',
4293 403 => '403 Forbidden',
4294 404 => '404 Not Found',
4295 500 => '500 Internal Server Error',
4296 503 => '503 Service Unavailable',
4297 );
4298 git_header_html($http_responses{$status}, undef, %opts);
4299 print <<EOF;
4300 <div class="page_body">
4301 <br /><br />
4302 $status - $error
4303 <br />
4304 EOF
4305 if (defined $extra) {
4306 print "<hr />\n" .
4307 "$extra\n";
4308 }
4309 print "</div>\n";
4310
4311 git_footer_html();
4312 goto DONE_GITWEB
4313 unless ($opts{'-error_handler'});
4314 }
4315
4316 ## ----------------------------------------------------------------------
4317 ## functions printing or outputting HTML: navigation
4318
4319 sub git_print_page_nav {
4320 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4321 $extra = '' if !defined $extra; # pager or formats
4322
4323 my @navs = qw(summary shortlog log commit commitdiff tree);
4324 if ($suppress) {
4325 @navs = grep { $_ ne $suppress } @navs;
4326 }
4327
4328 my %arg = map { $_ => {action=>$_} } @navs;
4329 if (defined $head) {
4330 for (qw(commit commitdiff)) {
4331 $arg{$_}{'hash'} = $head;
4332 }
4333 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4334 for (qw(shortlog log)) {
4335 $arg{$_}{'hash'} = $head;
4336 }
4337 }
4338 }
4339
4340 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4341 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4342
4343 my @actions = gitweb_get_feature('actions');
4344 my %repl = (
4345 '%' => '%',
4346 'n' => $project, # project name
4347 'f' => $git_dir, # project path within filesystem
4348 'h' => $treehead || '', # current hash ('h' parameter)
4349 'b' => $treebase || '', # hash base ('hb' parameter)
4350 );
4351 while (@actions) {
4352 my ($label, $link, $pos) = splice(@actions,0,3);
4353 # insert
4354 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4355 # munch munch
4356 $link =~ s/%([%nfhb])/$repl{$1}/g;
4357 $arg{$label}{'_href'} = $link;
4358 }
4359
4360 print "<div class=\"page_nav\">\n" .
4361 (join " | ",
4362 map { $_ eq $current ?
4363 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4364 } @navs);
4365 print "<br/>\n$extra<br/>\n" .
4366 "</div>\n";
4367 }
4368
4369 # returns a submenu for the nagivation of the refs views (tags, heads,
4370 # remotes) with the current view disabled and the remotes view only
4371 # available if the feature is enabled
4372 sub format_ref_views {
4373 my ($current) = @_;
4374 my @ref_views = qw{tags heads};
4375 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4376 return join " | ", map {
4377 $_ eq $current ? $_ :
4378 $cgi->a({-href => href(action=>$_)}, $_)
4379 } @ref_views
4380 }
4381
4382 sub format_paging_nav {
4383 my ($action, $page, $has_next_link) = @_;
4384 my $paging_nav;
4385
4386
4387 if ($page > 0) {
4388 $paging_nav .=
4389 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4390 " &sdot; " .
4391 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4392 -accesskey => "p", -title => "Alt-p"}, "prev");
4393 } else {
4394 $paging_nav .= "first &sdot; prev";
4395 }
4396
4397 if ($has_next_link) {
4398 $paging_nav .= " &sdot; " .
4399 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4400 -accesskey => "n", -title => "Alt-n"}, "next");
4401 } else {
4402 $paging_nav .= " &sdot; next";
4403 }
4404
4405 return $paging_nav;
4406 }
4407
4408 ## ......................................................................
4409 ## functions printing or outputting HTML: div
4410
4411 sub git_print_header_div {
4412 my ($action, $title, $hash, $hash_base) = @_;
4413 my %args = ();
4414
4415 $args{'action'} = $action;
4416 $args{'hash'} = $hash if $hash;
4417 $args{'hash_base'} = $hash_base if $hash_base;
4418
4419 print "<div class=\"header\">\n" .
4420 $cgi->a({-href => href(%args), -class => "title"},
4421 $title ? $title : $action) .
4422 "\n</div>\n";
4423 }
4424
4425 sub format_repo_url {
4426 my ($name, $url) = @_;
4427 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4428 }
4429
4430 # Group output by placing it in a DIV element and adding a header.
4431 # Options for start_div() can be provided by passing a hash reference as the
4432 # first parameter to the function.
4433 # Options to git_print_header_div() can be provided by passing an array
4434 # reference. This must follow the options to start_div if they are present.
4435 # The content can be a scalar, which is output as-is, a scalar reference, which
4436 # is output after html escaping, an IO handle passed either as *handle or
4437 # *handle{IO}, or a function reference. In the latter case all following
4438 # parameters will be taken as argument to the content function call.
4439 sub git_print_section {
4440 my ($div_args, $header_args, $content);
4441 my $arg = shift;
4442 if (ref($arg) eq 'HASH') {
4443 $div_args = $arg;
4444 $arg = shift;
4445 }
4446 if (ref($arg) eq 'ARRAY') {
4447 $header_args = $arg;
4448 $arg = shift;
4449 }
4450 $content = $arg;
4451
4452 print $cgi->start_div($div_args);
4453 git_print_header_div(@$header_args);
4454
4455 if (ref($content) eq 'CODE') {
4456 $content->(@_);
4457 } elsif (ref($content) eq 'SCALAR') {
4458 print esc_html($$content);
4459 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4460 print <$content>;
4461 } elsif (!ref($content) && defined($content)) {
4462 print $content;
4463 }
4464
4465 print $cgi->end_div;
4466 }
4467
4468 sub format_timestamp_html {
4469 my $date = shift;
4470 my $strtime = $date->{'rfc2822'};
4471
4472 my (undef, undef, $datetime_class) =
4473 gitweb_get_feature('javascript-timezone');
4474 if ($datetime_class) {
4475 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4476 }
4477
4478 my $localtime_format = '(%02d:%02d %s)';
4479 if ($date->{'hour_local'} < 6) {
4480 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4481 }
4482 $strtime .= ' ' .
4483 sprintf($localtime_format,
4484 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4485
4486 return $strtime;
4487 }
4488
4489 # Outputs the author name and date in long form
4490 sub git_print_authorship {
4491 my $co = shift;
4492 my %opts = @_;
4493 my $tag = $opts{-tag} || 'div';
4494 my $author = $co->{'author_name'};
4495
4496 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4497 print "<$tag class=\"author_date\">" .
4498 format_search_author($author, "author", esc_html($author)) .
4499 " [".format_timestamp_html(\%ad)."]".
4500 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4501 "</$tag>\n";
4502 }
4503
4504 # Outputs table rows containing the full author or committer information,
4505 # in the format expected for 'commit' view (& similar).
4506 # Parameters are a commit hash reference, followed by the list of people
4507 # to output information for. If the list is empty it defaults to both
4508 # author and committer.
4509 sub git_print_authorship_rows {
4510 my $co = shift;
4511 # too bad we can't use @people = @_ || ('author', 'committer')
4512 my @people = @_;
4513 @people = ('author', 'committer') unless @people;
4514 foreach my $who (@people) {
4515 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4516 print "<tr><td>$who</td><td>" .
4517 format_search_author($co->{"${who}_name"}, $who,
4518 esc_html($co->{"${who}_name"})) . " " .
4519 format_search_author($co->{"${who}_email"}, $who,
4520 esc_html("<" . $co->{"${who}_email"} . ">")) .
4521 "</td><td rowspan=\"2\">" .
4522 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4523 "</td></tr>\n" .
4524 "<tr>" .
4525 "<td></td><td>" .
4526 format_timestamp_html(\%wd) .
4527 "</td>" .
4528 "</tr>\n";
4529 }
4530 }
4531
4532 sub git_print_page_path {
4533 my $name = shift;
4534 my $type = shift;
4535 my $hb = shift;
4536
4537
4538 print "<div class=\"page_path\">";
4539 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4540 -title => 'tree root'}, to_utf8("[$project]"));
4541 print " / ";
4542 if (defined $name) {
4543 my @dirname = split '/', $name;
4544 my $basename = pop @dirname;
4545 my $fullname = '';
4546
4547 foreach my $dir (@dirname) {
4548 $fullname .= ($fullname ? '/' : '') . $dir;
4549 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4550 hash_base=>$hb),
4551 -title => $fullname}, esc_path($dir));
4552 print " / ";
4553 }
4554 if (defined $type && $type eq 'blob') {
4555 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4556 hash_base=>$hb),
4557 -title => $name}, esc_path($basename));
4558 } elsif (defined $type && $type eq 'tree') {
4559 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4560 hash_base=>$hb),
4561 -title => $name}, esc_path($basename));
4562 print " / ";
4563 } else {
4564 print esc_path($basename);
4565 }
4566 }
4567 print "<br/></div>\n";
4568 }
4569
4570 sub git_print_log {
4571 my $log = shift;
4572 my %opts = @_;
4573
4574 if ($opts{'-remove_title'}) {
4575 # remove title, i.e. first line of log
4576 shift @$log;
4577 }
4578 # remove leading empty lines
4579 while (defined $log->[0] && $log->[0] eq "") {
4580 shift @$log;
4581 }
4582
4583 # print log
4584 my $skip_blank_line = 0;
4585 foreach my $line (@$log) {
4586 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4587 if (! $opts{'-remove_signoff'}) {
4588 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4589 $skip_blank_line = 1;
4590 }
4591 next;
4592 }
4593
4594 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4595 if (! $opts{'-remove_signoff'}) {
4596 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4597 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4598 "</span><br/>\n";
4599 $skip_blank_line = 1;
4600 }
4601 next;
4602 }
4603
4604 # print only one empty line
4605 # do not print empty line after signoff
4606 if ($line eq "") {
4607 next if ($skip_blank_line);
4608 $skip_blank_line = 1;
4609 } else {
4610 $skip_blank_line = 0;
4611 }
4612
4613 print format_log_line_html($line) . "<br/>\n";
4614 }
4615
4616 if ($opts{'-final_empty_line'}) {
4617 # end with single empty line
4618 print "<br/>\n" unless $skip_blank_line;
4619 }
4620 }
4621
4622 # return link target (what link points to)
4623 sub git_get_link_target {
4624 my $hash = shift;
4625 my $link_target;
4626
4627 # read link
4628 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4629 or return;
4630 {
4631 local $/ = undef;
4632 $link_target = <$fd>;
4633 }
4634 close $fd
4635 or return;
4636
4637 return $link_target;
4638 }
4639
4640 # given link target, and the directory (basedir) the link is in,
4641 # return target of link relative to top directory (top tree);
4642 # return undef if it is not possible (including absolute links).
4643 sub normalize_link_target {
4644 my ($link_target, $basedir) = @_;
4645
4646 # absolute symlinks (beginning with '/') cannot be normalized
4647 return if (substr($link_target, 0, 1) eq '/');
4648
4649 # normalize link target to path from top (root) tree (dir)
4650 my $path;
4651 if ($basedir) {
4652 $path = $basedir . '/' . $link_target;
4653 } else {
4654 # we are in top (root) tree (dir)
4655 $path = $link_target;
4656 }
4657
4658 # remove //, /./, and /../
4659 my @path_parts;
4660 foreach my $part (split('/', $path)) {
4661 # discard '.' and ''
4662 next if (!$part || $part eq '.');
4663 # handle '..'
4664 if ($part eq '..') {
4665 if (@path_parts) {
4666 pop @path_parts;
4667 } else {
4668 # link leads outside repository (outside top dir)
4669 return;
4670 }
4671 } else {
4672 push @path_parts, $part;
4673 }
4674 }
4675 $path = join('/', @path_parts);
4676
4677 return $path;
4678 }
4679
4680 # print tree entry (row of git_tree), but without encompassing <tr> element
4681 sub git_print_tree_entry {
4682 my ($t, $basedir, $hash_base, $have_blame) = @_;
4683
4684 my %base_key = ();
4685 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4686
4687 # The format of a table row is: mode list link. Where mode is
4688 # the mode of the entry, list is the name of the entry, an href,
4689 # and link is the action links of the entry.
4690
4691 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4692 if (exists $t->{'size'}) {
4693 print "<td class=\"size\">$t->{'size'}</td>\n";
4694 }
4695 if ($t->{'type'} eq "blob") {
4696 print "<td class=\"list\">" .
4697 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4698 file_name=>"$basedir$t->{'name'}", %base_key),
4699 -class => "list"}, esc_path($t->{'name'}));
4700 if (S_ISLNK(oct $t->{'mode'})) {
4701 my $link_target = git_get_link_target($t->{'hash'});
4702 if ($link_target) {
4703 my $norm_target = normalize_link_target($link_target, $basedir);
4704 if (defined $norm_target) {
4705 print " -> " .
4706 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4707 file_name=>$norm_target),
4708 -title => $norm_target}, esc_path($link_target));
4709 } else {
4710 print " -> " . esc_path($link_target);
4711 }
4712 }
4713 }
4714 print "</td>\n";
4715 print "<td class=\"link\">";
4716 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4717 file_name=>"$basedir$t->{'name'}", %base_key)},
4718 "blob");
4719 if ($have_blame) {
4720 print " | " .
4721 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4722 file_name=>"$basedir$t->{'name'}", %base_key)},
4723 "blame");
4724 }
4725 if (defined $hash_base) {
4726 print " | " .
4727 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4728 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4729 "history");
4730 }
4731 print " | " .
4732 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4733 file_name=>"$basedir$t->{'name'}")},
4734 "raw");
4735 print "</td>\n";
4736
4737 } elsif ($t->{'type'} eq "tree") {
4738 print "<td class=\"list\">";
4739 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4740 file_name=>"$basedir$t->{'name'}",
4741 %base_key)},
4742 esc_path($t->{'name'}));
4743 print "</td>\n";
4744 print "<td class=\"link\">";
4745 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4746 file_name=>"$basedir$t->{'name'}",
4747 %base_key)},
4748 "tree");
4749 if (defined $hash_base) {
4750 print " | " .
4751 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4752 file_name=>"$basedir$t->{'name'}")},
4753 "history");
4754 }
4755 print "</td>\n";
4756 } else {
4757 # unknown object: we can only present history for it
4758 # (this includes 'commit' object, i.e. submodule support)
4759 print "<td class=\"list\">" .
4760 esc_path($t->{'name'}) .
4761 "</td>\n";
4762 print "<td class=\"link\">";
4763 if (defined $hash_base) {
4764 print $cgi->a({-href => href(action=>"history",
4765 hash_base=>$hash_base,
4766 file_name=>"$basedir$t->{'name'}")},
4767 "history");
4768 }
4769 print "</td>\n";
4770 }
4771 }
4772
4773 ## ......................................................................
4774 ## functions printing large fragments of HTML
4775
4776 # get pre-image filenames for merge (combined) diff
4777 sub fill_from_file_info {
4778 my ($diff, @parents) = @_;
4779
4780 $diff->{'from_file'} = [ ];
4781 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4782 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4783 if ($diff->{'status'}[$i] eq 'R' ||
4784 $diff->{'status'}[$i] eq 'C') {
4785 $diff->{'from_file'}[$i] =
4786 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4787 }
4788 }
4789
4790 return $diff;
4791 }
4792
4793 # is current raw difftree line of file deletion
4794 sub is_deleted {
4795 my $diffinfo = shift;
4796
4797 return $diffinfo->{'to_id'} eq ('0' x 40);
4798 }
4799
4800 # does patch correspond to [previous] difftree raw line
4801 # $diffinfo - hashref of parsed raw diff format
4802 # $patchinfo - hashref of parsed patch diff format
4803 # (the same keys as in $diffinfo)
4804 sub is_patch_split {
4805 my ($diffinfo, $patchinfo) = @_;
4806
4807 return defined $diffinfo && defined $patchinfo
4808 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4809 }
4810
4811
4812 sub git_difftree_body {
4813 my ($difftree, $hash, @parents) = @_;
4814 my ($parent) = $parents[0];
4815 my $have_blame = gitweb_check_feature('blame');
4816 if ($#{$difftree} > 10) {
4817 print "<div class=\"list_head\">\n";
4818 print(($#{$difftree} + 1) . " files changed:\n");
4819 print "</div>\n";
4820 }
4821
4822 print "<table class=\"" .
4823 (@parents > 1 ? "combined " : "") .
4824 "diff_tree\">\n";
4825
4826 # header only for combined diff in 'commitdiff' view
4827 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4828 if ($has_header) {
4829 # table header
4830 print "<thead><tr>\n" .
4831 "<th></th><th></th>\n"; # filename, patchN link
4832 for (my $i = 0; $i < @parents; $i++) {
4833 my $par = $parents[$i];
4834 print "<th>" .
4835 $cgi->a({-href => href(action=>"commitdiff",
4836 hash=>$hash, hash_parent=>$par),
4837 -title => 'commitdiff to parent number ' .
4838 ($i+1) . ': ' . substr($par,0,7)},
4839 $i+1) .
4840 "&nbsp;</th>\n";
4841 }
4842 print "</tr></thead>\n<tbody>\n";
4843 }
4844
4845 my $alternate = 1;
4846 my $patchno = 0;
4847 foreach my $line (@{$difftree}) {
4848 my $diff = parsed_difftree_line($line);
4849
4850 if ($alternate) {
4851 print "<tr class=\"dark\">\n";
4852 } else {
4853 print "<tr class=\"light\">\n";
4854 }
4855 $alternate ^= 1;
4856
4857 if (exists $diff->{'nparents'}) { # combined diff
4858
4859 fill_from_file_info($diff, @parents)
4860 unless exists $diff->{'from_file'};
4861
4862 if (!is_deleted($diff)) {
4863 # file exists in the result (child) commit
4864 print "<td>" .
4865 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4866 file_name=>$diff->{'to_file'},
4867 hash_base=>$hash),
4868 -class => "list"}, esc_path($diff->{'to_file'})) .
4869 "</td>\n";
4870 } else {
4871 print "<td>" .
4872 esc_path($diff->{'to_file'}) .
4873 "</td>\n";
4874 }
4875
4876 if ($action eq 'commitdiff') {
4877 # link to patch
4878 $patchno++;
4879 print "<td class=\"link\">" .
4880 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4881 "patch") .
4882 " | " .
4883 "</td>\n";
4884 }
4885
4886 my $has_history = 0;
4887 my $not_deleted = 0;
4888 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4889 my $hash_parent = $parents[$i];
4890 my $from_hash = $diff->{'from_id'}[$i];
4891 my $from_path = $diff->{'from_file'}[$i];
4892 my $status = $diff->{'status'}[$i];
4893
4894 $has_history ||= ($status ne 'A');
4895 $not_deleted ||= ($status ne 'D');
4896
4897 if ($status eq 'A') {
4898 print "<td class=\"link\" align=\"right\"> | </td>\n";
4899 } elsif ($status eq 'D') {
4900 print "<td class=\"link\">" .
4901 $cgi->a({-href => href(action=>"blob",
4902 hash_base=>$hash,
4903 hash=>$from_hash,
4904 file_name=>$from_path)},
4905 "blob" . ($i+1)) .
4906 " | </td>\n";
4907 } else {
4908 if ($diff->{'to_id'} eq $from_hash) {
4909 print "<td class=\"link nochange\">";
4910 } else {
4911 print "<td class=\"link\">";
4912 }
4913 print $cgi->a({-href => href(action=>"blobdiff",
4914 hash=>$diff->{'to_id'},
4915 hash_parent=>$from_hash,
4916 hash_base=>$hash,
4917 hash_parent_base=>$hash_parent,
4918 file_name=>$diff->{'to_file'},
4919 file_parent=>$from_path)},
4920 "diff" . ($i+1)) .
4921 " | </td>\n";
4922 }
4923 }
4924
4925 print "<td class=\"link\">";
4926 if ($not_deleted) {
4927 print $cgi->a({-href => href(action=>"blob",
4928 hash=>$diff->{'to_id'},
4929 file_name=>$diff->{'to_file'},
4930 hash_base=>$hash)},
4931 "blob");
4932 print " | " if ($has_history);
4933 }
4934 if ($has_history) {
4935 print $cgi->a({-href => href(action=>"history",
4936 file_name=>$diff->{'to_file'},
4937 hash_base=>$hash)},
4938 "history");
4939 }
4940 print "</td>\n";
4941
4942 print "</tr>\n";
4943 next; # instead of 'else' clause, to avoid extra indent
4944 }
4945 # else ordinary diff
4946
4947 my ($to_mode_oct, $to_mode_str, $to_file_type);
4948 my ($from_mode_oct, $from_mode_str, $from_file_type);
4949 if ($diff->{'to_mode'} ne ('0' x 6)) {
4950 $to_mode_oct = oct $diff->{'to_mode'};
4951 if (S_ISREG($to_mode_oct)) { # only for regular file
4952 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4953 }
4954 $to_file_type = file_type($diff->{'to_mode'});
4955 }
4956 if ($diff->{'from_mode'} ne ('0' x 6)) {
4957 $from_mode_oct = oct $diff->{'from_mode'};
4958 if (S_ISREG($from_mode_oct)) { # only for regular file
4959 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4960 }
4961 $from_file_type = file_type($diff->{'from_mode'});
4962 }
4963
4964 if ($diff->{'status'} eq "A") { # created
4965 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4966 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4967 $mode_chng .= "]</span>";
4968 print "<td>";
4969 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4970 hash_base=>$hash, file_name=>$diff->{'file'}),
4971 -class => "list"}, esc_path($diff->{'file'}));
4972 print "</td>\n";
4973 print "<td>$mode_chng</td>\n";
4974 print "<td class=\"link\">";
4975 if ($action eq 'commitdiff') {
4976 # link to patch
4977 $patchno++;
4978 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4979 "patch") .
4980 " | ";
4981 }
4982 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4983 hash_base=>$hash, file_name=>$diff->{'file'})},
4984 "blob");
4985 print "</td>\n";
4986
4987 } elsif ($diff->{'status'} eq "D") { # deleted
4988 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4989 print "<td>";
4990 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4991 hash_base=>$parent, file_name=>$diff->{'file'}),
4992 -class => "list"}, esc_path($diff->{'file'}));
4993 print "</td>\n";
4994 print "<td>$mode_chng</td>\n";
4995 print "<td class=\"link\">";
4996 if ($action eq 'commitdiff') {
4997 # link to patch
4998 $patchno++;
4999 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5000 "patch") .
5001 " | ";
5002 }
5003 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5004 hash_base=>$parent, file_name=>$diff->{'file'})},
5005 "blob") . " | ";
5006 if ($have_blame) {
5007 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5008 file_name=>$diff->{'file'})},
5009 "blame") . " | ";
5010 }
5011 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5012 file_name=>$diff->{'file'})},
5013 "history");
5014 print "</td>\n";
5015
5016 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5017 my $mode_chnge = "";
5018 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5019 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5020 if ($from_file_type ne $to_file_type) {
5021 $mode_chnge .= " from $from_file_type to $to_file_type";
5022 }
5023 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5024 if ($from_mode_str && $to_mode_str) {
5025 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5026 } elsif ($to_mode_str) {
5027 $mode_chnge .= " mode: $to_mode_str";
5028 }
5029 }
5030 $mode_chnge .= "]</span>\n";
5031 }
5032 print "<td>";
5033 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5034 hash_base=>$hash, file_name=>$diff->{'file'}),
5035 -class => "list"}, esc_path($diff->{'file'}));
5036 print "</td>\n";
5037 print "<td>$mode_chnge</td>\n";
5038 print "<td class=\"link\">";
5039 if ($action eq 'commitdiff') {
5040 # link to patch
5041 $patchno++;
5042 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5043 "patch") .
5044 " | ";
5045 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5046 # "commit" view and modified file (not onlu mode changed)
5047 print $cgi->a({-href => href(action=>"blobdiff",
5048 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5049 hash_base=>$hash, hash_parent_base=>$parent,
5050 file_name=>$diff->{'file'})},
5051 "diff") .
5052 " | ";
5053 }
5054 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5055 hash_base=>$hash, file_name=>$diff->{'file'})},
5056 "blob") . " | ";
5057 if ($have_blame) {
5058 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5059 file_name=>$diff->{'file'})},
5060 "blame") . " | ";
5061 }
5062 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5063 file_name=>$diff->{'file'})},
5064 "history");
5065 print "</td>\n";
5066
5067 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5068 my %status_name = ('R' => 'moved', 'C' => 'copied');
5069 my $nstatus = $status_name{$diff->{'status'}};
5070 my $mode_chng = "";
5071 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5072 # mode also for directories, so we cannot use $to_mode_str
5073 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5074 }
5075 print "<td>" .
5076 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5077 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5078 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5079 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5080 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5081 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5082 -class => "list"}, esc_path($diff->{'from_file'})) .
5083 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5084 "<td class=\"link\">";
5085 if ($action eq 'commitdiff') {
5086 # link to patch
5087 $patchno++;
5088 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5089 "patch") .
5090 " | ";
5091 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5092 # "commit" view and modified file (not only pure rename or copy)
5093 print $cgi->a({-href => href(action=>"blobdiff",
5094 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5095 hash_base=>$hash, hash_parent_base=>$parent,
5096 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5097 "diff") .
5098 " | ";
5099 }
5100 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5101 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5102 "blob") . " | ";
5103 if ($have_blame) {
5104 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5105 file_name=>$diff->{'to_file'})},
5106 "blame") . " | ";
5107 }
5108 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5109 file_name=>$diff->{'to_file'})},
5110 "history");
5111 print "</td>\n";
5112
5113 } # we should not encounter Unmerged (U) or Unknown (X) status
5114 print "</tr>\n";
5115 }
5116 print "</tbody>" if $has_header;
5117 print "</table>\n";
5118 }
5119
5120 # Print context lines and then rem/add lines in a side-by-side manner.
5121 sub print_sidebyside_diff_lines {
5122 my ($ctx, $rem, $add) = @_;
5123
5124 # print context block before add/rem block
5125 if (@$ctx) {
5126 print join '',
5127 '<div class="chunk_block ctx">',
5128 '<div class="old">',
5129 @$ctx,
5130 '</div>',
5131 '<div class="new">',
5132 @$ctx,
5133 '</div>',
5134 '</div>';
5135 }
5136
5137 if (!@$add) {
5138 # pure removal
5139 print join '',
5140 '<div class="chunk_block rem">',
5141 '<div class="old">',
5142 @$rem,
5143 '</div>',
5144 '</div>';
5145 } elsif (!@$rem) {
5146 # pure addition
5147 print join '',
5148 '<div class="chunk_block add">',
5149 '<div class="new">',
5150 @$add,
5151 '</div>',
5152 '</div>';
5153 } else {
5154 print join '',
5155 '<div class="chunk_block chg">',
5156 '<div class="old">',
5157 @$rem,
5158 '</div>',
5159 '<div class="new">',
5160 @$add,
5161 '</div>',
5162 '</div>';
5163 }
5164 }
5165
5166 # Print context lines and then rem/add lines in inline manner.
5167 sub print_inline_diff_lines {
5168 my ($ctx, $rem, $add) = @_;
5169
5170 print @$ctx, @$rem, @$add;
5171 }
5172
5173 # Format removed and added line, mark changed part and HTML-format them.
5174 # Implementation is based on contrib/diff-highlight
5175 sub format_rem_add_lines_pair {
5176 my ($rem, $add, $num_parents) = @_;
5177
5178 # We need to untabify lines before split()'ing them;
5179 # otherwise offsets would be invalid.
5180 chomp $rem;
5181 chomp $add;
5182 $rem = untabify($rem);
5183 $add = untabify($add);
5184
5185 my @rem = split(//, $rem);
5186 my @add = split(//, $add);
5187 my ($esc_rem, $esc_add);
5188 # Ignore leading +/- characters for each parent.
5189 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5190 my ($prefix_has_nonspace, $suffix_has_nonspace);
5191
5192 my $shorter = (@rem < @add) ? @rem : @add;
5193 while ($prefix_len < $shorter) {
5194 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5195
5196 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5197 $prefix_len++;
5198 }
5199
5200 while ($prefix_len + $suffix_len < $shorter) {
5201 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5202
5203 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5204 $suffix_len++;
5205 }
5206
5207 # Mark lines that are different from each other, but have some common
5208 # part that isn't whitespace. If lines are completely different, don't
5209 # mark them because that would make output unreadable, especially if
5210 # diff consists of multiple lines.
5211 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5212 $esc_rem = esc_html_hl_regions($rem, 'marked',
5213 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5214 $esc_add = esc_html_hl_regions($add, 'marked',
5215 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5216 } else {
5217 $esc_rem = esc_html($rem, -nbsp=>1);
5218 $esc_add = esc_html($add, -nbsp=>1);
5219 }
5220
5221 return format_diff_line(\$esc_rem, 'rem'),
5222 format_diff_line(\$esc_add, 'add');
5223 }
5224
5225 # HTML-format diff context, removed and added lines.
5226 sub format_ctx_rem_add_lines {
5227 my ($ctx, $rem, $add, $num_parents) = @_;
5228 my (@new_ctx, @new_rem, @new_add);
5229 my $can_highlight = 0;
5230 my $is_combined = ($num_parents > 1);
5231
5232 # Highlight if every removed line has a corresponding added line.
5233 if (@$add > 0 && @$add == @$rem) {
5234 $can_highlight = 1;
5235
5236 # Highlight lines in combined diff only if the chunk contains
5237 # diff between the same version, e.g.
5238 #
5239 # - a
5240 # - b
5241 # + c
5242 # + d
5243 #
5244 # Otherwise the highlightling would be confusing.
5245 if ($is_combined) {
5246 for (my $i = 0; $i < @$add; $i++) {
5247 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5248 my $prefix_add = substr($add->[$i], 0, $num_parents);
5249
5250 $prefix_rem =~ s/-/+/g;
5251
5252 if ($prefix_rem ne $prefix_add) {
5253 $can_highlight = 0;
5254 last;
5255 }
5256 }
5257 }
5258 }
5259
5260 if ($can_highlight) {
5261 for (my $i = 0; $i < @$add; $i++) {
5262 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5263 $rem->[$i], $add->[$i], $num_parents);
5264 push @new_rem, $line_rem;
5265 push @new_add, $line_add;
5266 }
5267 } else {
5268 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5269 @new_add = map { format_diff_line($_, 'add') } @$add;
5270 }
5271
5272 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5273
5274 return (\@new_ctx, \@new_rem, \@new_add);
5275 }
5276
5277 # Print context lines and then rem/add lines.
5278 sub print_diff_lines {
5279 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5280 my $is_combined = $num_parents > 1;
5281
5282 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5283 $num_parents);
5284
5285 if ($diff_style eq 'sidebyside' && !$is_combined) {
5286 print_sidebyside_diff_lines($ctx, $rem, $add);
5287 } else {
5288 # default 'inline' style and unknown styles
5289 print_inline_diff_lines($ctx, $rem, $add);
5290 }
5291 }
5292
5293 sub print_diff_chunk {
5294 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5295 my (@ctx, @rem, @add);
5296
5297 # The class of the previous line.
5298 my $prev_class = '';
5299
5300 return unless @chunk;
5301
5302 # incomplete last line might be among removed or added lines,
5303 # or both, or among context lines: find which
5304 for (my $i = 1; $i < @chunk; $i++) {
5305 if ($chunk[$i][0] eq 'incomplete') {
5306 $chunk[$i][0] = $chunk[$i-1][0];
5307 }
5308 }
5309
5310 # guardian
5311 push @chunk, ["", ""];
5312
5313 foreach my $line_info (@chunk) {
5314 my ($class, $line) = @$line_info;
5315
5316 # print chunk headers
5317 if ($class && $class eq 'chunk_header') {
5318 print format_diff_line($line, $class, $from, $to);
5319 next;
5320 }
5321
5322 ## print from accumulator when have some add/rem lines or end
5323 # of chunk (flush context lines), or when have add and rem
5324 # lines and new block is reached (otherwise add/rem lines could
5325 # be reordered)
5326 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5327 (@rem && @add && $class ne $prev_class)) {
5328 print_diff_lines(\@ctx, \@rem, \@add,
5329 $diff_style, $num_parents);
5330 @ctx = @rem = @add = ();
5331 }
5332
5333 ## adding lines to accumulator
5334 # guardian value
5335 last unless $line;
5336 # rem, add or change
5337 if ($class eq 'rem') {
5338 push @rem, $line;
5339 } elsif ($class eq 'add') {
5340 push @add, $line;
5341 }
5342 # context line
5343 if ($class eq 'ctx') {
5344 push @ctx, $line;
5345 }
5346
5347 $prev_class = $class;
5348 }
5349 }
5350
5351 sub git_patchset_body {
5352 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5353 my ($hash_parent) = $hash_parents[0];
5354
5355 my $is_combined = (@hash_parents > 1);
5356 my $patch_idx = 0;
5357 my $patch_number = 0;
5358 my $patch_line;
5359 my $diffinfo;
5360 my $to_name;
5361 my (%from, %to);
5362 my @chunk; # for side-by-side diff
5363
5364 print "<div class=\"patchset\">\n";
5365
5366 # skip to first patch
5367 while ($patch_line = <$fd>) {
5368 chomp $patch_line;
5369
5370 last if ($patch_line =~ m/^diff /);
5371 }
5372
5373 PATCH:
5374 while ($patch_line) {
5375
5376 # parse "git diff" header line
5377 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5378 # $1 is from_name, which we do not use
5379 $to_name = unquote($2);
5380 $to_name =~ s!^b/!!;
5381 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5382 # $1 is 'cc' or 'combined', which we do not use
5383 $to_name = unquote($2);
5384 } else {
5385 $to_name = undef;
5386 }
5387
5388 # check if current patch belong to current raw line
5389 # and parse raw git-diff line if needed
5390 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5391 # this is continuation of a split patch
5392 print "<div class=\"patch cont\">\n";
5393 } else {
5394 # advance raw git-diff output if needed
5395 $patch_idx++ if defined $diffinfo;
5396
5397 # read and prepare patch information
5398 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5399
5400 # compact combined diff output can have some patches skipped
5401 # find which patch (using pathname of result) we are at now;
5402 if ($is_combined) {
5403 while ($to_name ne $diffinfo->{'to_file'}) {
5404 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5405 format_diff_cc_simplified($diffinfo, @hash_parents) .
5406 "</div>\n"; # class="patch"
5407
5408 $patch_idx++;
5409 $patch_number++;
5410
5411 last if $patch_idx > $#$difftree;
5412 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5413 }
5414 }
5415
5416 # modifies %from, %to hashes
5417 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5418
5419 # this is first patch for raw difftree line with $patch_idx index
5420 # we index @$difftree array from 0, but number patches from 1
5421 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5422 }
5423
5424 # git diff header
5425 #assert($patch_line =~ m/^diff /) if DEBUG;
5426 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5427 $patch_number++;
5428 # print "git diff" header
5429 print format_git_diff_header_line($patch_line, $diffinfo,
5430 \%from, \%to);
5431
5432 # print extended diff header
5433 print "<div class=\"diff extended_header\">\n";
5434 EXTENDED_HEADER:
5435 while ($patch_line = <$fd>) {
5436 chomp $patch_line;
5437
5438 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5439
5440 print format_extended_diff_header_line($patch_line, $diffinfo,
5441 \%from, \%to);
5442 }
5443 print "</div>\n"; # class="diff extended_header"
5444
5445 # from-file/to-file diff header
5446 if (! $patch_line) {
5447 print "</div>\n"; # class="patch"
5448 last PATCH;
5449 }
5450 next PATCH if ($patch_line =~ m/^diff /);
5451 #assert($patch_line =~ m/^---/) if DEBUG;
5452
5453 my $last_patch_line = $patch_line;
5454 $patch_line = <$fd>;
5455 chomp $patch_line;
5456 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5457
5458 print format_diff_from_to_header($last_patch_line, $patch_line,
5459 $diffinfo, \%from, \%to,
5460 @hash_parents);
5461
5462 # the patch itself
5463 LINE:
5464 while ($patch_line = <$fd>) {
5465 chomp $patch_line;
5466
5467 next PATCH if ($patch_line =~ m/^diff /);
5468
5469 my $class = diff_line_class($patch_line, \%from, \%to);
5470
5471 if ($class eq 'chunk_header') {
5472 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5473 @chunk = ();
5474 }
5475
5476 push @chunk, [ $class, $patch_line ];
5477 }
5478
5479 } continue {
5480 if (@chunk) {
5481 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5482 @chunk = ();
5483 }
5484 print "</div>\n"; # class="patch"
5485 }
5486
5487 # for compact combined (--cc) format, with chunk and patch simplification
5488 # the patchset might be empty, but there might be unprocessed raw lines
5489 for (++$patch_idx if $patch_number > 0;
5490 $patch_idx < @$difftree;
5491 ++$patch_idx) {
5492 # read and prepare patch information
5493 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5494
5495 # generate anchor for "patch" links in difftree / whatchanged part
5496 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5497 format_diff_cc_simplified($diffinfo, @hash_parents) .
5498 "</div>\n"; # class="patch"
5499
5500 $patch_number++;
5501 }
5502
5503 if ($patch_number == 0) {
5504 if (@hash_parents > 1) {
5505 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5506 } else {
5507 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5508 }
5509 }
5510
5511 print "</div>\n"; # class="patchset"
5512 }
5513
5514 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5515
5516 sub git_project_search_form {
5517 my ($searchtext, $search_use_regexp) = @_;
5518
5519 my $limit = '';
5520 if ($project_filter) {
5521 $limit = " in '$project_filter/'";
5522 }
5523
5524 print "<div class=\"projsearch\">\n";
5525 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5526 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5527 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5528 if (defined $project_filter);
5529 print $cgi->textfield(-name => 's', -value => $searchtext,
5530 -title => "Search project by name and description$limit",
5531 -size => 60) . "\n" .
5532 "<span title=\"Extended regular expression\">" .
5533 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5534 -checked => $search_use_regexp) .
5535 "</span>\n" .
5536 $cgi->submit(-name => 'btnS', -value => 'Search') .
5537 $cgi->end_form() . "\n" .
5538 $cgi->a({-href => href(project => undef, searchtext => undef,
5539 project_filter => $project_filter)},
5540 esc_html("List all projects$limit")) . "<br />\n";
5541 print "</div>\n";
5542 }
5543
5544 # entry for given @keys needs filling if at least one of keys in list
5545 # is not present in %$project_info
5546 sub project_info_needs_filling {
5547 my ($project_info, @keys) = @_;
5548
5549 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5550 foreach my $key (@keys) {
5551 if (!exists $project_info->{$key}) {
5552 return 1;
5553 }
5554 }
5555 return;
5556 }
5557
5558 # fills project list info (age, description, owner, category, forks, etc.)
5559 # for each project in the list, removing invalid projects from
5560 # returned list, or fill only specified info.
5561 #
5562 # Invalid projects are removed from the returned list if and only if you
5563 # ask 'age' or 'age_string' to be filled, because they are the only fields
5564 # that run unconditionally git command that requires repository, and
5565 # therefore do always check if project repository is invalid.
5566 #
5567 # USAGE:
5568 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5569 # ensures that 'descr_long' and 'ctags' fields are filled
5570 # * @project_list = fill_project_list_info(\@project_list)
5571 # ensures that all fields are filled (and invalid projects removed)
5572 #
5573 # NOTE: modifies $projlist, but does not remove entries from it
5574 sub fill_project_list_info {
5575 my ($projlist, @wanted_keys) = @_;
5576 my @projects;
5577 my $filter_set = sub { return @_; };
5578 if (@wanted_keys) {
5579 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5580 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5581 }
5582
5583 my $show_ctags = gitweb_check_feature('ctags');
5584 PROJECT:
5585 foreach my $pr (@$projlist) {
5586 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5587 my (@activity) = git_get_last_activity($pr->{'path'});
5588 unless (@activity) {
5589 next PROJECT;
5590 }
5591 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5592 }
5593 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5594 my $descr = git_get_project_description($pr->{'path'}) || "";
5595 $descr = to_utf8($descr);
5596 $pr->{'descr_long'} = $descr;
5597 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5598 }
5599 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5600 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5601 }
5602 if ($show_ctags &&
5603 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5604 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5605 }
5606 if ($projects_list_group_categories &&
5607 project_info_needs_filling($pr, $filter_set->('category'))) {
5608 my $cat = git_get_project_category($pr->{'path'}) ||
5609 $project_list_default_category;
5610 $pr->{'category'} = to_utf8($cat);
5611 }
5612
5613 push @projects, $pr;
5614 }
5615
5616 return @projects;
5617 }
5618
5619 sub sort_projects_list {
5620 my ($projlist, $order) = @_;
5621
5622 sub order_str {
5623 my $key = shift;
5624 return sub { $a->{$key} cmp $b->{$key} };
5625 }
5626
5627 sub order_num_then_undef {
5628 my $key = shift;
5629 return sub {
5630 defined $a->{$key} ?
5631 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5632 (defined $b->{$key} ? 1 : 0)
5633 };
5634 }
5635
5636 my %orderings = (
5637 project => order_str('path'),
5638 descr => order_str('descr_long'),
5639 owner => order_str('owner'),
5640 age => order_num_then_undef('age'),
5641 );
5642
5643 my $ordering = $orderings{$order};
5644 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5645 }
5646
5647 # returns a hash of categories, containing the list of project
5648 # belonging to each category
5649 sub build_projlist_by_category {
5650 my ($projlist, $from, $to) = @_;
5651 my %categories;
5652
5653 $from = 0 unless defined $from;
5654 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5655
5656 for (my $i = $from; $i <= $to; $i++) {
5657 my $pr = $projlist->[$i];
5658 push @{$categories{ $pr->{'category'} }}, $pr;
5659 }
5660
5661 return wantarray ? %categories : \%categories;
5662 }
5663
5664 # print 'sort by' <th> element, generating 'sort by $name' replay link
5665 # if that order is not selected
5666 sub print_sort_th {
5667 print format_sort_th(@_);
5668 }
5669
5670 sub format_sort_th {
5671 my ($name, $order, $header) = @_;
5672 my $sort_th = "";
5673 $header ||= ucfirst($name);
5674
5675 if ($order eq $name) {
5676 $sort_th .= "<th>$header</th>\n";
5677 } else {
5678 $sort_th .= "<th>" .
5679 $cgi->a({-href => href(-replay=>1, order=>$name),
5680 -class => "header"}, $header) .
5681 "</th>\n";
5682 }
5683
5684 return $sort_th;
5685 }
5686
5687 sub git_project_list_rows {
5688 my ($projlist, $from, $to, $check_forks) = @_;
5689
5690 $from = 0 unless defined $from;
5691 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5692
5693 my $alternate = 1;
5694 for (my $i = $from; $i <= $to; $i++) {
5695 my $pr = $projlist->[$i];
5696
5697 if ($alternate) {
5698 print "<tr class=\"dark\">\n";
5699 } else {
5700 print "<tr class=\"light\">\n";
5701 }
5702 $alternate ^= 1;
5703
5704 if ($check_forks) {
5705 print "<td>";
5706 if ($pr->{'forks'}) {
5707 my $nforks = scalar @{$pr->{'forks'}};
5708 if ($nforks > 0) {
5709 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5710 -title => "$nforks forks"}, "+");
5711 } else {
5712 print $cgi->span({-title => "$nforks forks"}, "+");
5713 }
5714 }
5715 print "</td>\n";
5716 }
5717 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5718 -class => "list"},
5719 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5720 "</td>\n" .
5721 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5722 -class => "list",
5723 -title => $pr->{'descr_long'}},
5724 $search_regexp
5725 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5726 $pr->{'descr'}, $search_regexp)
5727 : esc_html($pr->{'descr'})) .
5728 "</td>\n";
5729 unless ($omit_owner) {
5730 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5731 }
5732 unless ($omit_age_column) {
5733 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5734 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5735 }
5736 print"<td class=\"link\">" .
5737 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5738 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5739 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5740 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5741 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5742 "</td>\n" .
5743 "</tr>\n";
5744 }
5745 print '<tr><td colspan="'.($check_forks ? '1' : '2').'">&nbsp;</td>';
5746 print "<td>".($to + 1)." project".($to > 1 ? ($to < 1 ? "" : "s") : "")." found</td><td colspan=\"3\">&nbsp;</td></tr>";
5747 }
5748
5749 sub git_project_list_body {
5750 # actually uses global variable $project
5751 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5752 my @projects = @$projlist;
5753
5754 my $check_forks = gitweb_check_feature('forks');
5755 my $show_ctags = gitweb_check_feature('ctags');
5756 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5757 $check_forks = undef
5758 if ($tagfilter || $search_regexp);
5759
5760 # filtering out forks before filling info allows to do less work
5761 @projects = filter_forks_from_projects_list(\@projects)
5762 if ($check_forks);
5763 # search_projects_list pre-fills required info
5764 @projects = search_projects_list(\@projects,
5765 'search_regexp' => $search_regexp,
5766 'tagfilter' => $tagfilter)
5767 if ($tagfilter || $search_regexp);
5768 # fill the rest
5769 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5770 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5771 push @all_fields, 'owner' unless($omit_owner);
5772 @projects = fill_project_list_info(\@projects, @all_fields);
5773
5774 $order ||= $default_projects_order;
5775 $from = 0 unless defined $from;
5776 $to = $#projects if (!defined $to || $#projects < $to);
5777
5778 # short circuit
5779 if ($from > $to) {
5780 print "<center>\n".
5781 "<b>No such projects found</b><br />\n".
5782 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5783 "</center>\n<br />\n";
5784 return;
5785 }
5786
5787 @projects = sort_projects_list(\@projects, $order);
5788
5789 if ($show_ctags) {
5790 my $ctags = git_gather_all_ctags(\@projects);
5791 my $cloud = git_populate_project_tagcloud($ctags);
5792 print git_show_project_tagcloud($cloud, 64);
5793 }
5794
5795 print "<table class=\"project_list\">\n";
5796 unless ($no_header) {
5797 print "<tr>\n";
5798 if ($check_forks) {
5799 print "<th></th>\n";
5800 }
5801 print_sort_th('project', $order, 'Project');
5802 print_sort_th('descr', $order, 'Description');
5803 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5804 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5805 print "<th></th>\n" . # for links
5806 "</tr>\n";
5807 }
5808
5809 if ($projects_list_group_categories) {
5810 # only display categories with projects in the $from-$to window
5811 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5812 my %categories = build_projlist_by_category(\@projects, $from, $to);
5813 foreach my $cat (sort keys %categories) {
5814 unless ($cat eq "") {
5815 print "<tr>\n";
5816 if ($check_forks) {
5817 print "<td></td>\n";
5818 }
5819 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5820 print "</tr>\n";
5821 }
5822
5823 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5824 }
5825 } else {
5826 git_project_list_rows(\@projects, $from, $to, $check_forks);
5827 }
5828
5829 if (defined $extra) {
5830 print "<tr>\n";
5831 if ($check_forks) {
5832 print "<td></td>\n";
5833 }
5834 print "<td colspan=\"5\">$extra</td>\n" .
5835 "</tr>\n";
5836 }
5837 print "</table>\n";
5838 }
5839
5840 sub git_log_body {
5841 # uses global variable $project
5842 my ($commitlist, $from, $to, $refs, $extra) = @_;
5843
5844 $from = 0 unless defined $from;
5845 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5846
5847 for (my $i = 0; $i <= $to; $i++) {
5848 my %co = %{$commitlist->[$i]};
5849 next if !%co;
5850 my $commit = $co{'id'};
5851 my $ref = format_ref_marker($refs, $commit);
5852 git_print_header_div('commit',
5853 "<span class=\"age\">$co{'age_string'}</span>" .
5854 esc_html($co{'title'}) . $ref,
5855 $commit);
5856 print "<div class=\"title_text\">\n" .
5857 "<div class=\"log_link\">\n" .
5858 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5859 " | " .
5860 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5861 " | " .
5862 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5863 "<br/>\n" .
5864 "</div>\n";
5865 git_print_authorship(\%co, -tag => 'span');
5866 print "<br/>\n</div>\n";
5867
5868 print "<div class=\"log_body\">\n";
5869 git_print_log($co{'comment'}, -final_empty_line=> 1);
5870 print "</div>\n";
5871 }
5872 if ($extra) {
5873 print "<div class=\"page_nav\">\n";
5874 print "$extra\n";
5875 print "</div>\n";
5876 }
5877 }
5878
5879 sub git_shortlog_body {
5880 # uses global variable $project
5881 my ($commitlist, $from, $to, $refs, $extra, $file_name, $file_hash, $ftype, $allrefs) = @_;
5882
5883 $from = 0 unless defined $from;
5884 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5885
5886 print "<table class=\"shortlog\" cellspacing=\"0\" cellpadding=\"0\">\n";
5887 my $alternate = 1;
5888 my $graph_rand = int(rand(99999));
5889
5890 my $head = git_get_head_hash($project);
5891 my $graph_hash;
5892
5893 if (defined $allrefs && $allrefs == 1) {
5894 $graph_hash = "all";
5895 }
5896 if (!defined $hash) {
5897 $hash = $head;
5898 }
5899 if(!defined $graph_hash) {
5900 $graph_hash = $hash;
5901 }
5902 if (!defined $page) {
5903 $page = 0;
5904 }
5905
5906 print "<tr class=\"header\">\n";
5907 print "<td colspan=\"2\"><img class=\"graph\" src=\"git_graph.php?r=".$graph_rand.";p=".$project.";h=".$graph_hash.";from=".($from + (100 * $page)).";to=".($to + (100 * $page)).";c=header\" /></td>\n";
5908 print "<td valign=\"bottom\"><b>Author</b></td>\n";
5909 print "<td valign=\"bottom\"><b>Commit</b></td>\n";
5910 print "<td></td>\n";
5911 print "</tr>\n";
5912
5913 for (my $i = $from; $i <= $to; $i++) {
5914 my %co = %{$commitlist->[$i]};
5915 my $commit = $co{'id'};
5916 my $ref = format_ref_marker($refs, $commit);
5917 if ($alternate) {
5918 print "<tr class=\"dark\">\n";
5919 } else {
5920 print "<tr class=\"light\">\n";
5921 }
5922 $alternate ^= 1;
5923 print "<td><img class=\"graph\" src=\"git_graph.php?r=".$graph_rand.";p=".$project.";h=".$graph_hash.";from=".($from + (100 * $page)).";to=".($to + (100 * $page)).";c=".$commit."\" /></td>";
5924 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5925 print "<td class=\"". age_class($co{'age'}) . "\" title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5926 format_author_html('td', \%co, 10) . "<td>";
5927 print format_subject_html($co{'title'}, $co{'title_short'},
5928 href(action=>"commit", hash=>$commit), $ref);
5929 print "</td>\n" .
5930 "<td class=\"link\">" .
5931 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5932 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5933 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5934 my $snapshot_links = format_snapshot_links($commit);
5935 if (defined $snapshot_links) {
5936 print " | " . $snapshot_links;
5937 }
5938 print "</td>\n" .
5939 "</tr>\n";
5940 }
5941 if (defined $extra) {
5942 print "<tr>\n" .
5943 "<td colspan=\"4\">$extra</td>\n" .
5944 "</tr>\n";
5945 }
5946 print "</table>\n";
5947 }
5948
5949 sub git_history_body {
5950 # Warning: assumes constant type (blob or tree) during history
5951 my ($commitlist, $from, $to, $refs, $extra,
5952 $file_name, $file_hash, $ftype) = @_;
5953
5954 $from = 0 unless defined $from;
5955 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5956
5957 print "<table class=\"history\">\n";
5958 my $alternate = 1;
5959 for (my $i = $from; $i <= $to; $i++) {
5960 my %co = %{$commitlist->[$i]};
5961 if (!%co) {
5962 next;
5963 }
5964 my $commit = $co{'id'};
5965
5966 my $ref = format_ref_marker($refs, $commit);
5967
5968 if ($alternate) {
5969 print "<tr class=\"dark\">\n";
5970 } else {
5971 print "<tr class=\"light\">\n";
5972 }
5973 $alternate ^= 1;
5974 print "<td class=\"". age_class($co{'age'}) . "\" title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5975 # shortlog: format_author_html('td', \%co, 10)
5976 format_author_html('td', \%co, 15, 3) . "<td>";
5977 # originally git_history used chop_str($co{'title'}, 50)
5978 print format_subject_html($co{'title'}, $co{'title_short'},
5979 href(action=>"commit", hash=>$commit), $ref);
5980 print "</td>\n" .
5981 "<td class=\"link\">" .
5982 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5983 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5984
5985 if ($ftype eq 'blob') {
5986 my $blob_current = $file_hash;
5987 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5988 if (defined $blob_current && defined $blob_parent &&
5989 $blob_current ne $blob_parent) {
5990 print " | " .
5991 $cgi->a({-href => href(action=>"blobdiff",
5992 hash=>$blob_current, hash_parent=>$blob_parent,
5993 hash_base=>$hash_base, hash_parent_base=>$commit,
5994 file_name=>$file_name)},
5995 "diff to current");
5996 }
5997 }
5998 print "</td>\n" .
5999 "</tr>\n";
6000 }
6001 if (defined $extra) {
6002 print "<tr>\n" .
6003 "<td colspan=\"4\">$extra</td>\n" .
6004 "</tr>\n";
6005 }
6006 print "</table>\n";
6007 }
6008
6009 sub git_tags_body {
6010 # uses global variable $project
6011 my ($taglist, $from, $to, $extra) = @_;
6012 $from = 0 unless defined $from;
6013 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6014
6015 print "<table class=\"tags\">\n";
6016 my $alternate = 1;
6017 for (my $i = $from; $i <= $to; $i++) {
6018 my $entry = $taglist->[$i];
6019 my %tag = %$entry;
6020 my $comment = $tag{'subject'};
6021 my $comment_short;
6022 if (defined $comment) {
6023 $comment_short = chop_str($comment, 30, 5);
6024 }
6025 if ($alternate) {
6026 print "<tr class=\"dark\">\n";
6027 } else {
6028 print "<tr class=\"light\">\n";
6029 }
6030 $alternate ^= 1;
6031 if (defined $tag{'age'}) {
6032 print "<td><i>$tag{'age'}</i></td>\n";
6033 } else {
6034 print "<td></td>\n";
6035 }
6036 print "<td>" .
6037 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6038 -class => "list name"}, esc_html($tag{'name'})) .
6039 "</td>\n" .
6040 "<td>";
6041 if (defined $comment) {
6042 print format_subject_html($comment, $comment_short,
6043 href(action=>"tag", hash=>$tag{'id'}));
6044 }
6045 print "</td>\n" .
6046 "<td class=\"selflink\">";
6047 if ($tag{'type'} eq "tag") {
6048 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6049 } else {
6050 print "&nbsp;";
6051 }
6052 print "</td>\n" .
6053 "<td class=\"link\">" . " | " .
6054 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6055 if ($tag{'reftype'} eq "commit") {
6056 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6057 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6058 } elsif ($tag{'reftype'} eq "blob") {
6059 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6060 }
6061 print "</td>\n" .
6062 "</tr>";
6063 }
6064 if (defined $extra) {
6065 print "<tr>\n" .
6066 "<td colspan=\"5\">$extra</td>\n" .
6067 "</tr>\n";
6068 }
6069 print "</table>\n";
6070 }
6071
6072 sub git_heads_body {
6073 # uses global variable $project
6074 my ($headlist, $head_at, $from, $to, $extra) = @_;
6075 $from = 0 unless defined $from;
6076 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6077
6078 print "<table class=\"heads\">\n";
6079 my $alternate = 1;
6080 for (my $i = $from; $i <= $to; $i++) {
6081 my $entry = $headlist->[$i];
6082 my %ref = %$entry;
6083 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6084 if ($alternate) {
6085 print "<tr class=\"dark\">\n";
6086 } else {
6087 print "<tr class=\"light\">\n";
6088 }
6089 $alternate ^= 1;
6090 print "<td><i>$ref{'age'}</i></td>\n" .
6091 ($curr ? "<td class=\"current_head\">" : "<td>") .
6092 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6093 -class => "list name"},esc_html($ref{'name'})) .
6094 "</td>\n" .
6095 "<td class=\"link\">" .
6096 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6097 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6098 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6099 "</td>\n" .
6100 "</tr>";
6101 }
6102 if (defined $extra) {
6103 print "<tr>\n" .
6104 "<td colspan=\"3\">$extra</td>\n" .
6105 "</tr>\n";
6106 }
6107 print "</table>\n";
6108 }
6109
6110 # Display a single remote block
6111 sub git_remote_block {
6112 my ($remote, $rdata, $limit, $head) = @_;
6113
6114 my $heads = $rdata->{'heads'};
6115 my $fetch = $rdata->{'fetch'};
6116 my $push = $rdata->{'push'};
6117
6118 my $urls_table = "<table class=\"projects_list\">\n" ;
6119
6120 if (defined $fetch) {
6121 if ($fetch eq $push) {
6122 $urls_table .= format_repo_url("URL", $fetch);
6123 } else {
6124 $urls_table .= format_repo_url("Fetch URL", $fetch);
6125 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6126 }
6127 } elsif (defined $push) {
6128 $urls_table .= format_repo_url("Push URL", $push);
6129 } else {
6130 $urls_table .= format_repo_url("", "No remote URL");
6131 }
6132
6133 $urls_table .= "</table>\n";
6134
6135 my $dots;
6136 if (defined $limit && $limit < @$heads) {
6137 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6138 }
6139
6140 print $urls_table;
6141 git_heads_body($heads, $head, 0, $limit, $dots);
6142 }
6143
6144 # Display a list of remote names with the respective fetch and push URLs
6145 sub git_remotes_list {
6146 my ($remotedata, $limit) = @_;
6147 print "<table class=\"heads\">\n";
6148 my $alternate = 1;
6149 my @remotes = sort keys %$remotedata;
6150
6151 my $limited = $limit && $limit < @remotes;
6152
6153 $#remotes = $limit - 1 if $limited;
6154
6155 while (my $remote = shift @remotes) {
6156 my $rdata = $remotedata->{$remote};
6157 my $fetch = $rdata->{'fetch'};
6158 my $push = $rdata->{'push'};
6159 if ($alternate) {
6160 print "<tr class=\"dark\">\n";
6161 } else {
6162 print "<tr class=\"light\">\n";
6163 }
6164 $alternate ^= 1;
6165 print "<td>" .
6166 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6167 -class=> "list name"},esc_html($remote)) .
6168 "</td>";
6169 print "<td class=\"link\">" .
6170 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6171 " | " .
6172 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6173 "</td>";
6174
6175 print "</tr>\n";
6176 }
6177
6178 if ($limited) {
6179 print "<tr>\n" .
6180 "<td colspan=\"3\">" .
6181 $cgi->a({-href => href(action=>"remotes")}, "...") .
6182 "</td>\n" . "</tr>\n";
6183 }
6184
6185 print "</table>";
6186 }
6187
6188 # Display remote heads grouped by remote, unless there are too many
6189 # remotes, in which case we only display the remote names
6190 sub git_remotes_body {
6191 my ($remotedata, $limit, $head) = @_;
6192 if ($limit and $limit < keys %$remotedata) {
6193 git_remotes_list($remotedata, $limit);
6194 } else {
6195 fill_remote_heads($remotedata);
6196 while (my ($remote, $rdata) = each %$remotedata) {
6197 git_print_section({-class=>"remote", -id=>$remote},
6198 ["remotes", $remote, $remote], sub {
6199 git_remote_block($remote, $rdata, $limit, $head);
6200 });
6201 }
6202 }
6203 }
6204
6205 sub git_search_message {
6206 my %co = @_;
6207
6208 my $greptype;
6209 if ($searchtype eq 'commit') {
6210 $greptype = "--grep=";
6211 } elsif ($searchtype eq 'author') {
6212 $greptype = "--author=";
6213 } elsif ($searchtype eq 'committer') {
6214 $greptype = "--committer=";
6215 }
6216 $greptype .= $searchtext;
6217 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6218 $greptype, '--regexp-ignore-case',
6219 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6220
6221 my $paging_nav = '';
6222 if ($page > 0) {
6223 $paging_nav .=
6224 $cgi->a({-href => href(-replay=>1, page=>undef)},
6225 "first") .
6226 " &sdot; " .
6227 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6228 -accesskey => "p", -title => "Alt-p"}, "prev");
6229 } else {
6230 $paging_nav .= "first &sdot; prev";
6231 }
6232 my $next_link = '';
6233 if ($#commitlist >= 100) {
6234 $next_link =
6235 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6236 -accesskey => "n", -title => "Alt-n"}, "next");
6237 $paging_nav .= " &sdot; $next_link";
6238 } else {
6239 $paging_nav .= " &sdot; next";
6240 }
6241
6242 git_header_html();
6243
6244 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6245 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6246 if ($page == 0 && !@commitlist) {
6247 print "<p>No match.</p>\n";
6248 } else {
6249 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6250 }
6251
6252 git_footer_html();
6253 }
6254
6255 sub git_search_changes {
6256 my %co = @_;
6257
6258 local $/ = "\n";
6259 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6260 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6261 ($search_use_regexp ? '--pickaxe-regex' : ())
6262 or die_error(500, "Open git-log failed");
6263
6264 git_header_html();
6265
6266 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6267 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6268
6269 print "<table class=\"pickaxe search\">\n";
6270 my $alternate = 1;
6271 undef %co;
6272 my @files;
6273 while (my $line = <$fd>) {
6274 chomp $line;
6275 next unless $line;
6276
6277 my %set = parse_difftree_raw_line($line);
6278 if (defined $set{'commit'}) {
6279 # finish previous commit
6280 if (%co) {
6281 print "</td>\n" .
6282 "<td class=\"link\">" .
6283 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6284 "commit") .
6285 " | " .
6286 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6287 hash_base=>$co{'id'})},
6288 "tree") .
6289 "</td>\n" .
6290 "</tr>\n";
6291 }
6292
6293 if ($alternate) {
6294 print "<tr class=\"dark\">\n";
6295 } else {
6296 print "<tr class=\"light\">\n";
6297 }
6298 $alternate ^= 1;
6299 %co = parse_commit($set{'commit'});
6300 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6301 print "<td class=\"". age_class($co{'age'}) . "\" title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6302 "<td><i>$author</i></td>\n" .
6303 "<td>" .
6304 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6305 -class => "list subject"},
6306 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6307 } elsif (defined $set{'to_id'}) {
6308 next if ($set{'to_id'} =~ m/^0{40}$/);
6309
6310 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6311 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6312 -class => "list"},
6313 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6314 "<br/>\n";
6315 }
6316 }
6317 close $fd;
6318
6319 # finish last commit (warning: repetition!)
6320 if (%co) {
6321 print "</td>\n" .
6322 "<td class=\"link\">" .
6323 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6324 "commit") .
6325 " | " .
6326 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6327 hash_base=>$co{'id'})},
6328 "tree") .
6329 "</td>\n" .
6330 "</tr>\n";
6331 }
6332
6333 print "</table>\n";
6334
6335 git_footer_html();
6336 }
6337
6338 sub git_search_files {
6339 my %co = @_;
6340
6341 local $/ = "\n";
6342 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6343 $search_use_regexp ? ('-E', '-i') : '-F',
6344 $searchtext, $co{'tree'}
6345 or die_error(500, "Open git-grep failed");
6346
6347 git_header_html();
6348
6349 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6350 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6351
6352 print "<table class=\"grep_search\">\n";
6353 my $alternate = 1;
6354 my $matches = 0;
6355 my $lastfile = '';
6356 my $file_href;
6357 while (my $line = <$fd>) {
6358 chomp $line;
6359 my ($file, $lno, $ltext, $binary);
6360 last if ($matches++ > 1000);
6361 if ($line =~ /^Binary file (.+) matches$/) {
6362 $file = $1;
6363 $binary = 1;
6364 } else {
6365 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6366 $file =~ s/^$co{'tree'}://;
6367 }
6368 if ($file ne $lastfile) {
6369 $lastfile and print "</td></tr>\n";
6370 if ($alternate++) {
6371 print "<tr class=\"dark\">\n";
6372 } else {
6373 print "<tr class=\"light\">\n";
6374 }
6375 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6376 file_name=>$file);
6377 print "<td class=\"list\">".
6378 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6379 print "</td><td>\n";
6380 $lastfile = $file;
6381 }
6382 if ($binary) {
6383 print "<div class=\"binary\">Binary file</div>\n";
6384 } else {
6385 $ltext = untabify($ltext);
6386 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6387 $ltext = esc_html($1, -nbsp=>1);
6388 $ltext .= '<span class="match">';
6389 $ltext .= esc_html($2, -nbsp=>1);
6390 $ltext .= '</span>';
6391 $ltext .= esc_html($3, -nbsp=>1);
6392 } else {
6393 $ltext = esc_html($ltext, -nbsp=>1);
6394 }
6395 print "<div class=\"pre\">" .
6396 $cgi->a({-href => $file_href.'#l'.$lno,
6397 -class => "linenr"}, sprintf('%4i', $lno)) .
6398 ' ' . $ltext . "</div>\n";
6399 }
6400 }
6401 if ($lastfile) {
6402 print "</td></tr>\n";
6403 if ($matches > 1000) {
6404 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6405 }
6406 } else {
6407 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6408 }
6409 close $fd;
6410
6411 print "</table>\n";
6412
6413 git_footer_html();
6414 }
6415
6416 sub git_search_grep_body {
6417 my ($commitlist, $from, $to, $extra) = @_;
6418 $from = 0 unless defined $from;
6419 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6420
6421 print "<table class=\"commit_search\">\n";
6422 my $alternate = 1;
6423 for (my $i = $from; $i <= $to; $i++) {
6424 my %co = %{$commitlist->[$i]};
6425 if (!%co) {
6426 next;
6427 }
6428 my $commit = $co{'id'};
6429 if ($alternate) {
6430 print "<tr class=\"dark\">\n";
6431 } else {
6432 print "<tr class=\"light\">\n";
6433 }
6434 $alternate ^= 1;
6435 print "<td class=\"". age_class($co{'age'}) . "\" title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6436 format_author_html('td', \%co, 15, 5) .
6437 "<td>" .
6438 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6439 -class => "list subject"},
6440 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6441 my $comment = $co{'comment'};
6442 foreach my $line (@$comment) {
6443 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6444 my ($lead, $match, $trail) = ($1, $2, $3);
6445 $match = chop_str($match, 70, 5, 'center');
6446 my $contextlen = int((80 - length($match))/2);
6447 $contextlen = 30 if ($contextlen > 30);
6448 $lead = chop_str($lead, $contextlen, 10, 'left');
6449 $trail = chop_str($trail, $contextlen, 10, 'right');
6450
6451 $lead = esc_html($lead);
6452 $match = esc_html($match);
6453 $trail = esc_html($trail);
6454
6455 print "$lead<span class=\"match\">$match</span>$trail<br />";
6456 }
6457 }
6458 print "</td>\n" .
6459 "<td class=\"link\">" .
6460 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6461 " | " .
6462 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6463 " | " .
6464 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6465 print "</td>\n" .
6466 "</tr>\n";
6467 }
6468 if (defined $extra) {
6469 print "<tr>\n" .
6470 "<td colspan=\"3\">$extra</td>\n" .
6471 "</tr>\n";
6472 }
6473 print "</table>\n";
6474 }
6475
6476 ## ======================================================================
6477 ## ======================================================================
6478 ## actions
6479
6480 sub git_project_list {
6481 my $order = $input_params{'order'};
6482 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6483 die_error(400, "Unknown order parameter");
6484 }
6485
6486 my @list = git_get_projects_list($project_filter, $strict_export);
6487 if (!@list) {
6488 die_error(404, "No projects found");
6489 }
6490
6491 git_header_html();
6492 if (defined $home_text && -f $home_text) {
6493 print "<div class=\"index_include\">\n";
6494 insert_file($home_text);
6495 print "</div>\n";
6496 }
6497
6498 git_project_search_form($searchtext, $search_use_regexp);
6499 git_project_list_body(\@list, $order);
6500 git_footer_html();
6501 }
6502
6503 sub git_forks {
6504 my $order = $input_params{'order'};
6505 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6506 die_error(400, "Unknown order parameter");
6507 }
6508
6509 my $filter = $project;
6510 $filter =~ s/\.git$//;
6511 my @list = git_get_projects_list($filter);
6512 if (!@list) {
6513 die_error(404, "No forks found");
6514 }
6515
6516 git_header_html();
6517 git_print_page_nav('','');
6518 git_print_header_div('summary', "$project forks");
6519 git_project_list_body(\@list, $order);
6520 git_footer_html();
6521 }
6522
6523 sub git_project_index {
6524 my @projects = git_get_projects_list($project_filter, $strict_export);
6525 if (!@projects) {
6526 die_error(404, "No projects found");
6527 }
6528
6529 print $cgi->header(
6530 -type => 'text/plain',
6531 -charset => 'utf-8',
6532 -content_disposition => 'inline; filename="index.aux"');
6533
6534 foreach my $pr (@projects) {
6535 if (!exists $pr->{'owner'}) {
6536 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6537 }
6538
6539 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6540 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6541 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6542 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6543 $path =~ s/ /\+/g;
6544 $owner =~ s/ /\+/g;
6545
6546 print "$path $owner\n";
6547 }
6548 }
6549
6550 sub git_summary {
6551 my $descr = git_get_project_description($project) || "none";
6552 my %co = parse_commit("HEAD");
6553 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6554 my $head = $co{'id'};
6555 my $remote_heads = gitweb_check_feature('remote_heads');
6556
6557 my $owner = git_get_project_owner($project);
6558
6559 my $refs = git_get_references();
6560 # These get_*_list functions return one more to allow us to see if
6561 # there are more ...
6562 my @taglist = git_get_tags_list(16);
6563 my @headlist = git_get_heads_list(16);
6564 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6565 my @forklist;
6566 my $check_forks = gitweb_check_feature('forks');
6567
6568 if ($check_forks) {
6569 # find forks of a project
6570 my $filter = $project;
6571 $filter =~ s/\.git$//;
6572 @forklist = git_get_projects_list($filter);
6573 # filter out forks of forks
6574 @forklist = filter_forks_from_projects_list(\@forklist)
6575 if (@forklist);
6576 }
6577
6578 git_header_html();
6579 git_print_page_nav('summary','', $head);
6580
6581 print "<div class=\"title\">&nbsp;</div>\n";
6582 print "<table class=\"projects_list\">\n" .
6583 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6584 if ($owner and not $omit_owner) {
6585 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6586 }
6587 if (defined $cd{'rfc2822'}) {
6588 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6589 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6590 }
6591
6592 # use per project git URL list in $projectroot/$project/cloneurl
6593 # or make project git URL from git base URL and project name
6594 my $url_tag = "URL";
6595 my @url_list = git_get_project_url_list($project);
6596 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6597 foreach my $git_url (@url_list) {
6598 next unless $git_url;
6599 print format_repo_url($url_tag, $git_url);
6600 $url_tag = "";
6601 }
6602
6603 # Tag cloud
6604 my $show_ctags = gitweb_check_feature('ctags');
6605 if ($show_ctags) {
6606 my $ctags = git_get_project_ctags($project);
6607 if (%$ctags) {
6608 # without ability to add tags, don't show if there are none
6609 my $cloud = git_populate_project_tagcloud($ctags);
6610 print "<tr id=\"metadata_ctags\">" .
6611 "<td>content tags</td>" .
6612 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6613 "</tr>\n";
6614 }
6615 }
6616
6617 print "</table>\n";
6618
6619 # If XSS prevention is on, we don't include README.html.
6620 # TODO: Allow a readme in some safe format.
6621 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6622 print "<div class=\"title\">readme</div>\n" .
6623 "<div class=\"readme\">\n";
6624 insert_file("$projectroot/$project/README.html");
6625 print "\n</div>\n"; # class="readme"
6626 }
6627
6628 # we need to request one more than 16 (0..15) to check if
6629 # those 16 are all
6630 my @commitlist = $head ? parse_commits("--all", 17) : ();
6631 if (@commitlist) {
6632 git_print_header_div('shortlog');
6633 git_shortlog_body(\@commitlist, 0, 15, $refs,
6634 $#commitlist <= 15 ? undef :
6635 $cgi->a({-href => href(action=>"shortlog")}, "..."), 0, 0, 0, 1);
6636 }
6637
6638 if (@taglist) {
6639 git_print_header_div('tags');
6640 git_tags_body(\@taglist, 0, 15,
6641 $#taglist <= 15 ? undef :
6642 $cgi->a({-href => href(action=>"tags")}, "..."));
6643 }
6644
6645 if (@headlist) {
6646 git_print_header_div('heads');
6647 git_heads_body(\@headlist, $head, 0, 15,
6648 $#headlist <= 15 ? undef :
6649 $cgi->a({-href => href(action=>"heads")}, "..."));
6650 }
6651
6652 if (%remotedata) {
6653 git_print_header_div('remotes');
6654 git_remotes_body(\%remotedata, 15, $head);
6655 }
6656
6657 if (@forklist) {
6658 git_print_header_div('forks');
6659 git_project_list_body(\@forklist, 'age', 0, 15,
6660 $#forklist <= 15 ? undef :
6661 $cgi->a({-href => href(action=>"forks")}, "..."),
6662 'no_header');
6663 }
6664
6665 git_footer_html();
6666 }
6667
6668 sub git_tag {
6669 my %tag = parse_tag($hash);
6670
6671 if (! %tag) {
6672 die_error(404, "Unknown tag object");
6673 }
6674
6675 my $head = git_get_head_hash($project);
6676 git_header_html();
6677 git_print_page_nav('','', $head,undef,$head);
6678 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6679 print "<div class=\"title_text\">\n" .
6680 "<table class=\"object_header\">\n" .
6681 "<tr>\n" .
6682 "<td>object</td>\n" .
6683 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6684 $tag{'object'}) . "</td>\n" .
6685 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6686 $tag{'type'}) . "</td>\n" .
6687 "</tr>\n";
6688 if (defined($tag{'author'})) {
6689 git_print_authorship_rows(\%tag, 'author');
6690 }
6691 print "</table>\n\n" .
6692 "</div>\n";
6693 print "<div class=\"page_body\">";
6694 my $comment = $tag{'comment'};
6695 foreach my $line (@$comment) {
6696 chomp $line;
6697 print esc_html($line, -nbsp=>1) . "<br/>\n";
6698 }
6699 print "</div>\n";
6700 git_footer_html();
6701 }
6702
6703 sub git_blame_common {
6704 my $format = shift || 'porcelain';
6705 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6706 $format = 'incremental';
6707 $action = 'blame_incremental'; # for page title etc
6708 }
6709
6710 # permissions
6711 gitweb_check_feature('blame')
6712 or die_error(403, "Blame view not allowed");
6713
6714 # error checking
6715 die_error(400, "No file name given") unless $file_name;
6716 $hash_base ||= git_get_head_hash($project);
6717 die_error(404, "Couldn't find base commit") unless $hash_base;
6718 my %co = parse_commit($hash_base)
6719 or die_error(404, "Commit not found");
6720 my $ftype = "blob";
6721 if (!defined $hash) {
6722 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6723 or die_error(404, "Error looking up file");
6724 } else {
6725 $ftype = git_get_type($hash);
6726 if ($ftype !~ "blob") {
6727 die_error(400, "Object is not a blob");
6728 }
6729 }
6730
6731 my $fd;
6732 if ($format eq 'incremental') {
6733 # get file contents (as base)
6734 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6735 or die_error(500, "Open git-cat-file failed");
6736 } elsif ($format eq 'data') {
6737 # run git-blame --incremental
6738 open $fd, "-|", git_cmd(), "blame", "--incremental",
6739 $hash_base, "--", $file_name
6740 or die_error(500, "Open git-blame --incremental failed");
6741 } else {
6742 # run git-blame --porcelain
6743 open $fd, "-|", git_cmd(), "blame", '-p',
6744 $hash_base, '--', $file_name
6745 or die_error(500, "Open git-blame --porcelain failed");
6746 }
6747 binmode $fd, ':utf8';
6748
6749 # incremental blame data returns early
6750 if ($format eq 'data') {
6751 print $cgi->header(
6752 -type=>"text/plain", -charset => "utf-8",
6753 -status=> "200 OK");
6754 local $| = 1; # output autoflush
6755 while (my $line = <$fd>) {
6756 print to_utf8($line);
6757 }
6758 close $fd
6759 or print "ERROR $!\n";
6760
6761 print 'END';
6762 if (defined $t0 && gitweb_check_feature('timed')) {
6763 print ' '.
6764 tv_interval($t0, [ gettimeofday() ]).
6765 ' '.$number_of_git_cmds;
6766 }
6767 print "\n";
6768
6769 return;
6770 }
6771
6772 # page header
6773 git_header_html();
6774 my $formats_nav =
6775 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6776 "blob") .
6777 " | ";
6778 if ($format eq 'incremental') {
6779 $formats_nav .=
6780 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6781 "blame") . " (non-incremental)";
6782 } else {
6783 $formats_nav .=
6784 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6785 "blame") . " (incremental)";
6786 }
6787 $formats_nav .=
6788 " | " .
6789 $cgi->a({-href => href(action=>"history", -replay=>1)},
6790 "history") .
6791 " | " .
6792 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6793 "HEAD");
6794 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6795 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6796 git_print_page_path($file_name, $ftype, $hash_base);
6797
6798 # page body
6799 if ($format eq 'incremental') {
6800 print "<noscript>\n<div class=\"error\"><center><b>\n".
6801 "This page requires JavaScript to run.\n Use ".
6802 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6803 'this page').
6804 " instead.\n".
6805 "</b></center></div>\n</noscript>\n";
6806
6807 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6808 }
6809
6810 print qq!<div class="page_body">\n!;
6811 print qq!<div id="progress_info">... / ...</div>\n!
6812 if ($format eq 'incremental');
6813 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6814 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6815 qq!<thead>\n!.
6816 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6817 qq!</thead>\n!.
6818 qq!<tbody>\n!;
6819
6820 my @rev_color = qw(light dark);
6821 my $num_colors = scalar(@rev_color);
6822 my $current_color = 0;
6823
6824 if ($format eq 'incremental') {
6825 my $color_class = $rev_color[$current_color];
6826
6827 #contents of a file
6828 my $linenr = 0;
6829 LINE:
6830 while (my $line = <$fd>) {
6831 chomp $line;
6832 $linenr++;
6833
6834 print qq!<tr id="l$linenr" class="$color_class">!.
6835 qq!<td class="sha1"><a href=""> </a></td>!.
6836 qq!<td class="linenr">!.
6837 qq!<a class="linenr" href="">$linenr</a></td>!;
6838 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6839 print qq!</tr>\n!;
6840 }
6841
6842 } else { # porcelain, i.e. ordinary blame
6843 my %metainfo = (); # saves information about commits
6844
6845 # blame data
6846 LINE:
6847 while (my $line = <$fd>) {
6848 chomp $line;
6849 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6850 # no <lines in group> for subsequent lines in group of lines
6851 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6852 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6853 if (!exists $metainfo{$full_rev}) {
6854 $metainfo{$full_rev} = { 'nprevious' => 0 };
6855 }
6856 my $meta = $metainfo{$full_rev};
6857 my $data;
6858 while ($data = <$fd>) {
6859 chomp $data;
6860 last if ($data =~ s/^\t//); # contents of line
6861 if ($data =~ /^(\S+)(?: (.*))?$/) {
6862 $meta->{$1} = $2 unless exists $meta->{$1};
6863 }
6864 if ($data =~ /^previous /) {
6865 $meta->{'nprevious'}++;
6866 }
6867 }
6868 my $short_rev = substr($full_rev, 0, 8);
6869 my $author = $meta->{'author'};
6870 my %date =
6871 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6872 my $date = $date{'iso-tz'};
6873 if ($group_size) {
6874 $current_color = ($current_color + 1) % $num_colors;
6875 }
6876 my $tr_class = $rev_color[$current_color];
6877 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6878 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6879 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6880 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6881 if ($group_size) {
6882 print "<td class=\"sha1\"";
6883 print " title=\"". esc_html($author) . ", $date\"";
6884 print " rowspan=\"$group_size\"" if ($group_size > 1);
6885 print ">";
6886 print $cgi->a({-href => href(action=>"commit",
6887 hash=>$full_rev,
6888 file_name=>$file_name)},
6889 esc_html($short_rev));
6890 if ($group_size >= 2) {
6891 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6892 if (@author_initials) {
6893 print "<br />" .
6894 esc_html(join('', @author_initials));
6895 # or join('.', ...)
6896 }
6897 }
6898 print "</td>\n";
6899 }
6900 # 'previous' <sha1 of parent commit> <filename at commit>
6901 if (exists $meta->{'previous'} &&
6902 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6903 $meta->{'parent'} = $1;
6904 $meta->{'file_parent'} = unquote($2);
6905 }
6906 my $linenr_commit =
6907 exists($meta->{'parent'}) ?
6908 $meta->{'parent'} : $full_rev;
6909 my $linenr_filename =
6910 exists($meta->{'file_parent'}) ?
6911 $meta->{'file_parent'} : unquote($meta->{'filename'});
6912 my $blamed = href(action => 'blame',
6913 file_name => $linenr_filename,
6914 hash_base => $linenr_commit);
6915 print "<td class=\"linenr\">";
6916 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6917 -class => "linenr" },
6918 esc_html($lineno));
6919 print "</td>";
6920 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6921 print "</tr>\n";
6922 } # end while
6923
6924 }
6925
6926 # footer
6927 print "</tbody>\n".
6928 "</table>\n"; # class="blame"
6929 print "</div>\n"; # class="blame_body"
6930 close $fd
6931 or print "Reading blob failed\n";
6932
6933 git_footer_html();
6934 }
6935
6936 sub git_blame {
6937 git_blame_common();
6938 }
6939
6940 sub git_blame_incremental {
6941 git_blame_common('incremental');
6942 }
6943
6944 sub git_blame_data {
6945 git_blame_common('data');
6946 }
6947
6948 sub git_tags {
6949 my $head = git_get_head_hash($project);
6950 git_header_html();
6951 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6952 git_print_header_div('summary', $project);
6953
6954 my @tagslist = git_get_tags_list();
6955 if (@tagslist) {
6956 git_tags_body(\@tagslist);
6957 }
6958 git_footer_html();
6959 }
6960
6961 sub git_heads {
6962 my $head = git_get_head_hash($project);
6963 git_header_html();
6964 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6965 git_print_header_div('summary', $project);
6966
6967 my @headslist = git_get_heads_list();
6968 if (@headslist) {
6969 git_heads_body(\@headslist, $head);
6970 }
6971 git_footer_html();
6972 }
6973
6974 # used both for single remote view and for list of all the remotes
6975 sub git_remotes {
6976 gitweb_check_feature('remote_heads')
6977 or die_error(403, "Remote heads view is disabled");
6978
6979 my $head = git_get_head_hash($project);
6980 my $remote = $input_params{'hash'};
6981
6982 my $remotedata = git_get_remotes_list($remote);
6983 die_error(500, "Unable to get remote information") unless defined $remotedata;
6984
6985 unless (%$remotedata) {
6986 die_error(404, defined $remote ?
6987 "Remote $remote not found" :
6988 "No remotes found");
6989 }
6990
6991 git_header_html(undef, undef, -action_extra => $remote);
6992 git_print_page_nav('', '', $head, undef, $head,
6993 format_ref_views($remote ? '' : 'remotes'));
6994
6995 fill_remote_heads($remotedata);
6996 if (defined $remote) {
6997 git_print_header_div('remotes', "$remote remote for $project");
6998 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6999 } else {
7000 git_print_header_div('summary', "$project remotes");
7001 git_remotes_body($remotedata, undef, $head);
7002 }
7003
7004 git_footer_html();
7005 }
7006
7007 sub git_blob_plain {
7008 my $type = shift;
7009 my $expires;
7010
7011 if (!defined $hash) {
7012 if (defined $file_name) {
7013 my $base = $hash_base || git_get_head_hash($project);
7014 $hash = git_get_hash_by_path($base, $file_name, "blob")
7015 or die_error(404, "Cannot find file");
7016 } else {
7017 die_error(400, "No file name defined");
7018 }
7019 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7020 # blobs defined by non-textual hash id's can be cached
7021 $expires = "+1d";
7022 }
7023
7024 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7025 or die_error(500, "Open git-cat-file blob '$hash' failed");
7026
7027 # content-type (can include charset)
7028 $type = blob_contenttype($fd, $file_name, $type);
7029
7030 # "save as" filename, even when no $file_name is given
7031 my $save_as = "$hash";
7032 if (defined $file_name) {
7033 $save_as = $file_name;
7034 } elsif ($type =~ m/^text\//) {
7035 $save_as .= '.txt';
7036 }
7037
7038 # With XSS prevention on, blobs of all types except a few known safe
7039 # ones are served with "Content-Disposition: attachment" to make sure
7040 # they don't run in our security domain. For certain image types,
7041 # blob view writes an <img> tag referring to blob_plain view, and we
7042 # want to be sure not to break that by serving the image as an
7043 # attachment (though Firefox 3 doesn't seem to care).
7044 my $sandbox = $prevent_xss &&
7045 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7046
7047 # serve text/* as text/plain
7048 if ($prevent_xss &&
7049 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7050 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7051 my $rest = $1;
7052 $rest = defined $rest ? $rest : '';
7053 $type = "text/plain$rest";
7054 }
7055
7056 print $cgi->header(
7057 -type => $type,
7058 -expires => $expires,
7059 -content_disposition =>
7060 ($sandbox ? 'attachment' : 'inline')
7061 . '; filename="' . $save_as . '"');
7062 local $/ = undef;
7063 binmode STDOUT, ':raw';
7064 print <$fd>;
7065 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7066 close $fd;
7067 }
7068
7069 sub git_blob {
7070 my $expires;
7071
7072 if (!defined $hash) {
7073 if (defined $file_name) {
7074 my $base = $hash_base || git_get_head_hash($project);
7075 $hash = git_get_hash_by_path($base, $file_name, "blob")
7076 or die_error(404, "Cannot find file");
7077 } else {
7078 die_error(400, "No file name defined");
7079 }
7080 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7081 # blobs defined by non-textual hash id's can be cached
7082 $expires = "+1d";
7083 }
7084
7085 my $have_blame = gitweb_check_feature('blame');
7086 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7087 or die_error(500, "Couldn't cat $file_name, $hash");
7088 my $mimetype = blob_mimetype($fd, $file_name);
7089 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7090 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7091 close $fd;
7092 return git_blob_plain($mimetype);
7093 }
7094 # we can have blame only for text/* mimetype
7095 $have_blame &&= ($mimetype =~ m!^text/!);
7096
7097 my $highlight = gitweb_check_feature('highlight');
7098 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7099 $fd = run_highlighter($fd, $highlight, $syntax)
7100 if $syntax;
7101
7102 git_header_html(undef, $expires);
7103 my $formats_nav = '';
7104 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7105 if (defined $file_name) {
7106 if ($have_blame) {
7107 $formats_nav .=
7108 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7109 "blame") .
7110 " | ";
7111 }
7112 $formats_nav .=
7113 $cgi->a({-href => href(action=>"history", -replay=>1)},
7114 "history") .
7115 " | " .
7116 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7117 "raw") .
7118 " | " .
7119 $cgi->a({-href => href(action=>"blob",
7120 hash_base=>"HEAD", file_name=>$file_name)},
7121 "HEAD");
7122 } else {
7123 $formats_nav .=
7124 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7125 "raw");
7126 }
7127 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7128 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7129 } else {
7130 print "<div class=\"page_nav\">\n" .
7131 "<br/><br/></div>\n" .
7132 "<div class=\"title\">".esc_html($hash)."</div>\n";
7133 }
7134 git_print_page_path($file_name, "blob", $hash_base);
7135 print "<div class=\"page_body\">\n";
7136 if ($mimetype =~ m!^image/!) {
7137 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7138 if ($file_name) {
7139 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7140 }
7141 print qq! src="! .
7142 href(action=>"blob_plain", hash=>$hash,
7143 hash_base=>$hash_base, file_name=>$file_name) .
7144 qq!" />\n!;
7145 } else {
7146 my $nr;
7147 while (my $line = <$fd>) {
7148 chomp $line;
7149 $nr++;
7150 $line = untabify($line);
7151 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7152 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7153 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7154 }
7155 }
7156 close $fd
7157 or print "Reading blob failed.\n";
7158 print "</div>";
7159 git_footer_html();
7160 }
7161
7162 sub git_tree {
7163 if (!defined $hash_base) {
7164 $hash_base = "HEAD";
7165 }
7166 if (!defined $hash) {
7167 if (defined $file_name) {
7168 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7169 } else {
7170 $hash = $hash_base;
7171 }
7172 }
7173 die_error(404, "No such tree") unless defined($hash);
7174
7175 my $show_sizes = gitweb_check_feature('show-sizes');
7176 my $have_blame = gitweb_check_feature('blame');
7177
7178 my @entries = ();
7179 {
7180 local $/ = "\0";
7181 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7182 ($show_sizes ? '-l' : ()), @extra_options, $hash
7183 or die_error(500, "Open git-ls-tree failed");
7184 @entries = map { chomp; $_ } <$fd>;
7185 close $fd
7186 or die_error(404, "Reading tree failed");
7187 }
7188
7189 my $refs = git_get_references();
7190 my $ref = format_ref_marker($refs, $hash_base);
7191 git_header_html();
7192 my $basedir = '';
7193 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7194 my @views_nav = ();
7195 if (defined $file_name) {
7196 push @views_nav,
7197 $cgi->a({-href => href(action=>"history", -replay=>1)},
7198 "history"),
7199 $cgi->a({-href => href(action=>"tree",
7200 hash_base=>"HEAD", file_name=>$file_name)},
7201 "HEAD"),
7202 }
7203 my $snapshot_links = format_snapshot_links($hash);
7204 if (defined $snapshot_links) {
7205 # FIXME: Should be available when we have no hash base as well.
7206 push @views_nav, $snapshot_links;
7207 }
7208 git_print_page_nav('tree','', $hash_base, undef, undef,
7209 join(' | ', @views_nav));
7210 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7211 } else {
7212 undef $hash_base;
7213 print "<div class=\"page_nav\">\n";
7214 print "<br/><br/></div>\n";
7215 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7216 }
7217 if (defined $file_name) {
7218 $basedir = $file_name;
7219 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7220 $basedir .= '/';
7221 }
7222 git_print_page_path($file_name, 'tree', $hash_base);
7223 }
7224 print "<div class=\"page_body\">\n";
7225 print "<table class=\"tree\">\n";
7226 my $alternate = 1;
7227 # '..' (top directory) link if possible
7228 if (defined $hash_base &&
7229 defined $file_name && $file_name =~ m![^/]+$!) {
7230 if ($alternate) {
7231 print "<tr class=\"dark\">\n";
7232 } else {
7233 print "<tr class=\"light\">\n";
7234 }
7235 $alternate ^= 1;
7236
7237 my $up = $file_name;
7238 $up =~ s!/?[^/]+$!!;
7239 undef $up unless $up;
7240 # based on git_print_tree_entry
7241 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7242 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7243 print '<td class="list">';
7244 print $cgi->a({-href => href(action=>"tree",
7245 hash_base=>$hash_base,
7246 file_name=>$up)},
7247 "..");
7248 print "</td>\n";
7249 print "<td class=\"link\"></td>\n";
7250
7251 print "</tr>\n";
7252 }
7253 foreach my $line (@entries) {
7254 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7255
7256 if ($alternate) {
7257 print "<tr class=\"dark\">\n";
7258 } else {
7259 print "<tr class=\"light\">\n";
7260 }
7261 $alternate ^= 1;
7262
7263 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7264
7265 print "</tr>\n";
7266 }
7267 print "</table>\n" .
7268 "</div>";
7269 git_footer_html();
7270 }
7271
7272 sub sanitize_for_filename {
7273 my $name = shift;
7274
7275 $name =~ s!/!-!g;
7276 $name =~ s/[^[:alnum:]_.-]//g;
7277
7278 return $name;
7279 }
7280
7281 sub snapshot_name {
7282 my ($project, $hash) = @_;
7283
7284 # path/to/project.git -> project
7285 # path/to/project/.git -> project
7286 my $name = to_utf8($project);
7287 $name =~ s,([^/])/*\.git$,$1,;
7288 $name = sanitize_for_filename(basename($name));
7289
7290 my $ver = $hash;
7291 if ($hash =~ /^[0-9a-fA-F]+$/) {
7292 # shorten SHA-1 hash
7293 my $full_hash = git_get_full_hash($project, $hash);
7294 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7295 $ver = git_get_short_hash($project, $hash);
7296 }
7297 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7298 # tags don't need shortened SHA-1 hash
7299 $ver = $1;
7300 } else {
7301 # branches and other need shortened SHA-1 hash
7302 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7303 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7304 my $ref_dir = (defined $1) ? $1 : '';
7305 $ver = $2;
7306
7307 $ref_dir = sanitize_for_filename($ref_dir);
7308 # for refs neither in heads nor remotes we want to
7309 # add a ref dir to archive name
7310 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7311 $ver = $ref_dir . '-' . $ver;
7312 }
7313 }
7314 $ver .= '-' . git_get_short_hash($project, $hash);
7315 }
7316 # special case of sanitization for filename - we change
7317 # slashes to dots instead of dashes
7318 # in case of hierarchical branch names
7319 $ver =~ s!/!.!g;
7320 $ver =~ s/[^[:alnum:]_.-]//g;
7321
7322 # name = project-version_string
7323 $name = "$name-$ver";
7324
7325 return wantarray ? ($name, $name) : $name;
7326 }
7327
7328 sub exit_if_unmodified_since {
7329 my ($latest_epoch) = @_;
7330 our $cgi;
7331
7332 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7333 if (defined $if_modified) {
7334 my $since;
7335 if (eval { require HTTP::Date; 1; }) {
7336 $since = HTTP::Date::str2time($if_modified);
7337 } elsif (eval { require Time::ParseDate; 1; }) {
7338 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7339 }
7340 if (defined $since && $latest_epoch <= $since) {
7341 my %latest_date = parse_date($latest_epoch);
7342 print $cgi->header(
7343 -last_modified => $latest_date{'rfc2822'},
7344 -status => '304 Not Modified');
7345 goto DONE_GITWEB;
7346 }
7347 }
7348 }
7349
7350 sub git_snapshot {
7351 my $format = $input_params{'snapshot_format'};
7352 if (!@snapshot_fmts) {
7353 die_error(403, "Snapshots not allowed");
7354 }
7355 # default to first supported snapshot format
7356 $format ||= $snapshot_fmts[0];
7357 if ($format !~ m/^[a-z0-9]+$/) {
7358 die_error(400, "Invalid snapshot format parameter");
7359 } elsif (!exists($known_snapshot_formats{$format})) {
7360 die_error(400, "Unknown snapshot format");
7361 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7362 die_error(403, "Snapshot format not allowed");
7363 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7364 die_error(403, "Unsupported snapshot format");
7365 }
7366
7367 my $type = git_get_type("$hash^{}");
7368 if (!$type) {
7369 die_error(404, 'Object does not exist');
7370 } elsif ($type eq 'blob') {
7371 die_error(400, 'Object is not a tree-ish');
7372 }
7373
7374 my ($name, $prefix) = snapshot_name($project, $hash);
7375 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7376
7377 my %co = parse_commit($hash);
7378 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7379
7380 my $cmd = quote_command(
7381 git_cmd(), 'archive',
7382 "--format=$known_snapshot_formats{$format}{'format'}",
7383 "--prefix=$prefix/", $hash);
7384 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7385 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7386 }
7387
7388 $filename =~ s/(["\\])/\\$1/g;
7389 my %latest_date;
7390 if (%co) {
7391 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7392 }
7393
7394 print $cgi->header(
7395 -type => $known_snapshot_formats{$format}{'type'},
7396 -content_disposition => 'inline; filename="' . $filename . '"',
7397 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7398 -status => '200 OK');
7399
7400 open my $fd, "-|", $cmd
7401 or die_error(500, "Execute git-archive failed");
7402 binmode STDOUT, ':raw';
7403 print <$fd>;
7404 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7405 close $fd;
7406 }
7407
7408 sub git_log_generic {
7409 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash, $allrefs) = @_;
7410
7411 my $head = git_get_head_hash($project);
7412 my $allrefs;
7413 if (!defined $base) {
7414 $base = $head;
7415 $allrefs = 1;
7416 }
7417 if (!defined $page) {
7418 $page = 0;
7419 }
7420 my $refs = git_get_references();
7421
7422 my $commit_hash = $base;
7423 if (defined $allrefs) {
7424 $commit_hash = "--all";
7425 }
7426 if (defined $parent) {
7427 $commit_hash = "$parent..$base";
7428 }
7429 my @commitlist =
7430 parse_commits($commit_hash, 101, (100 * $page),
7431 defined $file_name ? ($file_name, "--full-history") : ());
7432
7433 my $ftype;
7434 if (!defined $file_hash && defined $file_name) {
7435 # some commits could have deleted file in question,
7436 # and not have it in tree, but one of them has to have it
7437 for (my $i = 0; $i < @commitlist; $i++) {
7438 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7439 last if defined $file_hash;
7440 }
7441 }
7442 if (defined $file_hash) {
7443 $ftype = git_get_type($file_hash);
7444 }
7445 if (defined $file_name && !defined $ftype) {
7446 die_error(500, "Unknown type of object");
7447 }
7448 my %co;
7449 if (defined $file_name) {
7450 %co = parse_commit($base)
7451 or die_error(404, "Unknown commit object");
7452 }
7453
7454
7455 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7456 my $next_link = '';
7457 if ($#commitlist >= 100) {
7458 $next_link =
7459 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7460 -accesskey => "n", -title => "Alt-n"}, "next");
7461 }
7462 my $patch_max = gitweb_get_feature('patches');
7463 if ($patch_max && !defined $file_name) {
7464 if ($patch_max < 0 || @commitlist <= $patch_max) {
7465 $paging_nav .= " &sdot; " .
7466 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7467 "patches");
7468 }
7469 }
7470
7471 git_header_html();
7472 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7473 if (defined $file_name) {
7474 git_print_header_div('commit', esc_html($co{'title'}), $base);
7475 } else {
7476 git_print_header_div('summary', $project)
7477 }
7478 git_print_page_path($file_name, $ftype, $hash_base)
7479 if (defined $file_name);
7480
7481 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7482 $file_name, $file_hash, $ftype, $allrefs);
7483
7484 git_footer_html();
7485 }
7486
7487 sub git_log {
7488 git_log_generic('log', \&git_log_body,
7489 $hash, $hash_parent);
7490 }
7491
7492 sub git_commit {
7493 $hash ||= $hash_base || "HEAD";
7494 my %co = parse_commit($hash)
7495 or die_error(404, "Unknown commit object");
7496
7497 my $parent = $co{'parent'};
7498 my $parents = $co{'parents'}; # listref
7499
7500 # we need to prepare $formats_nav before any parameter munging
7501 my $formats_nav;
7502 if (!defined $parent) {
7503 # --root commitdiff
7504 $formats_nav .= '(initial)';
7505 } elsif (@$parents == 1) {
7506 # single parent commit
7507 $formats_nav .=
7508 '(parent: ' .
7509 $cgi->a({-href => href(action=>"commit",
7510 hash=>$parent)},
7511 esc_html(substr($parent, 0, 7))) .
7512 ')';
7513 } else {
7514 # merge commit
7515 $formats_nav .=
7516 '(merge: ' .
7517 join(' ', map {
7518 $cgi->a({-href => href(action=>"commit",
7519 hash=>$_)},
7520 esc_html(substr($_, 0, 7)));
7521 } @$parents ) .
7522 ')';
7523 }
7524 if (gitweb_check_feature('patches') && @$parents <= 1) {
7525 $formats_nav .= " | " .
7526 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7527 "patch");
7528 }
7529
7530 if (!defined $parent) {
7531 $parent = "--root";
7532 }
7533 my @difftree;
7534 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7535 @diff_opts,
7536 (@$parents <= 1 ? $parent : '-c'),
7537 $hash, "--"
7538 or die_error(500, "Open git-diff-tree failed");
7539 @difftree = map { chomp; $_ } <$fd>;
7540 close $fd or die_error(404, "Reading git-diff-tree failed");
7541
7542 # non-textual hash id's can be cached
7543 my $expires;
7544 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7545 $expires = "+1d";
7546 }
7547 my $refs = git_get_references();
7548 my $ref = format_ref_marker($refs, $co{'id'});
7549
7550 git_header_html(undef, $expires);
7551 git_print_page_nav('commit', '',
7552 $hash, $co{'tree'}, $hash,
7553 $formats_nav);
7554
7555 if (defined $co{'parent'}) {
7556 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7557 } else {
7558 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7559 }
7560 print "<div class=\"title_text\">\n" .
7561 "<table class=\"object_header\">\n";
7562 git_print_authorship_rows(\%co);
7563 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7564 print "<tr>" .
7565 "<td>tree</td>" .
7566 "<td class=\"sha1\">" .
7567 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7568 class => "list"}, $co{'tree'}) .
7569 "</td>" .
7570 "<td class=\"link\">" .
7571 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7572 "tree");
7573 my $snapshot_links = format_snapshot_links($hash);
7574 if (defined $snapshot_links) {
7575 print " | " . $snapshot_links;
7576 }
7577 print "</td>" .
7578 "</tr>\n";
7579
7580 foreach my $par (@$parents) {
7581 print "<tr>" .
7582 "<td>parent</td>" .
7583 "<td class=\"sha1\">" .
7584 $cgi->a({-href => href(action=>"commit", hash=>$par),
7585 class => "list"}, $par) .
7586 "</td>" .
7587 "<td class=\"link\">" .
7588 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7589 " | " .
7590 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7591 "</td>" .
7592 "</tr>\n";
7593 }
7594 print "</table>".
7595 "</div>\n";
7596
7597 print "<div class=\"page_body\">\n";
7598 git_print_log($co{'comment'});
7599 print "</div>\n";
7600
7601 git_difftree_body(\@difftree, $hash, @$parents);
7602
7603 git_footer_html();
7604 }
7605
7606 sub git_object {
7607 # object is defined by:
7608 # - hash or hash_base alone
7609 # - hash_base and file_name
7610 my $type;
7611
7612 # - hash or hash_base alone
7613 if ($hash || ($hash_base && !defined $file_name)) {
7614 my $object_id = $hash || $hash_base;
7615
7616 open my $fd, "-|", quote_command(
7617 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7618 or die_error(404, "Object does not exist");
7619 $type = <$fd>;
7620 chomp $type;
7621 close $fd
7622 or die_error(404, "Object does not exist");
7623
7624 # - hash_base and file_name
7625 } elsif ($hash_base && defined $file_name) {
7626 $file_name =~ s,/+$,,;
7627
7628 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7629 or die_error(404, "Base object does not exist");
7630
7631 # here errors should not happen
7632 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7633 or die_error(500, "Open git-ls-tree failed");
7634 my $line = <$fd>;
7635 close $fd;
7636
7637 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7638 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7639 die_error(404, "File or directory for given base does not exist");
7640 }
7641 $type = $2;
7642 $hash = $3;
7643 } else {
7644 die_error(400, "Not enough information to find object");
7645 }
7646
7647 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7648 hash=>$hash, hash_base=>$hash_base,
7649 file_name=>$file_name),
7650 -status => '302 Found');
7651 }
7652
7653 sub git_blobdiff {
7654 my $format = shift || 'html';
7655 my $diff_style = $input_params{'diff_style'} || 'inline';
7656
7657 my $fd;
7658 my @difftree;
7659 my %diffinfo;
7660 my $expires;
7661
7662 # preparing $fd and %diffinfo for git_patchset_body
7663 # new style URI
7664 if (defined $hash_base && defined $hash_parent_base) {
7665 if (defined $file_name) {
7666 # read raw output
7667 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7668 $hash_parent_base, $hash_base,
7669 "--", (defined $file_parent ? $file_parent : ()), $file_name
7670 or die_error(500, "Open git-diff-tree failed");
7671 @difftree = map { chomp; $_ } <$fd>;
7672 close $fd
7673 or die_error(404, "Reading git-diff-tree failed");
7674 @difftree
7675 or die_error(404, "Blob diff not found");
7676
7677 } elsif (defined $hash &&
7678 $hash =~ /[0-9a-fA-F]{40}/) {
7679 # try to find filename from $hash
7680
7681 # read filtered raw output
7682 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7683 $hash_parent_base, $hash_base, "--"
7684 or die_error(500, "Open git-diff-tree failed");
7685 @difftree =
7686 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7687 # $hash == to_id
7688 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7689 map { chomp; $_ } <$fd>;
7690 close $fd
7691 or die_error(404, "Reading git-diff-tree failed");
7692 @difftree
7693 or die_error(404, "Blob diff not found");
7694
7695 } else {
7696 die_error(400, "Missing one of the blob diff parameters");
7697 }
7698
7699 if (@difftree > 1) {
7700 die_error(400, "Ambiguous blob diff specification");
7701 }
7702
7703 %diffinfo = parse_difftree_raw_line($difftree[0]);
7704 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7705 $file_name ||= $diffinfo{'to_file'};
7706
7707 $hash_parent ||= $diffinfo{'from_id'};
7708 $hash ||= $diffinfo{'to_id'};
7709
7710 # non-textual hash id's can be cached
7711 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7712 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7713 $expires = '+1d';
7714 }
7715
7716 # open patch output
7717 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7718 '-p', ($format eq 'html' ? "--full-index" : ()),
7719 $hash_parent_base, $hash_base,
7720 "--", (defined $file_parent ? $file_parent : ()), $file_name
7721 or die_error(500, "Open git-diff-tree failed");
7722 }
7723
7724 # old/legacy style URI -- not generated anymore since 1.4.3.
7725 if (!%diffinfo) {
7726 die_error('404 Not Found', "Missing one of the blob diff parameters")
7727 }
7728
7729 # header
7730 if ($format eq 'html') {
7731 my $formats_nav =
7732 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7733 "raw");
7734 $formats_nav .= diff_style_nav($diff_style);
7735 git_header_html(undef, $expires);
7736 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7737 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7738 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7739 } else {
7740 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7741 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7742 }
7743 if (defined $file_name) {
7744 git_print_page_path($file_name, "blob", $hash_base);
7745 } else {
7746 print "<div class=\"page_path\"></div>\n";
7747 }
7748
7749 } elsif ($format eq 'plain') {
7750 print $cgi->header(
7751 -type => 'text/plain',
7752 -charset => 'utf-8',
7753 -expires => $expires,
7754 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7755
7756 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7757
7758 } else {
7759 die_error(400, "Unknown blobdiff format");
7760 }
7761
7762 # patch
7763 if ($format eq 'html') {
7764 print "<div class=\"page_body\">\n";
7765
7766 git_patchset_body($fd, $diff_style,
7767 [ \%diffinfo ], $hash_base, $hash_parent_base);
7768 close $fd;
7769
7770 print "</div>\n"; # class="page_body"
7771 git_footer_html();
7772
7773 } else {
7774 while (my $line = <$fd>) {
7775 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7776 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7777
7778 print $line;
7779
7780 last if $line =~ m!^\+\+\+!;
7781 }
7782 local $/ = undef;
7783 print <$fd>;
7784 close $fd;
7785 }
7786 }
7787
7788 sub git_blobdiff_plain {
7789 git_blobdiff('plain');
7790 }
7791
7792 # assumes that it is added as later part of already existing navigation,
7793 # so it returns "| foo | bar" rather than just "foo | bar"
7794 sub diff_style_nav {
7795 my ($diff_style, $is_combined) = @_;
7796 $diff_style ||= 'inline';
7797
7798 return "" if ($is_combined);
7799
7800 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7801 my %styles = @styles;
7802 @styles =
7803 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7804
7805 return join '',
7806 map { " | ".$_ }
7807 map {
7808 $_ eq $diff_style ? $styles{$_} :
7809 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7810 } @styles;
7811 }
7812
7813 sub git_commitdiff {
7814 my %params = @_;
7815 my $format = $params{-format} || 'html';
7816 my $diff_style = $input_params{'diff_style'} || 'inline';
7817
7818 my ($patch_max) = gitweb_get_feature('patches');
7819 if ($format eq 'patch') {
7820 die_error(403, "Patch view not allowed") unless $patch_max;
7821 }
7822
7823 $hash ||= $hash_base || "HEAD";
7824 my %co = parse_commit($hash)
7825 or die_error(404, "Unknown commit object");
7826
7827 # choose format for commitdiff for merge
7828 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7829 $hash_parent = '--cc';
7830 }
7831 # we need to prepare $formats_nav before almost any parameter munging
7832 my $formats_nav;
7833 if ($format eq 'html') {
7834 $formats_nav =
7835 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7836 "raw");
7837 if ($patch_max && @{$co{'parents'}} <= 1) {
7838 $formats_nav .= " | " .
7839 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7840 "patch");
7841 }
7842 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7843
7844 if (defined $hash_parent &&
7845 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7846 # commitdiff with two commits given
7847 my $hash_parent_short = $hash_parent;
7848 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7849 $hash_parent_short = substr($hash_parent, 0, 7);
7850 }
7851 $formats_nav .=
7852 ' (from';
7853 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7854 if ($co{'parents'}[$i] eq $hash_parent) {
7855 $formats_nav .= ' parent ' . ($i+1);
7856 last;
7857 }
7858 }
7859 $formats_nav .= ': ' .
7860 $cgi->a({-href => href(-replay=>1,
7861 hash=>$hash_parent, hash_base=>undef)},
7862 esc_html($hash_parent_short)) .
7863 ')';
7864 } elsif (!$co{'parent'}) {
7865 # --root commitdiff
7866 $formats_nav .= ' (initial)';
7867 } elsif (scalar @{$co{'parents'}} == 1) {
7868 # single parent commit
7869 $formats_nav .=
7870 ' (parent: ' .
7871 $cgi->a({-href => href(-replay=>1,
7872 hash=>$co{'parent'}, hash_base=>undef)},
7873 esc_html(substr($co{'parent'}, 0, 7))) .
7874 ')';
7875 } else {
7876 # merge commit
7877 if ($hash_parent eq '--cc') {
7878 $formats_nav .= ' | ' .
7879 $cgi->a({-href => href(-replay=>1,
7880 hash=>$hash, hash_parent=>'-c')},
7881 'combined');
7882 } else { # $hash_parent eq '-c'
7883 $formats_nav .= ' | ' .
7884 $cgi->a({-href => href(-replay=>1,
7885 hash=>$hash, hash_parent=>'--cc')},
7886 'compact');
7887 }
7888 $formats_nav .=
7889 ' (merge: ' .
7890 join(' ', map {
7891 $cgi->a({-href => href(-replay=>1,
7892 hash=>$_, hash_base=>undef)},
7893 esc_html(substr($_, 0, 7)));
7894 } @{$co{'parents'}} ) .
7895 ')';
7896 }
7897 }
7898
7899 my $hash_parent_param = $hash_parent;
7900 if (!defined $hash_parent_param) {
7901 # --cc for multiple parents, --root for parentless
7902 $hash_parent_param =
7903 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7904 }
7905
7906 # read commitdiff
7907 my $fd;
7908 my @difftree;
7909 if ($format eq 'html') {
7910 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7911 "--no-commit-id", "--patch-with-raw", "--full-index",
7912 $hash_parent_param, $hash, "--"
7913 or die_error(500, "Open git-diff-tree failed");
7914
7915 while (my $line = <$fd>) {
7916 chomp $line;
7917 # empty line ends raw part of diff-tree output
7918 last unless $line;
7919 push @difftree, scalar parse_difftree_raw_line($line);
7920 }
7921
7922 } elsif ($format eq 'plain') {
7923 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7924 '-p', $hash_parent_param, $hash, "--"
7925 or die_error(500, "Open git-diff-tree failed");
7926 } elsif ($format eq 'patch') {
7927 # For commit ranges, we limit the output to the number of
7928 # patches specified in the 'patches' feature.
7929 # For single commits, we limit the output to a single patch,
7930 # diverging from the git-format-patch default.
7931 my @commit_spec = ();
7932 if ($hash_parent) {
7933 if ($patch_max > 0) {
7934 push @commit_spec, "-$patch_max";
7935 }
7936 push @commit_spec, '-n', "$hash_parent..$hash";
7937 } else {
7938 if ($params{-single}) {
7939 push @commit_spec, '-1';
7940 } else {
7941 if ($patch_max > 0) {
7942 push @commit_spec, "-$patch_max";
7943 }
7944 push @commit_spec, "-n";
7945 }
7946 push @commit_spec, '--root', $hash;
7947 }
7948 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7949 '--encoding=utf8', '--stdout', @commit_spec
7950 or die_error(500, "Open git-format-patch failed");
7951 } else {
7952 die_error(400, "Unknown commitdiff format");
7953 }
7954
7955 # non-textual hash id's can be cached
7956 my $expires;
7957 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7958 $expires = "+1d";
7959 }
7960
7961 # write commit message
7962 if ($format eq 'html') {
7963 my $refs = git_get_references();
7964 my $ref = format_ref_marker($refs, $co{'id'});
7965
7966 git_header_html(undef, $expires);
7967 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7968 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7969 print "<div class=\"title_text\">\n" .
7970 "<table class=\"object_header\">\n";
7971 git_print_authorship_rows(\%co);
7972 print "</table>".
7973 "</div>\n";
7974 print "<div class=\"page_body\">\n";
7975 if (@{$co{'comment'}} > 1) {
7976 print "<div class=\"log\">\n";
7977 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7978 print "</div>\n"; # class="log"
7979 }
7980
7981 } elsif ($format eq 'plain') {
7982 my $refs = git_get_references("tags");
7983 my $tagname = git_get_rev_name_tags($hash);
7984 my $filename = basename($project) . "-$hash.patch";
7985
7986 print $cgi->header(
7987 -type => 'text/plain',
7988 -charset => 'utf-8',
7989 -expires => $expires,
7990 -content_disposition => 'inline; filename="' . "$filename" . '"');
7991 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7992 print "From: " . to_utf8($co{'author'}) . "\n";
7993 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7994 print "Subject: " . to_utf8($co{'title'}) . "\n";
7995
7996 print "X-Git-Tag: $tagname\n" if $tagname;
7997 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7998
7999 foreach my $line (@{$co{'comment'}}) {
8000 print to_utf8($line) . "\n";
8001 }
8002 print "---\n\n";
8003 } elsif ($format eq 'patch') {
8004 my $filename = basename($project) . "-$hash.patch";
8005
8006 print $cgi->header(
8007 -type => 'text/plain',
8008 -charset => 'utf-8',
8009 -expires => $expires,
8010 -content_disposition => 'inline; filename="' . "$filename" . '"');
8011 }
8012
8013 # write patch
8014 if ($format eq 'html') {
8015 my $use_parents = !defined $hash_parent ||
8016 $hash_parent eq '-c' || $hash_parent eq '--cc';
8017 git_difftree_body(\@difftree, $hash,
8018 $use_parents ? @{$co{'parents'}} : $hash_parent);
8019 print "<br/>\n";
8020
8021 git_patchset_body($fd, $diff_style,
8022 \@difftree, $hash,
8023 $use_parents ? @{$co{'parents'}} : $hash_parent);
8024 close $fd;
8025 print "</div>\n"; # class="page_body"
8026 git_footer_html();
8027
8028 } elsif ($format eq 'plain') {
8029 local $/ = undef;
8030 print <$fd>;
8031 close $fd
8032 or print "Reading git-diff-tree failed\n";
8033 } elsif ($format eq 'patch') {
8034 local $/ = undef;
8035 print <$fd>;
8036 close $fd
8037 or print "Reading git-format-patch failed\n";
8038 }
8039 }
8040
8041 sub git_commitdiff_plain {
8042 git_commitdiff(-format => 'plain');
8043 }
8044
8045 # format-patch-style patches
8046 sub git_patch {
8047 git_commitdiff(-format => 'patch', -single => 1);
8048 }
8049
8050 sub git_patches {
8051 git_commitdiff(-format => 'patch');
8052 }
8053
8054 sub git_history {
8055 git_log_generic('history', \&git_history_body,
8056 $hash_base, $hash_parent_base,
8057 $file_name, $hash);
8058 }
8059
8060 sub git_search {
8061 $searchtype ||= 'commit';
8062
8063 # check if appropriate features are enabled
8064 gitweb_check_feature('search')
8065 or die_error(403, "Search is disabled");
8066 if ($searchtype eq 'pickaxe') {
8067 # pickaxe may take all resources of your box and run for several minutes
8068 # with every query - so decide by yourself how public you make this feature
8069 gitweb_check_feature('pickaxe')
8070 or die_error(403, "Pickaxe search is disabled");
8071 }
8072 if ($searchtype eq 'grep') {
8073 # grep search might be potentially CPU-intensive, too
8074 gitweb_check_feature('grep')
8075 or die_error(403, "Grep search is disabled");
8076 }
8077
8078 if (!defined $searchtext) {
8079 die_error(400, "Text field is empty");
8080 }
8081 if (!defined $hash) {
8082 $hash = git_get_head_hash($project);
8083 }
8084 my %co = parse_commit($hash);
8085 if (!%co) {
8086 die_error(404, "Unknown commit object");
8087 }
8088 if (!defined $page) {
8089 $page = 0;
8090 }
8091
8092 if ($searchtype eq 'commit' ||
8093 $searchtype eq 'author' ||
8094 $searchtype eq 'committer') {
8095 git_search_message(%co);
8096 } elsif ($searchtype eq 'pickaxe') {
8097 git_search_changes(%co);
8098 } elsif ($searchtype eq 'grep') {
8099 git_search_files(%co);
8100 } else {
8101 die_error(400, "Unknown search type");
8102 }
8103 }
8104
8105 sub git_search_help {
8106 git_header_html();
8107 git_print_page_nav('','', $hash,$hash,$hash);
8108 print <<EOT;
8109 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8110 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8111 the pattern entered is recognized as the POSIX extended
8112 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8113 insensitive).</p>
8114 <dl>
8115 <dt><b>commit</b></dt>
8116 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8117 EOT
8118 my $have_grep = gitweb_check_feature('grep');
8119 if ($have_grep) {
8120 print <<EOT;
8121 <dt><b>grep</b></dt>
8122 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8123 a different one) are searched for the given pattern. On large trees, this search can take
8124 a while and put some strain on the server, so please use it with some consideration. Note that
8125 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8126 case-sensitive.</dd>
8127 EOT
8128 }
8129 print <<EOT;
8130 <dt><b>author</b></dt>
8131 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8132 <dt><b>committer</b></dt>
8133 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8134 EOT
8135 my $have_pickaxe = gitweb_check_feature('pickaxe');
8136 if ($have_pickaxe) {
8137 print <<EOT;
8138 <dt><b>pickaxe</b></dt>
8139 <dd>All commits that caused the string to appear or disappear from any file (changes that
8140 added, removed or "modified" the string) will be listed. This search can take a while and
8141 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8142 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8143 EOT
8144 }
8145 print "</dl>\n";
8146 git_footer_html();
8147 }
8148
8149 sub git_shortlog {
8150 git_log_generic('shortlog', \&git_shortlog_body,
8151 $hash, $hash_parent);
8152 }
8153
8154 ## ......................................................................
8155 ## feeds (RSS, Atom; OPML)
8156
8157 sub git_feed {
8158 my $format = shift || 'atom';
8159 my $have_blame = gitweb_check_feature('blame');
8160
8161 # Atom: http://www.atomenabled.org/developers/syndication/
8162 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8163 if ($format ne 'rss' && $format ne 'atom') {
8164 die_error(400, "Unknown web feed format");
8165 }
8166
8167 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8168 my $head = $hash || 'HEAD';
8169 my @commitlist = parse_commits($head, 150, 0, $file_name);
8170
8171 my %latest_commit;
8172 my %latest_date;
8173 my $content_type = "application/$format+xml";
8174 if (defined $cgi->http('HTTP_ACCEPT') &&
8175 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8176 # browser (feed reader) prefers text/xml
8177 $content_type = 'text/xml';
8178 }
8179 if (defined($commitlist[0])) {
8180 %latest_commit = %{$commitlist[0]};
8181 my $latest_epoch = $latest_commit{'committer_epoch'};
8182 exit_if_unmodified_since($latest_epoch);
8183 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8184 }
8185 print $cgi->header(
8186 -type => $content_type,
8187 -charset => 'utf-8',
8188 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8189 -status => '200 OK');
8190
8191 # Optimization: skip generating the body if client asks only
8192 # for Last-Modified date.
8193 return if ($cgi->request_method() eq 'HEAD');
8194
8195 # header variables
8196 my $title = "$site_name - $project/$action";
8197 my $feed_type = 'log';
8198 if (defined $hash) {
8199 $title .= " - '$hash'";
8200 $feed_type = 'branch log';
8201 if (defined $file_name) {
8202 $title .= " :: $file_name";
8203 $feed_type = 'history';
8204 }
8205 } elsif (defined $file_name) {
8206 $title .= " - $file_name";
8207 $feed_type = 'history';
8208 }
8209 $title .= " $feed_type";
8210 $title = esc_html($title);
8211 my $descr = git_get_project_description($project);
8212 if (defined $descr) {
8213 $descr = esc_html($descr);
8214 } else {
8215 $descr = "$project " .
8216 ($format eq 'rss' ? 'RSS' : 'Atom') .
8217 " feed";
8218 }
8219 my $owner = git_get_project_owner($project);
8220 $owner = esc_html($owner);
8221
8222 #header
8223 my $alt_url;
8224 if (defined $file_name) {
8225 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8226 } elsif (defined $hash) {
8227 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8228 } else {
8229 $alt_url = href(-full=>1, action=>"summary");
8230 }
8231 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8232 if ($format eq 'rss') {
8233 print <<XML;
8234 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8235 <channel>
8236 XML
8237 print "<title>$title</title>\n" .
8238 "<link>$alt_url</link>\n" .
8239 "<description>$descr</description>\n" .
8240 "<language>en</language>\n" .
8241 # project owner is responsible for 'editorial' content
8242 "<managingEditor>$owner</managingEditor>\n";
8243 if (defined $logo || defined $favicon) {
8244 # prefer the logo to the favicon, since RSS
8245 # doesn't allow both
8246 my $img = esc_url($logo || $favicon);
8247 print "<image>\n" .
8248 "<url>$img</url>\n" .
8249 "<title>$title</title>\n" .
8250 "<link>$alt_url</link>\n" .
8251 "</image>\n";
8252 }
8253 if (%latest_date) {
8254 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8255 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8256 }
8257 print "<generator>gitweb v.$version/$git_version</generator>\n";
8258 } elsif ($format eq 'atom') {
8259 print <<XML;
8260 <feed xmlns="http://www.w3.org/2005/Atom">
8261 XML
8262 print "<title>$title</title>\n" .
8263 "<subtitle>$descr</subtitle>\n" .
8264 '<link rel="alternate" type="text/html" href="' .
8265 $alt_url . '" />' . "\n" .
8266 '<link rel="self" type="' . $content_type . '" href="' .
8267 $cgi->self_url() . '" />' . "\n" .
8268 "<id>" . href(-full=>1) . "</id>\n" .
8269 # use project owner for feed author
8270 "<author><name>$owner</name></author>\n";
8271 if (defined $favicon) {
8272 print "<icon>" . esc_url($favicon) . "</icon>\n";
8273 }
8274 if (defined $logo) {
8275 # not twice as wide as tall: 72 x 27 pixels
8276 print "<logo>" . esc_url($logo) . "</logo>\n";
8277 }
8278 if (! %latest_date) {
8279 # dummy date to keep the feed valid until commits trickle in:
8280 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8281 } else {
8282 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8283 }
8284 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8285 }
8286
8287 # contents
8288 for (my $i = 0; $i <= $#commitlist; $i++) {
8289 my %co = %{$commitlist[$i]};
8290 my $commit = $co{'id'};
8291 # we read 150, we always show 30 and the ones more recent than 48 hours
8292 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8293 last;
8294 }
8295 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8296
8297 # get list of changed files
8298 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8299 $co{'parent'} || "--root",
8300 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8301 or next;
8302 my @difftree = map { chomp; $_ } <$fd>;
8303 close $fd
8304 or next;
8305
8306 # print element (entry, item)
8307 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8308 if ($format eq 'rss') {
8309 print "<item>\n" .
8310 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8311 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8312 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8313 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8314 "<link>$co_url</link>\n" .
8315 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8316 "<content:encoded>" .
8317 "<![CDATA[\n";
8318 } elsif ($format eq 'atom') {
8319 print "<entry>\n" .
8320 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8321 "<updated>$cd{'iso-8601'}</updated>\n" .
8322 "<author>\n" .
8323 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8324 if ($co{'author_email'}) {
8325 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8326 }
8327 print "</author>\n" .
8328 # use committer for contributor
8329 "<contributor>\n" .
8330 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8331 if ($co{'committer_email'}) {
8332 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8333 }
8334 print "</contributor>\n" .
8335 "<published>$cd{'iso-8601'}</published>\n" .
8336 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8337 "<id>$co_url</id>\n" .
8338 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8339 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8340 }
8341 my $comment = $co{'comment'};
8342 print "<pre>\n";
8343 foreach my $line (@$comment) {
8344 $line = esc_html($line);
8345 print "$line\n";
8346 }
8347 print "</pre><ul>\n";
8348 foreach my $difftree_line (@difftree) {
8349 my %difftree = parse_difftree_raw_line($difftree_line);
8350 next if !$difftree{'from_id'};
8351
8352 my $file = $difftree{'file'} || $difftree{'to_file'};
8353
8354 print "<li>" .
8355 "[" .
8356 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8357 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8358 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8359 file_name=>$file, file_parent=>$difftree{'from_file'}),
8360 -title => "diff"}, 'D');
8361 if ($have_blame) {
8362 print $cgi->a({-href => href(-full=>1, action=>"blame",
8363 file_name=>$file, hash_base=>$commit),
8364 -title => "blame"}, 'B');
8365 }
8366 # if this is not a feed of a file history
8367 if (!defined $file_name || $file_name ne $file) {
8368 print $cgi->a({-href => href(-full=>1, action=>"history",
8369 file_name=>$file, hash=>$commit),
8370 -title => "history"}, 'H');
8371 }
8372 $file = esc_path($file);
8373 print "] ".
8374 "$file</li>\n";
8375 }
8376 if ($format eq 'rss') {
8377 print "</ul>]]>\n" .
8378 "</content:encoded>\n" .
8379 "</item>\n";
8380 } elsif ($format eq 'atom') {
8381 print "</ul>\n</div>\n" .
8382 "</content>\n" .
8383 "</entry>\n";
8384 }
8385 }
8386
8387 # end of feed
8388 if ($format eq 'rss') {
8389 print "</channel>\n</rss>\n";
8390 } elsif ($format eq 'atom') {
8391 print "</feed>\n";
8392 }
8393 }
8394
8395 sub git_rss {
8396 git_feed('rss');
8397 }
8398
8399 sub git_atom {
8400 git_feed('atom');
8401 }
8402
8403 sub git_opml {
8404 my @list = git_get_projects_list($project_filter, $strict_export);
8405 if (!@list) {
8406 die_error(404, "No projects found");
8407 }
8408
8409 print $cgi->header(
8410 -type => 'text/xml',
8411 -charset => 'utf-8',
8412 -content_disposition => 'inline; filename="opml.xml"');
8413
8414 my $title = esc_html($site_name);
8415 my $filter = " within subdirectory ";
8416 if (defined $project_filter) {
8417 $filter .= esc_html($project_filter);
8418 } else {
8419 $filter = "";
8420 }
8421 print <<XML;
8422 <?xml version="1.0" encoding="utf-8"?>
8423 <opml version="1.0">
8424 <head>
8425 <title>$title OPML Export$filter</title>
8426 </head>
8427 <body>
8428 <outline text="git RSS feeds">
8429 XML
8430
8431 foreach my $pr (@list) {
8432 my %proj = %$pr;
8433 my $head = git_get_head_hash($proj{'path'});
8434 if (!defined $head) {
8435 next;
8436 }
8437 $git_dir = "$projectroot/$proj{'path'}";
8438 my %co = parse_commit($head);
8439 if (!%co) {
8440 next;
8441 }
8442
8443 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8444 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8445 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8446 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8447 }
8448 print <<XML;
8449 </outline>
8450 </body>
8451 </opml>
8452 XML
8453 }