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