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