]> Lady’s Gitweb - Gitweb/blob - gitweb.perl
gitweb: make hash size independent
[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 ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
746 read_config_file($GITWEB_CONFIG_COMMON);
747
748 # Use first config file that exists. This means use the per-instance
749 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
750 read_config_file($GITWEB_CONFIG) and return;
751 read_config_file($GITWEB_CONFIG_SYSTEM);
752 }
753
754 # Get loadavg of system, to compare against $maxload.
755 # Currently it requires '/proc/loadavg' present to get loadavg;
756 # if it is not present it returns 0, which means no load checking.
757 sub get_loadavg {
758 if( -e '/proc/loadavg' ){
759 open my $fd, '<', '/proc/loadavg'
760 or return 0;
761 my @load = split(/\s+/, scalar <$fd>);
762 close $fd;
763
764 # The first three columns measure CPU and IO utilization of the last one,
765 # five, and 10 minute periods. The fourth column shows the number of
766 # currently running processes and the total number of processes in the m/n
767 # format. The last column displays the last process ID used.
768 return $load[0] || 0;
769 }
770 # additional checks for load average should go here for things that don't export
771 # /proc/loadavg
772
773 return 0;
774 }
775
776 # version of the core git binary
777 our $git_version;
778 sub evaluate_git_version {
779 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
780 $number_of_git_cmds++;
781 }
782
783 sub check_loadavg {
784 if (defined $maxload && get_loadavg() > $maxload) {
785 die_error(503, "The load average on the server is too high");
786 }
787 }
788
789 # ======================================================================
790 # input validation and dispatch
791
792 # 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', # carrige 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'} = 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'} = 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), href(project=>undef, action=>"project_index"));
4075 printf('<link rel="alternate" title="%s projects feeds" '.
4076 'href="%s" type="text/x-opml" />'."\n",
4077 esc_attr($site_name), href(project=>undef, action=>"opml"));
4078 }
4079 }
4080
4081 sub print_header_links {
4082 my $status = shift;
4083
4084 # print out each stylesheet that exist, providing backwards capability
4085 # for those people who defined $stylesheet in a config file
4086 if (defined $stylesheet) {
4087 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4088 } else {
4089 foreach my $stylesheet (@stylesheets) {
4090 next unless $stylesheet;
4091 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4092 }
4093 }
4094 print_feed_meta()
4095 if ($status eq '200 OK');
4096 if (defined $favicon) {
4097 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4098 }
4099 }
4100
4101 sub print_nav_breadcrumbs_path {
4102 my $dirprefix = undef;
4103 while (my $part = shift) {
4104 $dirprefix .= "/" if defined $dirprefix;
4105 $dirprefix .= $part;
4106 print $cgi->a({-href => href(project => undef,
4107 project_filter => $dirprefix,
4108 action => "project_list")},
4109 esc_html($part)) . " / ";
4110 }
4111 }
4112
4113 sub print_nav_breadcrumbs {
4114 my %opts = @_;
4115
4116 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4117 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4118 }
4119 if (defined $project) {
4120 my @dirname = split '/', $project;
4121 my $projectbasename = pop @dirname;
4122 print_nav_breadcrumbs_path(@dirname);
4123 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4124 if (defined $action) {
4125 my $action_print = $action ;
4126 if (defined $opts{-action_extra}) {
4127 $action_print = $cgi->a({-href => href(action=>$action)},
4128 $action);
4129 }
4130 print " / $action_print";
4131 }
4132 if (defined $opts{-action_extra}) {
4133 print " / $opts{-action_extra}";
4134 }
4135 print "\n";
4136 } elsif (defined $project_filter) {
4137 print_nav_breadcrumbs_path(split '/', $project_filter);
4138 }
4139 }
4140
4141 sub print_search_form {
4142 if (!defined $searchtext) {
4143 $searchtext = "";
4144 }
4145 my $search_hash;
4146 if (defined $hash_base) {
4147 $search_hash = $hash_base;
4148 } elsif (defined $hash) {
4149 $search_hash = $hash;
4150 } else {
4151 $search_hash = "HEAD";
4152 }
4153 my $action = $my_uri;
4154 my $use_pathinfo = gitweb_check_feature('pathinfo');
4155 if ($use_pathinfo) {
4156 $action .= "/".esc_url($project);
4157 }
4158 print $cgi->start_form(-method => "get", -action => $action) .
4159 "<div class=\"search\">\n" .
4160 (!$use_pathinfo &&
4161 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4162 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4163 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4164 $cgi->popup_menu(-name => 'st', -default => 'commit',
4165 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4166 " " . $cgi->a({-href => href(action=>"search_help"),
4167 -title => "search help" }, "?") . " search:\n",
4168 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4169 "<span title=\"Extended regular expression\">" .
4170 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4171 -checked => $search_use_regexp) .
4172 "</span>" .
4173 "</div>" .
4174 $cgi->end_form() . "\n";
4175 }
4176
4177 sub git_header_html {
4178 my $status = shift || "200 OK";
4179 my $expires = shift;
4180 my %opts = @_;
4181
4182 my $title = get_page_title();
4183 my $content_type = get_content_type_html();
4184 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4185 -status=> $status, -expires => $expires)
4186 unless ($opts{'-no_http_header'});
4187 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4188 print <<EOF;
4189 <?xml version="1.0" encoding="utf-8"?>
4190 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4191 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4192 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4193 <!-- git core binaries version $git_version -->
4194 <head>
4195 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4196 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4197 <meta name="robots" content="index, nofollow"/>
4198 <title>$title</title>
4199 EOF
4200 # the stylesheet, favicon etc urls won't work correctly with path_info
4201 # unless we set the appropriate base URL
4202 if ($ENV{'PATH_INFO'}) {
4203 print "<base href=\"".esc_url($base_url)."\" />\n";
4204 }
4205 print_header_links($status);
4206
4207 if (defined $site_html_head_string) {
4208 print to_utf8($site_html_head_string);
4209 }
4210
4211 print "</head>\n" .
4212 "<body>\n";
4213
4214 if (defined $site_header && -f $site_header) {
4215 insert_file($site_header);
4216 }
4217
4218 print "<div class=\"page_header\">\n";
4219 if (defined $logo) {
4220 print $cgi->a({-href => esc_url($logo_url),
4221 -title => $logo_label},
4222 $cgi->img({-src => esc_url($logo),
4223 -width => 72, -height => 27,
4224 -alt => "git",
4225 -class => "logo"}));
4226 }
4227 print_nav_breadcrumbs(%opts);
4228 print "</div>\n";
4229
4230 my $have_search = gitweb_check_feature('search');
4231 if (defined $project && $have_search) {
4232 print_search_form();
4233 }
4234 }
4235
4236 sub git_footer_html {
4237 my $feed_class = 'rss_logo';
4238
4239 print "<div class=\"page_footer\">\n";
4240 if (defined $project) {
4241 my $descr = git_get_project_description($project);
4242 if (defined $descr) {
4243 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4244 }
4245
4246 my %href_params = get_feed_info();
4247 if (!%href_params) {
4248 $feed_class .= ' generic';
4249 }
4250 $href_params{'-title'} ||= 'log';
4251
4252 foreach my $format (qw(RSS Atom)) {
4253 $href_params{'action'} = lc($format);
4254 print $cgi->a({-href => href(%href_params),
4255 -title => "$href_params{'-title'} $format feed",
4256 -class => $feed_class}, $format)."\n";
4257 }
4258
4259 } else {
4260 print $cgi->a({-href => href(project=>undef, action=>"opml",
4261 project_filter => $project_filter),
4262 -class => $feed_class}, "OPML") . " ";
4263 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4264 project_filter => $project_filter),
4265 -class => $feed_class}, "TXT") . "\n";
4266 }
4267 print "</div>\n"; # class="page_footer"
4268
4269 if (defined $t0 && gitweb_check_feature('timed')) {
4270 print "<div id=\"generating_info\">\n";
4271 print 'This page took '.
4272 '<span id="generating_time" class="time_span">'.
4273 tv_interval($t0, [ gettimeofday() ]).
4274 ' seconds </span>'.
4275 ' and '.
4276 '<span id="generating_cmd">'.
4277 $number_of_git_cmds.
4278 '</span> git commands '.
4279 " to generate.\n";
4280 print "</div>\n"; # class="page_footer"
4281 }
4282
4283 if (defined $site_footer && -f $site_footer) {
4284 insert_file($site_footer);
4285 }
4286
4287 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4288 if (defined $action &&
4289 $action eq 'blame_incremental') {
4290 print qq!<script type="text/javascript">\n!.
4291 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4292 qq! "!. href() .qq!");\n!.
4293 qq!</script>\n!;
4294 } else {
4295 my ($jstimezone, $tz_cookie, $datetime_class) =
4296 gitweb_get_feature('javascript-timezone');
4297
4298 print qq!<script type="text/javascript">\n!.
4299 qq!window.onload = function () {\n!;
4300 if (gitweb_check_feature('javascript-actions')) {
4301 print qq! fixLinks();\n!;
4302 }
4303 if ($jstimezone && $tz_cookie && $datetime_class) {
4304 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4305 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4306 }
4307 print qq!};\n!.
4308 qq!</script>\n!;
4309 }
4310
4311 print "</body>\n" .
4312 "</html>";
4313 }
4314
4315 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4316 # Example: die_error(404, 'Hash not found')
4317 # By convention, use the following status codes (as defined in RFC 2616):
4318 # 400: Invalid or missing CGI parameters, or
4319 # requested object exists but has wrong type.
4320 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4321 # this server or project.
4322 # 404: Requested object/revision/project doesn't exist.
4323 # 500: The server isn't configured properly, or
4324 # an internal error occurred (e.g. failed assertions caused by bugs), or
4325 # an unknown error occurred (e.g. the git binary died unexpectedly).
4326 # 503: The server is currently unavailable (because it is overloaded,
4327 # or down for maintenance). Generally, this is a temporary state.
4328 sub die_error {
4329 my $status = shift || 500;
4330 my $error = esc_html(shift) || "Internal Server Error";
4331 my $extra = shift;
4332 my %opts = @_;
4333
4334 my %http_responses = (
4335 400 => '400 Bad Request',
4336 403 => '403 Forbidden',
4337 404 => '404 Not Found',
4338 500 => '500 Internal Server Error',
4339 503 => '503 Service Unavailable',
4340 );
4341 git_header_html($http_responses{$status}, undef, %opts);
4342 print <<EOF;
4343 <div class="page_body">
4344 <br /><br />
4345 $status - $error
4346 <br />
4347 EOF
4348 if (defined $extra) {
4349 print "<hr />\n" .
4350 "$extra\n";
4351 }
4352 print "</div>\n";
4353
4354 git_footer_html();
4355 goto DONE_GITWEB
4356 unless ($opts{'-error_handler'});
4357 }
4358
4359 ## ----------------------------------------------------------------------
4360 ## functions printing or outputting HTML: navigation
4361
4362 sub git_print_page_nav {
4363 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4364 $extra = '' if !defined $extra; # pager or formats
4365
4366 my @navs = qw(summary shortlog log commit commitdiff tree);
4367 if ($suppress) {
4368 @navs = grep { $_ ne $suppress } @navs;
4369 }
4370
4371 my %arg = map { $_ => {action=>$_} } @navs;
4372 if (defined $head) {
4373 for (qw(commit commitdiff)) {
4374 $arg{$_}{'hash'} = $head;
4375 }
4376 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4377 for (qw(shortlog log)) {
4378 $arg{$_}{'hash'} = $head;
4379 }
4380 }
4381 }
4382
4383 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4384 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4385
4386 my @actions = gitweb_get_feature('actions');
4387 my %repl = (
4388 '%' => '%',
4389 'n' => $project, # project name
4390 'f' => $git_dir, # project path within filesystem
4391 'h' => $treehead || '', # current hash ('h' parameter)
4392 'b' => $treebase || '', # hash base ('hb' parameter)
4393 );
4394 while (@actions) {
4395 my ($label, $link, $pos) = splice(@actions,0,3);
4396 # insert
4397 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4398 # munch munch
4399 $link =~ s/%([%nfhb])/$repl{$1}/g;
4400 $arg{$label}{'_href'} = $link;
4401 }
4402
4403 print "<div class=\"page_nav\">\n" .
4404 (join " | ",
4405 map { $_ eq $current ?
4406 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4407 } @navs);
4408 print "<br/>\n$extra<br/>\n" .
4409 "</div>\n";
4410 }
4411
4412 # returns a submenu for the navigation of the refs views (tags, heads,
4413 # remotes) with the current view disabled and the remotes view only
4414 # available if the feature is enabled
4415 sub format_ref_views {
4416 my ($current) = @_;
4417 my @ref_views = qw{tags heads};
4418 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4419 return join " | ", map {
4420 $_ eq $current ? $_ :
4421 $cgi->a({-href => href(action=>$_)}, $_)
4422 } @ref_views
4423 }
4424
4425 sub format_paging_nav {
4426 my ($action, $page, $has_next_link) = @_;
4427 my $paging_nav;
4428
4429
4430 if ($page > 0) {
4431 $paging_nav .=
4432 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4433 " &sdot; " .
4434 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4435 -accesskey => "p", -title => "Alt-p"}, "prev");
4436 } else {
4437 $paging_nav .= "first &sdot; prev";
4438 }
4439
4440 if ($has_next_link) {
4441 $paging_nav .= " &sdot; " .
4442 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4443 -accesskey => "n", -title => "Alt-n"}, "next");
4444 } else {
4445 $paging_nav .= " &sdot; next";
4446 }
4447
4448 return $paging_nav;
4449 }
4450
4451 ## ......................................................................
4452 ## functions printing or outputting HTML: div
4453
4454 sub git_print_header_div {
4455 my ($action, $title, $hash, $hash_base) = @_;
4456 my %args = ();
4457
4458 $args{'action'} = $action;
4459 $args{'hash'} = $hash if $hash;
4460 $args{'hash_base'} = $hash_base if $hash_base;
4461
4462 print "<div class=\"header\">\n" .
4463 $cgi->a({-href => href(%args), -class => "title"},
4464 $title ? $title : $action) .
4465 "\n</div>\n";
4466 }
4467
4468 sub format_repo_url {
4469 my ($name, $url) = @_;
4470 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4471 }
4472
4473 # Group output by placing it in a DIV element and adding a header.
4474 # Options for start_div() can be provided by passing a hash reference as the
4475 # first parameter to the function.
4476 # Options to git_print_header_div() can be provided by passing an array
4477 # reference. This must follow the options to start_div if they are present.
4478 # The content can be a scalar, which is output as-is, a scalar reference, which
4479 # is output after html escaping, an IO handle passed either as *handle or
4480 # *handle{IO}, or a function reference. In the latter case all following
4481 # parameters will be taken as argument to the content function call.
4482 sub git_print_section {
4483 my ($div_args, $header_args, $content);
4484 my $arg = shift;
4485 if (ref($arg) eq 'HASH') {
4486 $div_args = $arg;
4487 $arg = shift;
4488 }
4489 if (ref($arg) eq 'ARRAY') {
4490 $header_args = $arg;
4491 $arg = shift;
4492 }
4493 $content = $arg;
4494
4495 print $cgi->start_div($div_args);
4496 git_print_header_div(@$header_args);
4497
4498 if (ref($content) eq 'CODE') {
4499 $content->(@_);
4500 } elsif (ref($content) eq 'SCALAR') {
4501 print esc_html($$content);
4502 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4503 print <$content>;
4504 } elsif (!ref($content) && defined($content)) {
4505 print $content;
4506 }
4507
4508 print $cgi->end_div;
4509 }
4510
4511 sub format_timestamp_html {
4512 my $date = shift;
4513 my $strtime = $date->{'rfc2822'};
4514
4515 my (undef, undef, $datetime_class) =
4516 gitweb_get_feature('javascript-timezone');
4517 if ($datetime_class) {
4518 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4519 }
4520
4521 my $localtime_format = '(%02d:%02d %s)';
4522 if ($date->{'hour_local'} < 6) {
4523 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4524 }
4525 $strtime .= ' ' .
4526 sprintf($localtime_format,
4527 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4528
4529 return $strtime;
4530 }
4531
4532 # Outputs the author name and date in long form
4533 sub git_print_authorship {
4534 my $co = shift;
4535 my %opts = @_;
4536 my $tag = $opts{-tag} || 'div';
4537 my $author = $co->{'author_name'};
4538
4539 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4540 print "<$tag class=\"author_date\">" .
4541 format_search_author($author, "author", esc_html($author)) .
4542 " [".format_timestamp_html(\%ad)."]".
4543 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4544 "</$tag>\n";
4545 }
4546
4547 # Outputs table rows containing the full author or committer information,
4548 # in the format expected for 'commit' view (& similar).
4549 # Parameters are a commit hash reference, followed by the list of people
4550 # to output information for. If the list is empty it defaults to both
4551 # author and committer.
4552 sub git_print_authorship_rows {
4553 my $co = shift;
4554 # too bad we can't use @people = @_ || ('author', 'committer')
4555 my @people = @_;
4556 @people = ('author', 'committer') unless @people;
4557 foreach my $who (@people) {
4558 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4559 print "<tr><td>$who</td><td>" .
4560 format_search_author($co->{"${who}_name"}, $who,
4561 esc_html($co->{"${who}_name"})) . " " .
4562 format_search_author($co->{"${who}_email"}, $who,
4563 esc_html("<" . $co->{"${who}_email"} . ">")) .
4564 "</td><td rowspan=\"2\">" .
4565 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4566 "</td></tr>\n" .
4567 "<tr>" .
4568 "<td></td><td>" .
4569 format_timestamp_html(\%wd) .
4570 "</td>" .
4571 "</tr>\n";
4572 }
4573 }
4574
4575 sub git_print_page_path {
4576 my $name = shift;
4577 my $type = shift;
4578 my $hb = shift;
4579
4580
4581 print "<div class=\"page_path\">";
4582 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4583 -title => 'tree root'}, to_utf8("[$project]"));
4584 print " / ";
4585 if (defined $name) {
4586 my @dirname = split '/', $name;
4587 my $basename = pop @dirname;
4588 my $fullname = '';
4589
4590 foreach my $dir (@dirname) {
4591 $fullname .= ($fullname ? '/' : '') . $dir;
4592 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4593 hash_base=>$hb),
4594 -title => $fullname}, esc_path($dir));
4595 print " / ";
4596 }
4597 if (defined $type && $type eq 'blob') {
4598 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4599 hash_base=>$hb),
4600 -title => $name}, esc_path($basename));
4601 } elsif (defined $type && $type eq 'tree') {
4602 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4603 hash_base=>$hb),
4604 -title => $name}, esc_path($basename));
4605 print " / ";
4606 } else {
4607 print esc_path($basename);
4608 }
4609 }
4610 print "<br/></div>\n";
4611 }
4612
4613 sub git_print_log {
4614 my $log = shift;
4615 my %opts = @_;
4616
4617 if ($opts{'-remove_title'}) {
4618 # remove title, i.e. first line of log
4619 shift @$log;
4620 }
4621 # remove leading empty lines
4622 while (defined $log->[0] && $log->[0] eq "") {
4623 shift @$log;
4624 }
4625
4626 # print log
4627 my $skip_blank_line = 0;
4628 foreach my $line (@$log) {
4629 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4630 if (! $opts{'-remove_signoff'}) {
4631 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4632 $skip_blank_line = 1;
4633 }
4634 next;
4635 }
4636
4637 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4638 if (! $opts{'-remove_signoff'}) {
4639 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4640 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4641 "</span><br/>\n";
4642 $skip_blank_line = 1;
4643 }
4644 next;
4645 }
4646
4647 # print only one empty line
4648 # do not print empty line after signoff
4649 if ($line eq "") {
4650 next if ($skip_blank_line);
4651 $skip_blank_line = 1;
4652 } else {
4653 $skip_blank_line = 0;
4654 }
4655
4656 print format_log_line_html($line) . "<br/>\n";
4657 }
4658
4659 if ($opts{'-final_empty_line'}) {
4660 # end with single empty line
4661 print "<br/>\n" unless $skip_blank_line;
4662 }
4663 }
4664
4665 # return link target (what link points to)
4666 sub git_get_link_target {
4667 my $hash = shift;
4668 my $link_target;
4669
4670 # read link
4671 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4672 or return;
4673 {
4674 local $/ = undef;
4675 $link_target = <$fd>;
4676 }
4677 close $fd
4678 or return;
4679
4680 return $link_target;
4681 }
4682
4683 # given link target, and the directory (basedir) the link is in,
4684 # return target of link relative to top directory (top tree);
4685 # return undef if it is not possible (including absolute links).
4686 sub normalize_link_target {
4687 my ($link_target, $basedir) = @_;
4688
4689 # absolute symlinks (beginning with '/') cannot be normalized
4690 return if (substr($link_target, 0, 1) eq '/');
4691
4692 # normalize link target to path from top (root) tree (dir)
4693 my $path;
4694 if ($basedir) {
4695 $path = $basedir . '/' . $link_target;
4696 } else {
4697 # we are in top (root) tree (dir)
4698 $path = $link_target;
4699 }
4700
4701 # remove //, /./, and /../
4702 my @path_parts;
4703 foreach my $part (split('/', $path)) {
4704 # discard '.' and ''
4705 next if (!$part || $part eq '.');
4706 # handle '..'
4707 if ($part eq '..') {
4708 if (@path_parts) {
4709 pop @path_parts;
4710 } else {
4711 # link leads outside repository (outside top dir)
4712 return;
4713 }
4714 } else {
4715 push @path_parts, $part;
4716 }
4717 }
4718 $path = join('/', @path_parts);
4719
4720 return $path;
4721 }
4722
4723 # print tree entry (row of git_tree), but without encompassing <tr> element
4724 sub git_print_tree_entry {
4725 my ($t, $basedir, $hash_base, $have_blame) = @_;
4726
4727 my %base_key = ();
4728 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4729
4730 # The format of a table row is: mode list link. Where mode is
4731 # the mode of the entry, list is the name of the entry, an href,
4732 # and link is the action links of the entry.
4733
4734 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4735 if (exists $t->{'size'}) {
4736 print "<td class=\"size\">$t->{'size'}</td>\n";
4737 }
4738 if ($t->{'type'} eq "blob") {
4739 print "<td class=\"list\">" .
4740 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4741 file_name=>"$basedir$t->{'name'}", %base_key),
4742 -class => "list"}, esc_path($t->{'name'}));
4743 if (S_ISLNK(oct $t->{'mode'})) {
4744 my $link_target = git_get_link_target($t->{'hash'});
4745 if ($link_target) {
4746 my $norm_target = normalize_link_target($link_target, $basedir);
4747 if (defined $norm_target) {
4748 print " -> " .
4749 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4750 file_name=>$norm_target),
4751 -title => $norm_target}, esc_path($link_target));
4752 } else {
4753 print " -> " . esc_path($link_target);
4754 }
4755 }
4756 }
4757 print "</td>\n";
4758 print "<td class=\"link\">";
4759 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4760 file_name=>"$basedir$t->{'name'}", %base_key)},
4761 "blob");
4762 if ($have_blame) {
4763 print " | " .
4764 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4765 file_name=>"$basedir$t->{'name'}", %base_key)},
4766 "blame");
4767 }
4768 if (defined $hash_base) {
4769 print " | " .
4770 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4771 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4772 "history");
4773 }
4774 print " | " .
4775 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4776 file_name=>"$basedir$t->{'name'}")},
4777 "raw");
4778 print "</td>\n";
4779
4780 } elsif ($t->{'type'} eq "tree") {
4781 print "<td class=\"list\">";
4782 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4783 file_name=>"$basedir$t->{'name'}",
4784 %base_key)},
4785 esc_path($t->{'name'}));
4786 print "</td>\n";
4787 print "<td class=\"link\">";
4788 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4789 file_name=>"$basedir$t->{'name'}",
4790 %base_key)},
4791 "tree");
4792 if (defined $hash_base) {
4793 print " | " .
4794 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4795 file_name=>"$basedir$t->{'name'}")},
4796 "history");
4797 }
4798 print "</td>\n";
4799 } else {
4800 # unknown object: we can only present history for it
4801 # (this includes 'commit' object, i.e. submodule support)
4802 print "<td class=\"list\">" .
4803 esc_path($t->{'name'}) .
4804 "</td>\n";
4805 print "<td class=\"link\">";
4806 if (defined $hash_base) {
4807 print $cgi->a({-href => href(action=>"history",
4808 hash_base=>$hash_base,
4809 file_name=>"$basedir$t->{'name'}")},
4810 "history");
4811 }
4812 print "</td>\n";
4813 }
4814 }
4815
4816 ## ......................................................................
4817 ## functions printing large fragments of HTML
4818
4819 # get pre-image filenames for merge (combined) diff
4820 sub fill_from_file_info {
4821 my ($diff, @parents) = @_;
4822
4823 $diff->{'from_file'} = [ ];
4824 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4825 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4826 if ($diff->{'status'}[$i] eq 'R' ||
4827 $diff->{'status'}[$i] eq 'C') {
4828 $diff->{'from_file'}[$i] =
4829 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4830 }
4831 }
4832
4833 return $diff;
4834 }
4835
4836 # is current raw difftree line of file deletion
4837 sub is_deleted {
4838 my $diffinfo = shift;
4839
4840 return $diffinfo->{'to_id'} eq ('0' x 40) || $diffinfo->{'to_id'} eq ('0' x 64);
4841 }
4842
4843 # does patch correspond to [previous] difftree raw line
4844 # $diffinfo - hashref of parsed raw diff format
4845 # $patchinfo - hashref of parsed patch diff format
4846 # (the same keys as in $diffinfo)
4847 sub is_patch_split {
4848 my ($diffinfo, $patchinfo) = @_;
4849
4850 return defined $diffinfo && defined $patchinfo
4851 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4852 }
4853
4854
4855 sub git_difftree_body {
4856 my ($difftree, $hash, @parents) = @_;
4857 my ($parent) = $parents[0];
4858 my $have_blame = gitweb_check_feature('blame');
4859 print "<div class=\"list_head\">\n";
4860 if ($#{$difftree} > 10) {
4861 print(($#{$difftree} + 1) . " files changed:\n");
4862 }
4863 print "</div>\n";
4864
4865 print "<table class=\"" .
4866 (@parents > 1 ? "combined " : "") .
4867 "diff_tree\">\n";
4868
4869 # header only for combined diff in 'commitdiff' view
4870 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4871 if ($has_header) {
4872 # table header
4873 print "<thead><tr>\n" .
4874 "<th></th><th></th>\n"; # filename, patchN link
4875 for (my $i = 0; $i < @parents; $i++) {
4876 my $par = $parents[$i];
4877 print "<th>" .
4878 $cgi->a({-href => href(action=>"commitdiff",
4879 hash=>$hash, hash_parent=>$par),
4880 -title => 'commitdiff to parent number ' .
4881 ($i+1) . ': ' . substr($par,0,7)},
4882 $i+1) .
4883 "&nbsp;</th>\n";
4884 }
4885 print "</tr></thead>\n<tbody>\n";
4886 }
4887
4888 my $alternate = 1;
4889 my $patchno = 0;
4890 foreach my $line (@{$difftree}) {
4891 my $diff = parsed_difftree_line($line);
4892
4893 if ($alternate) {
4894 print "<tr class=\"dark\">\n";
4895 } else {
4896 print "<tr class=\"light\">\n";
4897 }
4898 $alternate ^= 1;
4899
4900 if (exists $diff->{'nparents'}) { # combined diff
4901
4902 fill_from_file_info($diff, @parents)
4903 unless exists $diff->{'from_file'};
4904
4905 if (!is_deleted($diff)) {
4906 # file exists in the result (child) commit
4907 print "<td>" .
4908 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4909 file_name=>$diff->{'to_file'},
4910 hash_base=>$hash),
4911 -class => "list"}, esc_path($diff->{'to_file'})) .
4912 "</td>\n";
4913 } else {
4914 print "<td>" .
4915 esc_path($diff->{'to_file'}) .
4916 "</td>\n";
4917 }
4918
4919 if ($action eq 'commitdiff') {
4920 # link to patch
4921 $patchno++;
4922 print "<td class=\"link\">" .
4923 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4924 "patch") .
4925 " | " .
4926 "</td>\n";
4927 }
4928
4929 my $has_history = 0;
4930 my $not_deleted = 0;
4931 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4932 my $hash_parent = $parents[$i];
4933 my $from_hash = $diff->{'from_id'}[$i];
4934 my $from_path = $diff->{'from_file'}[$i];
4935 my $status = $diff->{'status'}[$i];
4936
4937 $has_history ||= ($status ne 'A');
4938 $not_deleted ||= ($status ne 'D');
4939
4940 if ($status eq 'A') {
4941 print "<td class=\"link\" align=\"right\"> | </td>\n";
4942 } elsif ($status eq 'D') {
4943 print "<td class=\"link\">" .
4944 $cgi->a({-href => href(action=>"blob",
4945 hash_base=>$hash,
4946 hash=>$from_hash,
4947 file_name=>$from_path)},
4948 "blob" . ($i+1)) .
4949 " | </td>\n";
4950 } else {
4951 if ($diff->{'to_id'} eq $from_hash) {
4952 print "<td class=\"link nochange\">";
4953 } else {
4954 print "<td class=\"link\">";
4955 }
4956 print $cgi->a({-href => href(action=>"blobdiff",
4957 hash=>$diff->{'to_id'},
4958 hash_parent=>$from_hash,
4959 hash_base=>$hash,
4960 hash_parent_base=>$hash_parent,
4961 file_name=>$diff->{'to_file'},
4962 file_parent=>$from_path)},
4963 "diff" . ($i+1)) .
4964 " | </td>\n";
4965 }
4966 }
4967
4968 print "<td class=\"link\">";
4969 if ($not_deleted) {
4970 print $cgi->a({-href => href(action=>"blob",
4971 hash=>$diff->{'to_id'},
4972 file_name=>$diff->{'to_file'},
4973 hash_base=>$hash)},
4974 "blob");
4975 print " | " if ($has_history);
4976 }
4977 if ($has_history) {
4978 print $cgi->a({-href => href(action=>"history",
4979 file_name=>$diff->{'to_file'},
4980 hash_base=>$hash)},
4981 "history");
4982 }
4983 print "</td>\n";
4984
4985 print "</tr>\n";
4986 next; # instead of 'else' clause, to avoid extra indent
4987 }
4988 # else ordinary diff
4989
4990 my ($to_mode_oct, $to_mode_str, $to_file_type);
4991 my ($from_mode_oct, $from_mode_str, $from_file_type);
4992 if ($diff->{'to_mode'} ne ('0' x 6)) {
4993 $to_mode_oct = oct $diff->{'to_mode'};
4994 if (S_ISREG($to_mode_oct)) { # only for regular file
4995 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4996 }
4997 $to_file_type = file_type($diff->{'to_mode'});
4998 }
4999 if ($diff->{'from_mode'} ne ('0' x 6)) {
5000 $from_mode_oct = oct $diff->{'from_mode'};
5001 if (S_ISREG($from_mode_oct)) { # only for regular file
5002 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5003 }
5004 $from_file_type = file_type($diff->{'from_mode'});
5005 }
5006
5007 if ($diff->{'status'} eq "A") { # created
5008 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5009 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5010 $mode_chng .= "]</span>";
5011 print "<td>";
5012 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5013 hash_base=>$hash, file_name=>$diff->{'file'}),
5014 -class => "list"}, esc_path($diff->{'file'}));
5015 print "</td>\n";
5016 print "<td>$mode_chng</td>\n";
5017 print "<td class=\"link\">";
5018 if ($action eq 'commitdiff') {
5019 # link to patch
5020 $patchno++;
5021 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5022 "patch") .
5023 " | ";
5024 }
5025 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5026 hash_base=>$hash, file_name=>$diff->{'file'})},
5027 "blob");
5028 print "</td>\n";
5029
5030 } elsif ($diff->{'status'} eq "D") { # deleted
5031 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5032 print "<td>";
5033 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5034 hash_base=>$parent, file_name=>$diff->{'file'}),
5035 -class => "list"}, esc_path($diff->{'file'}));
5036 print "</td>\n";
5037 print "<td>$mode_chng</td>\n";
5038 print "<td class=\"link\">";
5039 if ($action eq 'commitdiff') {
5040 # link to patch
5041 $patchno++;
5042 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5043 "patch") .
5044 " | ";
5045 }
5046 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5047 hash_base=>$parent, file_name=>$diff->{'file'})},
5048 "blob") . " | ";
5049 if ($have_blame) {
5050 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5051 file_name=>$diff->{'file'})},
5052 "blame") . " | ";
5053 }
5054 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5055 file_name=>$diff->{'file'})},
5056 "history");
5057 print "</td>\n";
5058
5059 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5060 my $mode_chnge = "";
5061 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5062 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5063 if ($from_file_type ne $to_file_type) {
5064 $mode_chnge .= " from $from_file_type to $to_file_type";
5065 }
5066 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5067 if ($from_mode_str && $to_mode_str) {
5068 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5069 } elsif ($to_mode_str) {
5070 $mode_chnge .= " mode: $to_mode_str";
5071 }
5072 }
5073 $mode_chnge .= "]</span>\n";
5074 }
5075 print "<td>";
5076 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5077 hash_base=>$hash, file_name=>$diff->{'file'}),
5078 -class => "list"}, esc_path($diff->{'file'}));
5079 print "</td>\n";
5080 print "<td>$mode_chnge</td>\n";
5081 print "<td class=\"link\">";
5082 if ($action eq 'commitdiff') {
5083 # link to patch
5084 $patchno++;
5085 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5086 "patch") .
5087 " | ";
5088 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5089 # "commit" view and modified file (not onlu mode changed)
5090 print $cgi->a({-href => href(action=>"blobdiff",
5091 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5092 hash_base=>$hash, hash_parent_base=>$parent,
5093 file_name=>$diff->{'file'})},
5094 "diff") .
5095 " | ";
5096 }
5097 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5098 hash_base=>$hash, file_name=>$diff->{'file'})},
5099 "blob") . " | ";
5100 if ($have_blame) {
5101 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5102 file_name=>$diff->{'file'})},
5103 "blame") . " | ";
5104 }
5105 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5106 file_name=>$diff->{'file'})},
5107 "history");
5108 print "</td>\n";
5109
5110 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5111 my %status_name = ('R' => 'moved', 'C' => 'copied');
5112 my $nstatus = $status_name{$diff->{'status'}};
5113 my $mode_chng = "";
5114 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5115 # mode also for directories, so we cannot use $to_mode_str
5116 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5117 }
5118 print "<td>" .
5119 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5120 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5121 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5122 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5123 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5124 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5125 -class => "list"}, esc_path($diff->{'from_file'})) .
5126 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5127 "<td class=\"link\">";
5128 if ($action eq 'commitdiff') {
5129 # link to patch
5130 $patchno++;
5131 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5132 "patch") .
5133 " | ";
5134 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5135 # "commit" view and modified file (not only pure rename or copy)
5136 print $cgi->a({-href => href(action=>"blobdiff",
5137 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5138 hash_base=>$hash, hash_parent_base=>$parent,
5139 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5140 "diff") .
5141 " | ";
5142 }
5143 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5144 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5145 "blob") . " | ";
5146 if ($have_blame) {
5147 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5148 file_name=>$diff->{'to_file'})},
5149 "blame") . " | ";
5150 }
5151 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5152 file_name=>$diff->{'to_file'})},
5153 "history");
5154 print "</td>\n";
5155
5156 } # we should not encounter Unmerged (U) or Unknown (X) status
5157 print "</tr>\n";
5158 }
5159 print "</tbody>" if $has_header;
5160 print "</table>\n";
5161 }
5162
5163 # Print context lines and then rem/add lines in a side-by-side manner.
5164 sub print_sidebyside_diff_lines {
5165 my ($ctx, $rem, $add) = @_;
5166
5167 # print context block before add/rem block
5168 if (@$ctx) {
5169 print join '',
5170 '<div class="chunk_block ctx">',
5171 '<div class="old">',
5172 @$ctx,
5173 '</div>',
5174 '<div class="new">',
5175 @$ctx,
5176 '</div>',
5177 '</div>';
5178 }
5179
5180 if (!@$add) {
5181 # pure removal
5182 print join '',
5183 '<div class="chunk_block rem">',
5184 '<div class="old">',
5185 @$rem,
5186 '</div>',
5187 '</div>';
5188 } elsif (!@$rem) {
5189 # pure addition
5190 print join '',
5191 '<div class="chunk_block add">',
5192 '<div class="new">',
5193 @$add,
5194 '</div>',
5195 '</div>';
5196 } else {
5197 print join '',
5198 '<div class="chunk_block chg">',
5199 '<div class="old">',
5200 @$rem,
5201 '</div>',
5202 '<div class="new">',
5203 @$add,
5204 '</div>',
5205 '</div>';
5206 }
5207 }
5208
5209 # Print context lines and then rem/add lines in inline manner.
5210 sub print_inline_diff_lines {
5211 my ($ctx, $rem, $add) = @_;
5212
5213 print @$ctx, @$rem, @$add;
5214 }
5215
5216 # Format removed and added line, mark changed part and HTML-format them.
5217 # Implementation is based on contrib/diff-highlight
5218 sub format_rem_add_lines_pair {
5219 my ($rem, $add, $num_parents) = @_;
5220
5221 # We need to untabify lines before split()'ing them;
5222 # otherwise offsets would be invalid.
5223 chomp $rem;
5224 chomp $add;
5225 $rem = untabify($rem);
5226 $add = untabify($add);
5227
5228 my @rem = split(//, $rem);
5229 my @add = split(//, $add);
5230 my ($esc_rem, $esc_add);
5231 # Ignore leading +/- characters for each parent.
5232 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5233 my ($prefix_has_nonspace, $suffix_has_nonspace);
5234
5235 my $shorter = (@rem < @add) ? @rem : @add;
5236 while ($prefix_len < $shorter) {
5237 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5238
5239 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5240 $prefix_len++;
5241 }
5242
5243 while ($prefix_len + $suffix_len < $shorter) {
5244 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5245
5246 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5247 $suffix_len++;
5248 }
5249
5250 # Mark lines that are different from each other, but have some common
5251 # part that isn't whitespace. If lines are completely different, don't
5252 # mark them because that would make output unreadable, especially if
5253 # diff consists of multiple lines.
5254 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5255 $esc_rem = esc_html_hl_regions($rem, 'marked',
5256 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5257 $esc_add = esc_html_hl_regions($add, 'marked',
5258 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5259 } else {
5260 $esc_rem = esc_html($rem, -nbsp=>1);
5261 $esc_add = esc_html($add, -nbsp=>1);
5262 }
5263
5264 return format_diff_line(\$esc_rem, 'rem'),
5265 format_diff_line(\$esc_add, 'add');
5266 }
5267
5268 # HTML-format diff context, removed and added lines.
5269 sub format_ctx_rem_add_lines {
5270 my ($ctx, $rem, $add, $num_parents) = @_;
5271 my (@new_ctx, @new_rem, @new_add);
5272 my $can_highlight = 0;
5273 my $is_combined = ($num_parents > 1);
5274
5275 # Highlight if every removed line has a corresponding added line.
5276 if (@$add > 0 && @$add == @$rem) {
5277 $can_highlight = 1;
5278
5279 # Highlight lines in combined diff only if the chunk contains
5280 # diff between the same version, e.g.
5281 #
5282 # - a
5283 # - b
5284 # + c
5285 # + d
5286 #
5287 # Otherwise the highlightling would be confusing.
5288 if ($is_combined) {
5289 for (my $i = 0; $i < @$add; $i++) {
5290 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5291 my $prefix_add = substr($add->[$i], 0, $num_parents);
5292
5293 $prefix_rem =~ s/-/+/g;
5294
5295 if ($prefix_rem ne $prefix_add) {
5296 $can_highlight = 0;
5297 last;
5298 }
5299 }
5300 }
5301 }
5302
5303 if ($can_highlight) {
5304 for (my $i = 0; $i < @$add; $i++) {
5305 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5306 $rem->[$i], $add->[$i], $num_parents);
5307 push @new_rem, $line_rem;
5308 push @new_add, $line_add;
5309 }
5310 } else {
5311 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5312 @new_add = map { format_diff_line($_, 'add') } @$add;
5313 }
5314
5315 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5316
5317 return (\@new_ctx, \@new_rem, \@new_add);
5318 }
5319
5320 # Print context lines and then rem/add lines.
5321 sub print_diff_lines {
5322 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5323 my $is_combined = $num_parents > 1;
5324
5325 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5326 $num_parents);
5327
5328 if ($diff_style eq 'sidebyside' && !$is_combined) {
5329 print_sidebyside_diff_lines($ctx, $rem, $add);
5330 } else {
5331 # default 'inline' style and unknown styles
5332 print_inline_diff_lines($ctx, $rem, $add);
5333 }
5334 }
5335
5336 sub print_diff_chunk {
5337 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5338 my (@ctx, @rem, @add);
5339
5340 # The class of the previous line.
5341 my $prev_class = '';
5342
5343 return unless @chunk;
5344
5345 # incomplete last line might be among removed or added lines,
5346 # or both, or among context lines: find which
5347 for (my $i = 1; $i < @chunk; $i++) {
5348 if ($chunk[$i][0] eq 'incomplete') {
5349 $chunk[$i][0] = $chunk[$i-1][0];
5350 }
5351 }
5352
5353 # guardian
5354 push @chunk, ["", ""];
5355
5356 foreach my $line_info (@chunk) {
5357 my ($class, $line) = @$line_info;
5358
5359 # print chunk headers
5360 if ($class && $class eq 'chunk_header') {
5361 print format_diff_line($line, $class, $from, $to);
5362 next;
5363 }
5364
5365 ## print from accumulator when have some add/rem lines or end
5366 # of chunk (flush context lines), or when have add and rem
5367 # lines and new block is reached (otherwise add/rem lines could
5368 # be reordered)
5369 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5370 (@rem && @add && $class ne $prev_class)) {
5371 print_diff_lines(\@ctx, \@rem, \@add,
5372 $diff_style, $num_parents);
5373 @ctx = @rem = @add = ();
5374 }
5375
5376 ## adding lines to accumulator
5377 # guardian value
5378 last unless $line;
5379 # rem, add or change
5380 if ($class eq 'rem') {
5381 push @rem, $line;
5382 } elsif ($class eq 'add') {
5383 push @add, $line;
5384 }
5385 # context line
5386 if ($class eq 'ctx') {
5387 push @ctx, $line;
5388 }
5389
5390 $prev_class = $class;
5391 }
5392 }
5393
5394 sub git_patchset_body {
5395 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5396 my ($hash_parent) = $hash_parents[0];
5397
5398 my $is_combined = (@hash_parents > 1);
5399 my $patch_idx = 0;
5400 my $patch_number = 0;
5401 my $patch_line;
5402 my $diffinfo;
5403 my $to_name;
5404 my (%from, %to);
5405 my @chunk; # for side-by-side diff
5406
5407 print "<div class=\"patchset\">\n";
5408
5409 # skip to first patch
5410 while ($patch_line = <$fd>) {
5411 chomp $patch_line;
5412
5413 last if ($patch_line =~ m/^diff /);
5414 }
5415
5416 PATCH:
5417 while ($patch_line) {
5418
5419 # parse "git diff" header line
5420 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5421 # $1 is from_name, which we do not use
5422 $to_name = unquote($2);
5423 $to_name =~ s!^b/!!;
5424 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5425 # $1 is 'cc' or 'combined', which we do not use
5426 $to_name = unquote($2);
5427 } else {
5428 $to_name = undef;
5429 }
5430
5431 # check if current patch belong to current raw line
5432 # and parse raw git-diff line if needed
5433 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5434 # this is continuation of a split patch
5435 print "<div class=\"patch cont\">\n";
5436 } else {
5437 # advance raw git-diff output if needed
5438 $patch_idx++ if defined $diffinfo;
5439
5440 # read and prepare patch information
5441 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5442
5443 # compact combined diff output can have some patches skipped
5444 # find which patch (using pathname of result) we are at now;
5445 if ($is_combined) {
5446 while ($to_name ne $diffinfo->{'to_file'}) {
5447 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5448 format_diff_cc_simplified($diffinfo, @hash_parents) .
5449 "</div>\n"; # class="patch"
5450
5451 $patch_idx++;
5452 $patch_number++;
5453
5454 last if $patch_idx > $#$difftree;
5455 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5456 }
5457 }
5458
5459 # modifies %from, %to hashes
5460 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5461
5462 # this is first patch for raw difftree line with $patch_idx index
5463 # we index @$difftree array from 0, but number patches from 1
5464 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5465 }
5466
5467 # git diff header
5468 #assert($patch_line =~ m/^diff /) if DEBUG;
5469 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5470 $patch_number++;
5471 # print "git diff" header
5472 print format_git_diff_header_line($patch_line, $diffinfo,
5473 \%from, \%to);
5474
5475 # print extended diff header
5476 print "<div class=\"diff extended_header\">\n";
5477 EXTENDED_HEADER:
5478 while ($patch_line = <$fd>) {
5479 chomp $patch_line;
5480
5481 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5482
5483 print format_extended_diff_header_line($patch_line, $diffinfo,
5484 \%from, \%to);
5485 }
5486 print "</div>\n"; # class="diff extended_header"
5487
5488 # from-file/to-file diff header
5489 if (! $patch_line) {
5490 print "</div>\n"; # class="patch"
5491 last PATCH;
5492 }
5493 next PATCH if ($patch_line =~ m/^diff /);
5494 #assert($patch_line =~ m/^---/) if DEBUG;
5495
5496 my $last_patch_line = $patch_line;
5497 $patch_line = <$fd>;
5498 chomp $patch_line;
5499 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5500
5501 print format_diff_from_to_header($last_patch_line, $patch_line,
5502 $diffinfo, \%from, \%to,
5503 @hash_parents);
5504
5505 # the patch itself
5506 LINE:
5507 while ($patch_line = <$fd>) {
5508 chomp $patch_line;
5509
5510 next PATCH if ($patch_line =~ m/^diff /);
5511
5512 my $class = diff_line_class($patch_line, \%from, \%to);
5513
5514 if ($class eq 'chunk_header') {
5515 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5516 @chunk = ();
5517 }
5518
5519 push @chunk, [ $class, $patch_line ];
5520 }
5521
5522 } continue {
5523 if (@chunk) {
5524 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5525 @chunk = ();
5526 }
5527 print "</div>\n"; # class="patch"
5528 }
5529
5530 # for compact combined (--cc) format, with chunk and patch simplification
5531 # the patchset might be empty, but there might be unprocessed raw lines
5532 for (++$patch_idx if $patch_number > 0;
5533 $patch_idx < @$difftree;
5534 ++$patch_idx) {
5535 # read and prepare patch information
5536 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5537
5538 # generate anchor for "patch" links in difftree / whatchanged part
5539 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5540 format_diff_cc_simplified($diffinfo, @hash_parents) .
5541 "</div>\n"; # class="patch"
5542
5543 $patch_number++;
5544 }
5545
5546 if ($patch_number == 0) {
5547 if (@hash_parents > 1) {
5548 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5549 } else {
5550 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5551 }
5552 }
5553
5554 print "</div>\n"; # class="patchset"
5555 }
5556
5557 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5558
5559 sub git_project_search_form {
5560 my ($searchtext, $search_use_regexp) = @_;
5561
5562 my $limit = '';
5563 if ($project_filter) {
5564 $limit = " in '$project_filter/'";
5565 }
5566
5567 print "<div class=\"projsearch\">\n";
5568 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5569 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5570 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5571 if (defined $project_filter);
5572 print $cgi->textfield(-name => 's', -value => $searchtext,
5573 -title => "Search project by name and description$limit",
5574 -size => 60) . "\n" .
5575 "<span title=\"Extended regular expression\">" .
5576 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5577 -checked => $search_use_regexp) .
5578 "</span>\n" .
5579 $cgi->submit(-name => 'btnS', -value => 'Search') .
5580 $cgi->end_form() . "\n" .
5581 $cgi->a({-href => href(project => undef, searchtext => undef,
5582 project_filter => $project_filter)},
5583 esc_html("List all projects$limit")) . "<br />\n";
5584 print "</div>\n";
5585 }
5586
5587 # entry for given @keys needs filling if at least one of keys in list
5588 # is not present in %$project_info
5589 sub project_info_needs_filling {
5590 my ($project_info, @keys) = @_;
5591
5592 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5593 foreach my $key (@keys) {
5594 if (!exists $project_info->{$key}) {
5595 return 1;
5596 }
5597 }
5598 return;
5599 }
5600
5601 # fills project list info (age, description, owner, category, forks, etc.)
5602 # for each project in the list, removing invalid projects from
5603 # returned list, or fill only specified info.
5604 #
5605 # Invalid projects are removed from the returned list if and only if you
5606 # ask 'age' or 'age_string' to be filled, because they are the only fields
5607 # that run unconditionally git command that requires repository, and
5608 # therefore do always check if project repository is invalid.
5609 #
5610 # USAGE:
5611 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5612 # ensures that 'descr_long' and 'ctags' fields are filled
5613 # * @project_list = fill_project_list_info(\@project_list)
5614 # ensures that all fields are filled (and invalid projects removed)
5615 #
5616 # NOTE: modifies $projlist, but does not remove entries from it
5617 sub fill_project_list_info {
5618 my ($projlist, @wanted_keys) = @_;
5619 my @projects;
5620 my $filter_set = sub { return @_; };
5621 if (@wanted_keys) {
5622 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5623 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5624 }
5625
5626 my $show_ctags = gitweb_check_feature('ctags');
5627 PROJECT:
5628 foreach my $pr (@$projlist) {
5629 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5630 my (@activity) = git_get_last_activity($pr->{'path'});
5631 unless (@activity) {
5632 next PROJECT;
5633 }
5634 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5635 }
5636 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5637 my $descr = git_get_project_description($pr->{'path'}) || "";
5638 $descr = to_utf8($descr);
5639 $pr->{'descr_long'} = $descr;
5640 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5641 }
5642 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5643 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5644 }
5645 if ($show_ctags &&
5646 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5647 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5648 }
5649 if ($projects_list_group_categories &&
5650 project_info_needs_filling($pr, $filter_set->('category'))) {
5651 my $cat = git_get_project_category($pr->{'path'}) ||
5652 $project_list_default_category;
5653 $pr->{'category'} = to_utf8($cat);
5654 }
5655
5656 push @projects, $pr;
5657 }
5658
5659 return @projects;
5660 }
5661
5662 sub sort_projects_list {
5663 my ($projlist, $order) = @_;
5664
5665 sub order_str {
5666 my $key = shift;
5667 return sub { $a->{$key} cmp $b->{$key} };
5668 }
5669
5670 sub order_num_then_undef {
5671 my $key = shift;
5672 return sub {
5673 defined $a->{$key} ?
5674 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5675 (defined $b->{$key} ? 1 : 0)
5676 };
5677 }
5678
5679 my %orderings = (
5680 project => order_str('path'),
5681 descr => order_str('descr_long'),
5682 owner => order_str('owner'),
5683 age => order_num_then_undef('age'),
5684 );
5685
5686 my $ordering = $orderings{$order};
5687 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5688 }
5689
5690 # returns a hash of categories, containing the list of project
5691 # belonging to each category
5692 sub build_projlist_by_category {
5693 my ($projlist, $from, $to) = @_;
5694 my %categories;
5695
5696 $from = 0 unless defined $from;
5697 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5698
5699 for (my $i = $from; $i <= $to; $i++) {
5700 my $pr = $projlist->[$i];
5701 push @{$categories{ $pr->{'category'} }}, $pr;
5702 }
5703
5704 return wantarray ? %categories : \%categories;
5705 }
5706
5707 # print 'sort by' <th> element, generating 'sort by $name' replay link
5708 # if that order is not selected
5709 sub print_sort_th {
5710 print format_sort_th(@_);
5711 }
5712
5713 sub format_sort_th {
5714 my ($name, $order, $header) = @_;
5715 my $sort_th = "";
5716 $header ||= ucfirst($name);
5717
5718 if ($order eq $name) {
5719 $sort_th .= "<th>$header</th>\n";
5720 } else {
5721 $sort_th .= "<th>" .
5722 $cgi->a({-href => href(-replay=>1, order=>$name),
5723 -class => "header"}, $header) .
5724 "</th>\n";
5725 }
5726
5727 return $sort_th;
5728 }
5729
5730 sub git_project_list_rows {
5731 my ($projlist, $from, $to, $check_forks) = @_;
5732
5733 $from = 0 unless defined $from;
5734 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5735
5736 my $alternate = 1;
5737 for (my $i = $from; $i <= $to; $i++) {
5738 my $pr = $projlist->[$i];
5739
5740 if ($alternate) {
5741 print "<tr class=\"dark\">\n";
5742 } else {
5743 print "<tr class=\"light\">\n";
5744 }
5745 $alternate ^= 1;
5746
5747 if ($check_forks) {
5748 print "<td>";
5749 if ($pr->{'forks'}) {
5750 my $nforks = scalar @{$pr->{'forks'}};
5751 if ($nforks > 0) {
5752 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5753 -title => "$nforks forks"}, "+");
5754 } else {
5755 print $cgi->span({-title => "$nforks forks"}, "+");
5756 }
5757 }
5758 print "</td>\n";
5759 }
5760 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5761 -class => "list"},
5762 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5763 "</td>\n" .
5764 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5765 -class => "list",
5766 -title => $pr->{'descr_long'}},
5767 $search_regexp
5768 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5769 $pr->{'descr'}, $search_regexp)
5770 : esc_html($pr->{'descr'})) .
5771 "</td>\n";
5772 unless ($omit_owner) {
5773 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5774 }
5775 unless ($omit_age_column) {
5776 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5777 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5778 }
5779 print"<td class=\"link\">" .
5780 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5781 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5782 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5783 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5784 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5785 "</td>\n" .
5786 "</tr>\n";
5787 }
5788 }
5789
5790 sub git_project_list_body {
5791 # actually uses global variable $project
5792 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5793 my @projects = @$projlist;
5794
5795 my $check_forks = gitweb_check_feature('forks');
5796 my $show_ctags = gitweb_check_feature('ctags');
5797 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5798 $check_forks = undef
5799 if ($tagfilter || $search_regexp);
5800
5801 # filtering out forks before filling info allows to do less work
5802 @projects = filter_forks_from_projects_list(\@projects)
5803 if ($check_forks);
5804 # search_projects_list pre-fills required info
5805 @projects = search_projects_list(\@projects,
5806 'search_regexp' => $search_regexp,
5807 'tagfilter' => $tagfilter)
5808 if ($tagfilter || $search_regexp);
5809 # fill the rest
5810 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5811 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5812 push @all_fields, 'owner' unless($omit_owner);
5813 @projects = fill_project_list_info(\@projects, @all_fields);
5814
5815 $order ||= $default_projects_order;
5816 $from = 0 unless defined $from;
5817 $to = $#projects if (!defined $to || $#projects < $to);
5818
5819 # short circuit
5820 if ($from > $to) {
5821 print "<center>\n".
5822 "<b>No such projects found</b><br />\n".
5823 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5824 "</center>\n<br />\n";
5825 return;
5826 }
5827
5828 @projects = sort_projects_list(\@projects, $order);
5829
5830 if ($show_ctags) {
5831 my $ctags = git_gather_all_ctags(\@projects);
5832 my $cloud = git_populate_project_tagcloud($ctags);
5833 print git_show_project_tagcloud($cloud, 64);
5834 }
5835
5836 print "<table class=\"project_list\">\n";
5837 unless ($no_header) {
5838 print "<tr>\n";
5839 if ($check_forks) {
5840 print "<th></th>\n";
5841 }
5842 print_sort_th('project', $order, 'Project');
5843 print_sort_th('descr', $order, 'Description');
5844 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5845 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5846 print "<th></th>\n" . # for links
5847 "</tr>\n";
5848 }
5849
5850 if ($projects_list_group_categories) {
5851 # only display categories with projects in the $from-$to window
5852 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5853 my %categories = build_projlist_by_category(\@projects, $from, $to);
5854 foreach my $cat (sort keys %categories) {
5855 unless ($cat eq "") {
5856 print "<tr>\n";
5857 if ($check_forks) {
5858 print "<td></td>\n";
5859 }
5860 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5861 print "</tr>\n";
5862 }
5863
5864 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5865 }
5866 } else {
5867 git_project_list_rows(\@projects, $from, $to, $check_forks);
5868 }
5869
5870 if (defined $extra) {
5871 print "<tr>\n";
5872 if ($check_forks) {
5873 print "<td></td>\n";
5874 }
5875 print "<td colspan=\"5\">$extra</td>\n" .
5876 "</tr>\n";
5877 }
5878 print "</table>\n";
5879 }
5880
5881 sub git_log_body {
5882 # uses global variable $project
5883 my ($commitlist, $from, $to, $refs, $extra) = @_;
5884
5885 $from = 0 unless defined $from;
5886 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5887
5888 for (my $i = 0; $i <= $to; $i++) {
5889 my %co = %{$commitlist->[$i]};
5890 next if !%co;
5891 my $commit = $co{'id'};
5892 my $ref = format_ref_marker($refs, $commit);
5893 git_print_header_div('commit',
5894 "<span class=\"age\">$co{'age_string'}</span>" .
5895 esc_html($co{'title'}) . $ref,
5896 $commit);
5897 print "<div class=\"title_text\">\n" .
5898 "<div class=\"log_link\">\n" .
5899 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5900 " | " .
5901 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5902 " | " .
5903 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5904 "<br/>\n" .
5905 "</div>\n";
5906 git_print_authorship(\%co, -tag => 'span');
5907 print "<br/>\n</div>\n";
5908
5909 print "<div class=\"log_body\">\n";
5910 git_print_log($co{'comment'}, -final_empty_line=> 1);
5911 print "</div>\n";
5912 }
5913 if ($extra) {
5914 print "<div class=\"page_nav\">\n";
5915 print "$extra\n";
5916 print "</div>\n";
5917 }
5918 }
5919
5920 sub git_shortlog_body {
5921 # uses global variable $project
5922 my ($commitlist, $from, $to, $refs, $extra) = @_;
5923
5924 $from = 0 unless defined $from;
5925 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5926
5927 print "<table class=\"shortlog\">\n";
5928 my $alternate = 1;
5929 for (my $i = $from; $i <= $to; $i++) {
5930 my %co = %{$commitlist->[$i]};
5931 my $commit = $co{'id'};
5932 my $ref = format_ref_marker($refs, $commit);
5933 if ($alternate) {
5934 print "<tr class=\"dark\">\n";
5935 } else {
5936 print "<tr class=\"light\">\n";
5937 }
5938 $alternate ^= 1;
5939 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5940 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5941 format_author_html('td', \%co, 10) . "<td>";
5942 print format_subject_html($co{'title'}, $co{'title_short'},
5943 href(action=>"commit", hash=>$commit), $ref);
5944 print "</td>\n" .
5945 "<td class=\"link\">" .
5946 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5947 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5948 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5949 my $snapshot_links = format_snapshot_links($commit);
5950 if (defined $snapshot_links) {
5951 print " | " . $snapshot_links;
5952 }
5953 print "</td>\n" .
5954 "</tr>\n";
5955 }
5956 if (defined $extra) {
5957 print "<tr>\n" .
5958 "<td colspan=\"4\">$extra</td>\n" .
5959 "</tr>\n";
5960 }
5961 print "</table>\n";
5962 }
5963
5964 sub git_history_body {
5965 # Warning: assumes constant type (blob or tree) during history
5966 my ($commitlist, $from, $to, $refs, $extra,
5967 $file_name, $file_hash, $ftype) = @_;
5968
5969 $from = 0 unless defined $from;
5970 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5971
5972 print "<table class=\"history\">\n";
5973 my $alternate = 1;
5974 for (my $i = $from; $i <= $to; $i++) {
5975 my %co = %{$commitlist->[$i]};
5976 if (!%co) {
5977 next;
5978 }
5979 my $commit = $co{'id'};
5980
5981 my $ref = format_ref_marker($refs, $commit);
5982
5983 if ($alternate) {
5984 print "<tr class=\"dark\">\n";
5985 } else {
5986 print "<tr class=\"light\">\n";
5987 }
5988 $alternate ^= 1;
5989 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5990 # shortlog: format_author_html('td', \%co, 10)
5991 format_author_html('td', \%co, 15, 3) . "<td>";
5992 # originally git_history used chop_str($co{'title'}, 50)
5993 print format_subject_html($co{'title'}, $co{'title_short'},
5994 href(action=>"commit", hash=>$commit), $ref);
5995 print "</td>\n" .
5996 "<td class=\"link\">" .
5997 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5998 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5999
6000 if ($ftype eq 'blob') {
6001 print " | " .
6002 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$commit, file_name=>$file_name)}, "raw");
6003
6004 my $blob_current = $file_hash;
6005 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6006 if (defined $blob_current && defined $blob_parent &&
6007 $blob_current ne $blob_parent) {
6008 print " | " .
6009 $cgi->a({-href => href(action=>"blobdiff",
6010 hash=>$blob_current, hash_parent=>$blob_parent,
6011 hash_base=>$hash_base, hash_parent_base=>$commit,
6012 file_name=>$file_name)},
6013 "diff to current");
6014 }
6015 }
6016 print "</td>\n" .
6017 "</tr>\n";
6018 }
6019 if (defined $extra) {
6020 print "<tr>\n" .
6021 "<td colspan=\"4\">$extra</td>\n" .
6022 "</tr>\n";
6023 }
6024 print "</table>\n";
6025 }
6026
6027 sub git_tags_body {
6028 # uses global variable $project
6029 my ($taglist, $from, $to, $extra) = @_;
6030 $from = 0 unless defined $from;
6031 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6032
6033 print "<table class=\"tags\">\n";
6034 my $alternate = 1;
6035 for (my $i = $from; $i <= $to; $i++) {
6036 my $entry = $taglist->[$i];
6037 my %tag = %$entry;
6038 my $comment = $tag{'subject'};
6039 my $comment_short;
6040 if (defined $comment) {
6041 $comment_short = chop_str($comment, 30, 5);
6042 }
6043 if ($alternate) {
6044 print "<tr class=\"dark\">\n";
6045 } else {
6046 print "<tr class=\"light\">\n";
6047 }
6048 $alternate ^= 1;
6049 if (defined $tag{'age'}) {
6050 print "<td><i>$tag{'age'}</i></td>\n";
6051 } else {
6052 print "<td></td>\n";
6053 }
6054 print "<td>" .
6055 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6056 -class => "list name"}, esc_html($tag{'name'})) .
6057 "</td>\n" .
6058 "<td>";
6059 if (defined $comment) {
6060 print format_subject_html($comment, $comment_short,
6061 href(action=>"tag", hash=>$tag{'id'}));
6062 }
6063 print "</td>\n" .
6064 "<td class=\"selflink\">";
6065 if ($tag{'type'} eq "tag") {
6066 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6067 } else {
6068 print "&nbsp;";
6069 }
6070 print "</td>\n" .
6071 "<td class=\"link\">" . " | " .
6072 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6073 if ($tag{'reftype'} eq "commit") {
6074 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6075 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6076 } elsif ($tag{'reftype'} eq "blob") {
6077 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6078 }
6079 print "</td>\n" .
6080 "</tr>";
6081 }
6082 if (defined $extra) {
6083 print "<tr>\n" .
6084 "<td colspan=\"5\">$extra</td>\n" .
6085 "</tr>\n";
6086 }
6087 print "</table>\n";
6088 }
6089
6090 sub git_heads_body {
6091 # uses global variable $project
6092 my ($headlist, $head_at, $from, $to, $extra) = @_;
6093 $from = 0 unless defined $from;
6094 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6095
6096 print "<table class=\"heads\">\n";
6097 my $alternate = 1;
6098 for (my $i = $from; $i <= $to; $i++) {
6099 my $entry = $headlist->[$i];
6100 my %ref = %$entry;
6101 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6102 if ($alternate) {
6103 print "<tr class=\"dark\">\n";
6104 } else {
6105 print "<tr class=\"light\">\n";
6106 }
6107 $alternate ^= 1;
6108 print "<td><i>$ref{'age'}</i></td>\n" .
6109 ($curr ? "<td class=\"current_head\">" : "<td>") .
6110 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6111 -class => "list name"},esc_html($ref{'name'})) .
6112 "</td>\n" .
6113 "<td class=\"link\">" .
6114 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6115 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6116 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6117 "</td>\n" .
6118 "</tr>";
6119 }
6120 if (defined $extra) {
6121 print "<tr>\n" .
6122 "<td colspan=\"3\">$extra</td>\n" .
6123 "</tr>\n";
6124 }
6125 print "</table>\n";
6126 }
6127
6128 # Display a single remote block
6129 sub git_remote_block {
6130 my ($remote, $rdata, $limit, $head) = @_;
6131
6132 my $heads = $rdata->{'heads'};
6133 my $fetch = $rdata->{'fetch'};
6134 my $push = $rdata->{'push'};
6135
6136 my $urls_table = "<table class=\"projects_list\">\n" ;
6137
6138 if (defined $fetch) {
6139 if ($fetch eq $push) {
6140 $urls_table .= format_repo_url("URL", $fetch);
6141 } else {
6142 $urls_table .= format_repo_url("Fetch URL", $fetch);
6143 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6144 }
6145 } elsif (defined $push) {
6146 $urls_table .= format_repo_url("Push URL", $push);
6147 } else {
6148 $urls_table .= format_repo_url("", "No remote URL");
6149 }
6150
6151 $urls_table .= "</table>\n";
6152
6153 my $dots;
6154 if (defined $limit && $limit < @$heads) {
6155 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6156 }
6157
6158 print $urls_table;
6159 git_heads_body($heads, $head, 0, $limit, $dots);
6160 }
6161
6162 # Display a list of remote names with the respective fetch and push URLs
6163 sub git_remotes_list {
6164 my ($remotedata, $limit) = @_;
6165 print "<table class=\"heads\">\n";
6166 my $alternate = 1;
6167 my @remotes = sort keys %$remotedata;
6168
6169 my $limited = $limit && $limit < @remotes;
6170
6171 $#remotes = $limit - 1 if $limited;
6172
6173 while (my $remote = shift @remotes) {
6174 my $rdata = $remotedata->{$remote};
6175 my $fetch = $rdata->{'fetch'};
6176 my $push = $rdata->{'push'};
6177 if ($alternate) {
6178 print "<tr class=\"dark\">\n";
6179 } else {
6180 print "<tr class=\"light\">\n";
6181 }
6182 $alternate ^= 1;
6183 print "<td>" .
6184 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6185 -class=> "list name"},esc_html($remote)) .
6186 "</td>";
6187 print "<td class=\"link\">" .
6188 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6189 " | " .
6190 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6191 "</td>";
6192
6193 print "</tr>\n";
6194 }
6195
6196 if ($limited) {
6197 print "<tr>\n" .
6198 "<td colspan=\"3\">" .
6199 $cgi->a({-href => href(action=>"remotes")}, "...") .
6200 "</td>\n" . "</tr>\n";
6201 }
6202
6203 print "</table>";
6204 }
6205
6206 # Display remote heads grouped by remote, unless there are too many
6207 # remotes, in which case we only display the remote names
6208 sub git_remotes_body {
6209 my ($remotedata, $limit, $head) = @_;
6210 if ($limit and $limit < keys %$remotedata) {
6211 git_remotes_list($remotedata, $limit);
6212 } else {
6213 fill_remote_heads($remotedata);
6214 while (my ($remote, $rdata) = each %$remotedata) {
6215 git_print_section({-class=>"remote", -id=>$remote},
6216 ["remotes", $remote, $remote], sub {
6217 git_remote_block($remote, $rdata, $limit, $head);
6218 });
6219 }
6220 }
6221 }
6222
6223 sub git_search_message {
6224 my %co = @_;
6225
6226 my $greptype;
6227 if ($searchtype eq 'commit') {
6228 $greptype = "--grep=";
6229 } elsif ($searchtype eq 'author') {
6230 $greptype = "--author=";
6231 } elsif ($searchtype eq 'committer') {
6232 $greptype = "--committer=";
6233 }
6234 $greptype .= $searchtext;
6235 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6236 $greptype, '--regexp-ignore-case',
6237 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6238
6239 my $paging_nav = '';
6240 if ($page > 0) {
6241 $paging_nav .=
6242 $cgi->a({-href => href(-replay=>1, page=>undef)},
6243 "first") .
6244 " &sdot; " .
6245 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6246 -accesskey => "p", -title => "Alt-p"}, "prev");
6247 } else {
6248 $paging_nav .= "first &sdot; prev";
6249 }
6250 my $next_link = '';
6251 if ($#commitlist >= 100) {
6252 $next_link =
6253 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6254 -accesskey => "n", -title => "Alt-n"}, "next");
6255 $paging_nav .= " &sdot; $next_link";
6256 } else {
6257 $paging_nav .= " &sdot; next";
6258 }
6259
6260 git_header_html();
6261
6262 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6263 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6264 if ($page == 0 && !@commitlist) {
6265 print "<p>No match.</p>\n";
6266 } else {
6267 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6268 }
6269
6270 git_footer_html();
6271 }
6272
6273 sub git_search_changes {
6274 my %co = @_;
6275
6276 local $/ = "\n";
6277 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6278 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6279 ($search_use_regexp ? '--pickaxe-regex' : ())
6280 or die_error(500, "Open git-log failed");
6281
6282 git_header_html();
6283
6284 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6285 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6286
6287 print "<table class=\"pickaxe search\">\n";
6288 my $alternate = 1;
6289 undef %co;
6290 my @files;
6291 while (my $line = <$fd>) {
6292 chomp $line;
6293 next unless $line;
6294
6295 my %set = parse_difftree_raw_line($line);
6296 if (defined $set{'commit'}) {
6297 # finish previous commit
6298 if (%co) {
6299 print "</td>\n" .
6300 "<td class=\"link\">" .
6301 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6302 "commit") .
6303 " | " .
6304 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6305 hash_base=>$co{'id'})},
6306 "tree") .
6307 "</td>\n" .
6308 "</tr>\n";
6309 }
6310
6311 if ($alternate) {
6312 print "<tr class=\"dark\">\n";
6313 } else {
6314 print "<tr class=\"light\">\n";
6315 }
6316 $alternate ^= 1;
6317 %co = parse_commit($set{'commit'});
6318 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6319 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6320 "<td><i>$author</i></td>\n" .
6321 "<td>" .
6322 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6323 -class => "list subject"},
6324 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6325 } elsif (defined $set{'to_id'}) {
6326 next if is_deleted(\%set);
6327
6328 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6329 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6330 -class => "list"},
6331 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6332 "<br/>\n";
6333 }
6334 }
6335 close $fd;
6336
6337 # finish last commit (warning: repetition!)
6338 if (%co) {
6339 print "</td>\n" .
6340 "<td class=\"link\">" .
6341 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6342 "commit") .
6343 " | " .
6344 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6345 hash_base=>$co{'id'})},
6346 "tree") .
6347 "</td>\n" .
6348 "</tr>\n";
6349 }
6350
6351 print "</table>\n";
6352
6353 git_footer_html();
6354 }
6355
6356 sub git_search_files {
6357 my %co = @_;
6358
6359 local $/ = "\n";
6360 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6361 $search_use_regexp ? ('-E', '-i') : '-F',
6362 $searchtext, $co{'tree'}
6363 or die_error(500, "Open git-grep failed");
6364
6365 git_header_html();
6366
6367 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6368 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6369
6370 print "<table class=\"grep_search\">\n";
6371 my $alternate = 1;
6372 my $matches = 0;
6373 my $lastfile = '';
6374 my $file_href;
6375 while (my $line = <$fd>) {
6376 chomp $line;
6377 my ($file, $lno, $ltext, $binary);
6378 last if ($matches++ > 1000);
6379 if ($line =~ /^Binary file (.+) matches$/) {
6380 $file = $1;
6381 $binary = 1;
6382 } else {
6383 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6384 $file =~ s/^$co{'tree'}://;
6385 }
6386 if ($file ne $lastfile) {
6387 $lastfile and print "</td></tr>\n";
6388 if ($alternate++) {
6389 print "<tr class=\"dark\">\n";
6390 } else {
6391 print "<tr class=\"light\">\n";
6392 }
6393 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6394 file_name=>$file);
6395 print "<td class=\"list\">".
6396 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6397 print "</td><td>\n";
6398 $lastfile = $file;
6399 }
6400 if ($binary) {
6401 print "<div class=\"binary\">Binary file</div>\n";
6402 } else {
6403 $ltext = untabify($ltext);
6404 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6405 $ltext = esc_html($1, -nbsp=>1);
6406 $ltext .= '<span class="match">';
6407 $ltext .= esc_html($2, -nbsp=>1);
6408 $ltext .= '</span>';
6409 $ltext .= esc_html($3, -nbsp=>1);
6410 } else {
6411 $ltext = esc_html($ltext, -nbsp=>1);
6412 }
6413 print "<div class=\"pre\">" .
6414 $cgi->a({-href => $file_href.'#l'.$lno,
6415 -class => "linenr"}, sprintf('%4i', $lno)) .
6416 ' ' . $ltext . "</div>\n";
6417 }
6418 }
6419 if ($lastfile) {
6420 print "</td></tr>\n";
6421 if ($matches > 1000) {
6422 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6423 }
6424 } else {
6425 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6426 }
6427 close $fd;
6428
6429 print "</table>\n";
6430
6431 git_footer_html();
6432 }
6433
6434 sub git_search_grep_body {
6435 my ($commitlist, $from, $to, $extra) = @_;
6436 $from = 0 unless defined $from;
6437 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6438
6439 print "<table class=\"commit_search\">\n";
6440 my $alternate = 1;
6441 for (my $i = $from; $i <= $to; $i++) {
6442 my %co = %{$commitlist->[$i]};
6443 if (!%co) {
6444 next;
6445 }
6446 my $commit = $co{'id'};
6447 if ($alternate) {
6448 print "<tr class=\"dark\">\n";
6449 } else {
6450 print "<tr class=\"light\">\n";
6451 }
6452 $alternate ^= 1;
6453 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6454 format_author_html('td', \%co, 15, 5) .
6455 "<td>" .
6456 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6457 -class => "list subject"},
6458 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6459 my $comment = $co{'comment'};
6460 foreach my $line (@$comment) {
6461 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6462 my ($lead, $match, $trail) = ($1, $2, $3);
6463 $match = chop_str($match, 70, 5, 'center');
6464 my $contextlen = int((80 - length($match))/2);
6465 $contextlen = 30 if ($contextlen > 30);
6466 $lead = chop_str($lead, $contextlen, 10, 'left');
6467 $trail = chop_str($trail, $contextlen, 10, 'right');
6468
6469 $lead = esc_html($lead);
6470 $match = esc_html($match);
6471 $trail = esc_html($trail);
6472
6473 print "$lead<span class=\"match\">$match</span>$trail<br />";
6474 }
6475 }
6476 print "</td>\n" .
6477 "<td class=\"link\">" .
6478 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6479 " | " .
6480 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6481 " | " .
6482 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6483 print "</td>\n" .
6484 "</tr>\n";
6485 }
6486 if (defined $extra) {
6487 print "<tr>\n" .
6488 "<td colspan=\"3\">$extra</td>\n" .
6489 "</tr>\n";
6490 }
6491 print "</table>\n";
6492 }
6493
6494 ## ======================================================================
6495 ## ======================================================================
6496 ## actions
6497
6498 sub git_project_list {
6499 my $order = $input_params{'order'};
6500 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6501 die_error(400, "Unknown order parameter");
6502 }
6503
6504 my @list = git_get_projects_list($project_filter, $strict_export);
6505 if (!@list) {
6506 die_error(404, "No projects found");
6507 }
6508
6509 git_header_html();
6510 if (defined $home_text && -f $home_text) {
6511 print "<div class=\"index_include\">\n";
6512 insert_file($home_text);
6513 print "</div>\n";
6514 }
6515
6516 git_project_search_form($searchtext, $search_use_regexp);
6517 git_project_list_body(\@list, $order);
6518 git_footer_html();
6519 }
6520
6521 sub git_forks {
6522 my $order = $input_params{'order'};
6523 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6524 die_error(400, "Unknown order parameter");
6525 }
6526
6527 my $filter = $project;
6528 $filter =~ s/\.git$//;
6529 my @list = git_get_projects_list($filter);
6530 if (!@list) {
6531 die_error(404, "No forks found");
6532 }
6533
6534 git_header_html();
6535 git_print_page_nav('','');
6536 git_print_header_div('summary', "$project forks");
6537 git_project_list_body(\@list, $order);
6538 git_footer_html();
6539 }
6540
6541 sub git_project_index {
6542 my @projects = git_get_projects_list($project_filter, $strict_export);
6543 if (!@projects) {
6544 die_error(404, "No projects found");
6545 }
6546
6547 print $cgi->header(
6548 -type => 'text/plain',
6549 -charset => 'utf-8',
6550 -content_disposition => 'inline; filename="index.aux"');
6551
6552 foreach my $pr (@projects) {
6553 if (!exists $pr->{'owner'}) {
6554 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6555 }
6556
6557 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6558 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6559 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6560 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6561 $path =~ s/ /\+/g;
6562 $owner =~ s/ /\+/g;
6563
6564 print "$path $owner\n";
6565 }
6566 }
6567
6568 sub git_summary {
6569 my $descr = git_get_project_description($project) || "none";
6570 my %co = parse_commit("HEAD");
6571 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6572 my $head = $co{'id'};
6573 my $remote_heads = gitweb_check_feature('remote_heads');
6574
6575 my $owner = git_get_project_owner($project);
6576
6577 my $refs = git_get_references();
6578 # These get_*_list functions return one more to allow us to see if
6579 # there are more ...
6580 my @taglist = git_get_tags_list(16);
6581 my @headlist = git_get_heads_list(16);
6582 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6583 my @forklist;
6584 my $check_forks = gitweb_check_feature('forks');
6585
6586 if ($check_forks) {
6587 # find forks of a project
6588 my $filter = $project;
6589 $filter =~ s/\.git$//;
6590 @forklist = git_get_projects_list($filter);
6591 # filter out forks of forks
6592 @forklist = filter_forks_from_projects_list(\@forklist)
6593 if (@forklist);
6594 }
6595
6596 git_header_html();
6597 git_print_page_nav('summary','', $head);
6598
6599 print "<div class=\"title\">&nbsp;</div>\n";
6600 print "<table class=\"projects_list\">\n" .
6601 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6602 if ($owner and not $omit_owner) {
6603 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6604 }
6605 if (defined $cd{'rfc2822'}) {
6606 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6607 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6608 }
6609
6610 # use per project git URL list in $projectroot/$project/cloneurl
6611 # or make project git URL from git base URL and project name
6612 my $url_tag = "URL";
6613 my @url_list = git_get_project_url_list($project);
6614 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6615 foreach my $git_url (@url_list) {
6616 next unless $git_url;
6617 print format_repo_url($url_tag, $git_url);
6618 $url_tag = "";
6619 }
6620
6621 # Tag cloud
6622 my $show_ctags = gitweb_check_feature('ctags');
6623 if ($show_ctags) {
6624 my $ctags = git_get_project_ctags($project);
6625 if (%$ctags) {
6626 # without ability to add tags, don't show if there are none
6627 my $cloud = git_populate_project_tagcloud($ctags);
6628 print "<tr id=\"metadata_ctags\">" .
6629 "<td>content tags</td>" .
6630 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6631 "</tr>\n";
6632 }
6633 }
6634
6635 print "</table>\n";
6636
6637 # If XSS prevention is on, we don't include README.html.
6638 # TODO: Allow a readme in some safe format.
6639 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6640 print "<div class=\"title\">readme</div>\n" .
6641 "<div class=\"readme\">\n";
6642 insert_file("$projectroot/$project/README.html");
6643 print "\n</div>\n"; # class="readme"
6644 }
6645
6646 # we need to request one more than 16 (0..15) to check if
6647 # those 16 are all
6648 my @commitlist = $head ? parse_commits($head, 17) : ();
6649 if (@commitlist) {
6650 git_print_header_div('shortlog');
6651 git_shortlog_body(\@commitlist, 0, 15, $refs,
6652 $#commitlist <= 15 ? undef :
6653 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6654 }
6655
6656 if (@taglist) {
6657 git_print_header_div('tags');
6658 git_tags_body(\@taglist, 0, 15,
6659 $#taglist <= 15 ? undef :
6660 $cgi->a({-href => href(action=>"tags")}, "..."));
6661 }
6662
6663 if (@headlist) {
6664 git_print_header_div('heads');
6665 git_heads_body(\@headlist, $head, 0, 15,
6666 $#headlist <= 15 ? undef :
6667 $cgi->a({-href => href(action=>"heads")}, "..."));
6668 }
6669
6670 if (%remotedata) {
6671 git_print_header_div('remotes');
6672 git_remotes_body(\%remotedata, 15, $head);
6673 }
6674
6675 if (@forklist) {
6676 git_print_header_div('forks');
6677 git_project_list_body(\@forklist, 'age', 0, 15,
6678 $#forklist <= 15 ? undef :
6679 $cgi->a({-href => href(action=>"forks")}, "..."),
6680 'no_header');
6681 }
6682
6683 git_footer_html();
6684 }
6685
6686 sub git_tag {
6687 my %tag = parse_tag($hash);
6688
6689 if (! %tag) {
6690 die_error(404, "Unknown tag object");
6691 }
6692
6693 my $head = git_get_head_hash($project);
6694 git_header_html();
6695 git_print_page_nav('','', $head,undef,$head);
6696 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6697 print "<div class=\"title_text\">\n" .
6698 "<table class=\"object_header\">\n" .
6699 "<tr>\n" .
6700 "<td>object</td>\n" .
6701 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6702 $tag{'object'}) . "</td>\n" .
6703 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6704 $tag{'type'}) . "</td>\n" .
6705 "</tr>\n";
6706 if (defined($tag{'author'})) {
6707 git_print_authorship_rows(\%tag, 'author');
6708 }
6709 print "</table>\n\n" .
6710 "</div>\n";
6711 print "<div class=\"page_body\">";
6712 my $comment = $tag{'comment'};
6713 foreach my $line (@$comment) {
6714 chomp $line;
6715 print esc_html($line, -nbsp=>1) . "<br/>\n";
6716 }
6717 print "</div>\n";
6718 git_footer_html();
6719 }
6720
6721 sub git_blame_common {
6722 my $format = shift || 'porcelain';
6723 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6724 $format = 'incremental';
6725 $action = 'blame_incremental'; # for page title etc
6726 }
6727
6728 # permissions
6729 gitweb_check_feature('blame')
6730 or die_error(403, "Blame view not allowed");
6731
6732 # error checking
6733 die_error(400, "No file name given") unless $file_name;
6734 $hash_base ||= git_get_head_hash($project);
6735 die_error(404, "Couldn't find base commit") unless $hash_base;
6736 my %co = parse_commit($hash_base)
6737 or die_error(404, "Commit not found");
6738 my $ftype = "blob";
6739 if (!defined $hash) {
6740 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6741 or die_error(404, "Error looking up file");
6742 } else {
6743 $ftype = git_get_type($hash);
6744 if ($ftype !~ "blob") {
6745 die_error(400, "Object is not a blob");
6746 }
6747 }
6748
6749 my $fd;
6750 if ($format eq 'incremental') {
6751 # get file contents (as base)
6752 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6753 or die_error(500, "Open git-cat-file failed");
6754 } elsif ($format eq 'data') {
6755 # run git-blame --incremental
6756 open $fd, "-|", git_cmd(), "blame", "--incremental",
6757 $hash_base, "--", $file_name
6758 or die_error(500, "Open git-blame --incremental failed");
6759 } else {
6760 # run git-blame --porcelain
6761 open $fd, "-|", git_cmd(), "blame", '-p',
6762 $hash_base, '--', $file_name
6763 or die_error(500, "Open git-blame --porcelain failed");
6764 }
6765 binmode $fd, ':utf8';
6766
6767 # incremental blame data returns early
6768 if ($format eq 'data') {
6769 print $cgi->header(
6770 -type=>"text/plain", -charset => "utf-8",
6771 -status=> "200 OK");
6772 local $| = 1; # output autoflush
6773 while (my $line = <$fd>) {
6774 print to_utf8($line);
6775 }
6776 close $fd
6777 or print "ERROR $!\n";
6778
6779 print 'END';
6780 if (defined $t0 && gitweb_check_feature('timed')) {
6781 print ' '.
6782 tv_interval($t0, [ gettimeofday() ]).
6783 ' '.$number_of_git_cmds;
6784 }
6785 print "\n";
6786
6787 return;
6788 }
6789
6790 # page header
6791 git_header_html();
6792 my $formats_nav =
6793 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6794 "blob") .
6795 " | ";
6796 if ($format eq 'incremental') {
6797 $formats_nav .=
6798 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6799 "blame") . " (non-incremental)";
6800 } else {
6801 $formats_nav .=
6802 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6803 "blame") . " (incremental)";
6804 }
6805 $formats_nav .=
6806 " | " .
6807 $cgi->a({-href => href(action=>"history", -replay=>1)},
6808 "history") .
6809 " | " .
6810 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6811 "HEAD");
6812 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6813 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6814 git_print_page_path($file_name, $ftype, $hash_base);
6815
6816 # page body
6817 if ($format eq 'incremental') {
6818 print "<noscript>\n<div class=\"error\"><center><b>\n".
6819 "This page requires JavaScript to run.\n Use ".
6820 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6821 'this page').
6822 " instead.\n".
6823 "</b></center></div>\n</noscript>\n";
6824
6825 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6826 }
6827
6828 print qq!<div class="page_body">\n!;
6829 print qq!<div id="progress_info">... / ...</div>\n!
6830 if ($format eq 'incremental');
6831 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6832 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6833 qq!<thead>\n!.
6834 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6835 qq!</thead>\n!.
6836 qq!<tbody>\n!;
6837
6838 my @rev_color = qw(light dark);
6839 my $num_colors = scalar(@rev_color);
6840 my $current_color = 0;
6841
6842 if ($format eq 'incremental') {
6843 my $color_class = $rev_color[$current_color];
6844
6845 #contents of a file
6846 my $linenr = 0;
6847 LINE:
6848 while (my $line = <$fd>) {
6849 chomp $line;
6850 $linenr++;
6851
6852 print qq!<tr id="l$linenr" class="$color_class">!.
6853 qq!<td class="sha1"><a href=""> </a></td>!.
6854 qq!<td class="linenr">!.
6855 qq!<a class="linenr" href="">$linenr</a></td>!;
6856 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6857 print qq!</tr>\n!;
6858 }
6859
6860 } else { # porcelain, i.e. ordinary blame
6861 my %metainfo = (); # saves information about commits
6862
6863 # blame data
6864 LINE:
6865 while (my $line = <$fd>) {
6866 chomp $line;
6867 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6868 # no <lines in group> for subsequent lines in group of lines
6869 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6870 ($line =~ /^($oid_regex) (\d+) (\d+)(?: (\d+))?$/);
6871 if (!exists $metainfo{$full_rev}) {
6872 $metainfo{$full_rev} = { 'nprevious' => 0 };
6873 }
6874 my $meta = $metainfo{$full_rev};
6875 my $data;
6876 while ($data = <$fd>) {
6877 chomp $data;
6878 last if ($data =~ s/^\t//); # contents of line
6879 if ($data =~ /^(\S+)(?: (.*))?$/) {
6880 $meta->{$1} = $2 unless exists $meta->{$1};
6881 }
6882 if ($data =~ /^previous /) {
6883 $meta->{'nprevious'}++;
6884 }
6885 }
6886 my $short_rev = substr($full_rev, 0, 8);
6887 my $author = $meta->{'author'};
6888 my %date =
6889 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6890 my $date = $date{'iso-tz'};
6891 if ($group_size) {
6892 $current_color = ($current_color + 1) % $num_colors;
6893 }
6894 my $tr_class = $rev_color[$current_color];
6895 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6896 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6897 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6898 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6899 if ($group_size) {
6900 print "<td class=\"sha1\"";
6901 print " title=\"". esc_html($author) . ", $date\"";
6902 print " rowspan=\"$group_size\"" if ($group_size > 1);
6903 print ">";
6904 print $cgi->a({-href => href(action=>"commit",
6905 hash=>$full_rev,
6906 file_name=>$file_name)},
6907 esc_html($short_rev));
6908 if ($group_size >= 2) {
6909 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6910 if (@author_initials) {
6911 print "<br />" .
6912 esc_html(join('', @author_initials));
6913 # or join('.', ...)
6914 }
6915 }
6916 print "</td>\n";
6917 }
6918 # 'previous' <sha1 of parent commit> <filename at commit>
6919 if (exists $meta->{'previous'} &&
6920 $meta->{'previous'} =~ /^($oid_regex) (.*)$/) {
6921 $meta->{'parent'} = $1;
6922 $meta->{'file_parent'} = unquote($2);
6923 }
6924 my $linenr_commit =
6925 exists($meta->{'parent'}) ?
6926 $meta->{'parent'} : $full_rev;
6927 my $linenr_filename =
6928 exists($meta->{'file_parent'}) ?
6929 $meta->{'file_parent'} : unquote($meta->{'filename'});
6930 my $blamed = href(action => 'blame',
6931 file_name => $linenr_filename,
6932 hash_base => $linenr_commit);
6933 print "<td class=\"linenr\">";
6934 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6935 -class => "linenr" },
6936 esc_html($lineno));
6937 print "</td>";
6938 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6939 print "</tr>\n";
6940 } # end while
6941
6942 }
6943
6944 # footer
6945 print "</tbody>\n".
6946 "</table>\n"; # class="blame"
6947 print "</div>\n"; # class="blame_body"
6948 close $fd
6949 or print "Reading blob failed\n";
6950
6951 git_footer_html();
6952 }
6953
6954 sub git_blame {
6955 git_blame_common();
6956 }
6957
6958 sub git_blame_incremental {
6959 git_blame_common('incremental');
6960 }
6961
6962 sub git_blame_data {
6963 git_blame_common('data');
6964 }
6965
6966 sub git_tags {
6967 my $head = git_get_head_hash($project);
6968 git_header_html();
6969 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6970 git_print_header_div('summary', $project);
6971
6972 my @tagslist = git_get_tags_list();
6973 if (@tagslist) {
6974 git_tags_body(\@tagslist);
6975 }
6976 git_footer_html();
6977 }
6978
6979 sub git_heads {
6980 my $head = git_get_head_hash($project);
6981 git_header_html();
6982 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6983 git_print_header_div('summary', $project);
6984
6985 my @headslist = git_get_heads_list();
6986 if (@headslist) {
6987 git_heads_body(\@headslist, $head);
6988 }
6989 git_footer_html();
6990 }
6991
6992 # used both for single remote view and for list of all the remotes
6993 sub git_remotes {
6994 gitweb_check_feature('remote_heads')
6995 or die_error(403, "Remote heads view is disabled");
6996
6997 my $head = git_get_head_hash($project);
6998 my $remote = $input_params{'hash'};
6999
7000 my $remotedata = git_get_remotes_list($remote);
7001 die_error(500, "Unable to get remote information") unless defined $remotedata;
7002
7003 unless (%$remotedata) {
7004 die_error(404, defined $remote ?
7005 "Remote $remote not found" :
7006 "No remotes found");
7007 }
7008
7009 git_header_html(undef, undef, -action_extra => $remote);
7010 git_print_page_nav('', '', $head, undef, $head,
7011 format_ref_views($remote ? '' : 'remotes'));
7012
7013 fill_remote_heads($remotedata);
7014 if (defined $remote) {
7015 git_print_header_div('remotes', "$remote remote for $project");
7016 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7017 } else {
7018 git_print_header_div('summary', "$project remotes");
7019 git_remotes_body($remotedata, undef, $head);
7020 }
7021
7022 git_footer_html();
7023 }
7024
7025 sub git_blob_plain {
7026 my $type = shift;
7027 my $expires;
7028
7029 if (!defined $hash) {
7030 if (defined $file_name) {
7031 my $base = $hash_base || git_get_head_hash($project);
7032 $hash = git_get_hash_by_path($base, $file_name, "blob")
7033 or die_error(404, "Cannot find file");
7034 } else {
7035 die_error(400, "No file name defined");
7036 }
7037 } elsif ($hash =~ m/^$oid_regex$/) {
7038 # blobs defined by non-textual hash id's can be cached
7039 $expires = "+1d";
7040 }
7041
7042 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7043 or die_error(500, "Open git-cat-file blob '$hash' failed");
7044
7045 # content-type (can include charset)
7046 $type = blob_contenttype($fd, $file_name, $type);
7047
7048 # "save as" filename, even when no $file_name is given
7049 my $save_as = "$hash";
7050 if (defined $file_name) {
7051 $save_as = $file_name;
7052 } elsif ($type =~ m/^text\//) {
7053 $save_as .= '.txt';
7054 }
7055
7056 # With XSS prevention on, blobs of all types except a few known safe
7057 # ones are served with "Content-Disposition: attachment" to make sure
7058 # they don't run in our security domain. For certain image types,
7059 # blob view writes an <img> tag referring to blob_plain view, and we
7060 # want to be sure not to break that by serving the image as an
7061 # attachment (though Firefox 3 doesn't seem to care).
7062 my $sandbox = $prevent_xss &&
7063 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7064
7065 # serve text/* as text/plain
7066 if ($prevent_xss &&
7067 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7068 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7069 my $rest = $1;
7070 $rest = defined $rest ? $rest : '';
7071 $type = "text/plain$rest";
7072 }
7073
7074 print $cgi->header(
7075 -type => $type,
7076 -expires => $expires,
7077 -content_disposition =>
7078 ($sandbox ? 'attachment' : 'inline')
7079 . '; filename="' . $save_as . '"');
7080 local $/ = undef;
7081 binmode STDOUT, ':raw';
7082 print <$fd>;
7083 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7084 close $fd;
7085 }
7086
7087 sub git_blob {
7088 my $expires;
7089
7090 if (!defined $hash) {
7091 if (defined $file_name) {
7092 my $base = $hash_base || git_get_head_hash($project);
7093 $hash = git_get_hash_by_path($base, $file_name, "blob")
7094 or die_error(404, "Cannot find file");
7095 } else {
7096 die_error(400, "No file name defined");
7097 }
7098 } elsif ($hash =~ m/^$oid_regex$/) {
7099 # blobs defined by non-textual hash id's can be cached
7100 $expires = "+1d";
7101 }
7102
7103 my $have_blame = gitweb_check_feature('blame');
7104 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7105 or die_error(500, "Couldn't cat $file_name, $hash");
7106 my $mimetype = blob_mimetype($fd, $file_name);
7107 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7108 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7109 close $fd;
7110 return git_blob_plain($mimetype);
7111 }
7112 # we can have blame only for text/* mimetype
7113 $have_blame &&= ($mimetype =~ m!^text/!);
7114
7115 my $highlight = gitweb_check_feature('highlight');
7116 my $syntax = guess_file_syntax($highlight, $file_name);
7117 $fd = run_highlighter($fd, $highlight, $syntax);
7118
7119 git_header_html(undef, $expires);
7120 my $formats_nav = '';
7121 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7122 if (defined $file_name) {
7123 if ($have_blame) {
7124 $formats_nav .=
7125 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7126 "blame") .
7127 " | ";
7128 }
7129 $formats_nav .=
7130 $cgi->a({-href => href(action=>"history", -replay=>1)},
7131 "history") .
7132 " | " .
7133 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7134 "raw") .
7135 " | " .
7136 $cgi->a({-href => href(action=>"blob",
7137 hash_base=>"HEAD", file_name=>$file_name)},
7138 "HEAD");
7139 } else {
7140 $formats_nav .=
7141 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7142 "raw");
7143 }
7144 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7145 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7146 } else {
7147 print "<div class=\"page_nav\">\n" .
7148 "<br/><br/></div>\n" .
7149 "<div class=\"title\">".esc_html($hash)."</div>\n";
7150 }
7151 git_print_page_path($file_name, "blob", $hash_base);
7152 print "<div class=\"page_body\">\n";
7153 if ($mimetype =~ m!^image/!) {
7154 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7155 if ($file_name) {
7156 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7157 }
7158 print qq! src="! .
7159 href(action=>"blob_plain", hash=>$hash,
7160 hash_base=>$hash_base, file_name=>$file_name) .
7161 qq!" />\n!;
7162 } else {
7163 my $nr;
7164 while (my $line = <$fd>) {
7165 chomp $line;
7166 $nr++;
7167 $line = untabify($line);
7168 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7169 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7170 $highlight ? sanitize($line) : esc_html($line, -nbsp=>1);
7171 }
7172 }
7173 close $fd
7174 or print "Reading blob failed.\n";
7175 print "</div>";
7176 git_footer_html();
7177 }
7178
7179 sub git_tree {
7180 if (!defined $hash_base) {
7181 $hash_base = "HEAD";
7182 }
7183 if (!defined $hash) {
7184 if (defined $file_name) {
7185 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7186 } else {
7187 $hash = $hash_base;
7188 }
7189 }
7190 die_error(404, "No such tree") unless defined($hash);
7191
7192 my $show_sizes = gitweb_check_feature('show-sizes');
7193 my $have_blame = gitweb_check_feature('blame');
7194
7195 my @entries = ();
7196 {
7197 local $/ = "\0";
7198 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7199 ($show_sizes ? '-l' : ()), @extra_options, $hash
7200 or die_error(500, "Open git-ls-tree failed");
7201 @entries = map { chomp; $_ } <$fd>;
7202 close $fd
7203 or die_error(404, "Reading tree failed");
7204 }
7205
7206 my $refs = git_get_references();
7207 my $ref = format_ref_marker($refs, $hash_base);
7208 git_header_html();
7209 my $basedir = '';
7210 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7211 my @views_nav = ();
7212 if (defined $file_name) {
7213 push @views_nav,
7214 $cgi->a({-href => href(action=>"history", -replay=>1)},
7215 "history"),
7216 $cgi->a({-href => href(action=>"tree",
7217 hash_base=>"HEAD", file_name=>$file_name)},
7218 "HEAD"),
7219 }
7220 my $snapshot_links = format_snapshot_links($hash);
7221 if (defined $snapshot_links) {
7222 # FIXME: Should be available when we have no hash base as well.
7223 push @views_nav, $snapshot_links;
7224 }
7225 git_print_page_nav('tree','', $hash_base, undef, undef,
7226 join(' | ', @views_nav));
7227 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7228 } else {
7229 undef $hash_base;
7230 print "<div class=\"page_nav\">\n";
7231 print "<br/><br/></div>\n";
7232 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7233 }
7234 if (defined $file_name) {
7235 $basedir = $file_name;
7236 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7237 $basedir .= '/';
7238 }
7239 git_print_page_path($file_name, 'tree', $hash_base);
7240 }
7241 print "<div class=\"page_body\">\n";
7242 print "<table class=\"tree\">\n";
7243 my $alternate = 1;
7244 # '..' (top directory) link if possible
7245 if (defined $hash_base &&
7246 defined $file_name && $file_name =~ m![^/]+$!) {
7247 if ($alternate) {
7248 print "<tr class=\"dark\">\n";
7249 } else {
7250 print "<tr class=\"light\">\n";
7251 }
7252 $alternate ^= 1;
7253
7254 my $up = $file_name;
7255 $up =~ s!/?[^/]+$!!;
7256 undef $up unless $up;
7257 # based on git_print_tree_entry
7258 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7259 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7260 print '<td class="list">';
7261 print $cgi->a({-href => href(action=>"tree",
7262 hash_base=>$hash_base,
7263 file_name=>$up)},
7264 "..");
7265 print "</td>\n";
7266 print "<td class=\"link\"></td>\n";
7267
7268 print "</tr>\n";
7269 }
7270 foreach my $line (@entries) {
7271 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7272
7273 if ($alternate) {
7274 print "<tr class=\"dark\">\n";
7275 } else {
7276 print "<tr class=\"light\">\n";
7277 }
7278 $alternate ^= 1;
7279
7280 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7281
7282 print "</tr>\n";
7283 }
7284 print "</table>\n" .
7285 "</div>";
7286 git_footer_html();
7287 }
7288
7289 sub sanitize_for_filename {
7290 my $name = shift;
7291
7292 $name =~ s!/!-!g;
7293 $name =~ s/[^[:alnum:]_.-]//g;
7294
7295 return $name;
7296 }
7297
7298 sub snapshot_name {
7299 my ($project, $hash) = @_;
7300
7301 # path/to/project.git -> project
7302 # path/to/project/.git -> project
7303 my $name = to_utf8($project);
7304 $name =~ s,([^/])/*\.git$,$1,;
7305 $name = sanitize_for_filename(basename($name));
7306
7307 my $ver = $hash;
7308 if ($hash =~ /^[0-9a-fA-F]+$/) {
7309 # shorten SHA-1 hash
7310 my $full_hash = git_get_full_hash($project, $hash);
7311 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7312 $ver = git_get_short_hash($project, $hash);
7313 }
7314 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7315 # tags don't need shortened SHA-1 hash
7316 $ver = $1;
7317 } else {
7318 # branches and other need shortened SHA-1 hash
7319 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7320 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7321 my $ref_dir = (defined $1) ? $1 : '';
7322 $ver = $2;
7323
7324 $ref_dir = sanitize_for_filename($ref_dir);
7325 # for refs neither in heads nor remotes we want to
7326 # add a ref dir to archive name
7327 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7328 $ver = $ref_dir . '-' . $ver;
7329 }
7330 }
7331 $ver .= '-' . git_get_short_hash($project, $hash);
7332 }
7333 # special case of sanitization for filename - we change
7334 # slashes to dots instead of dashes
7335 # in case of hierarchical branch names
7336 $ver =~ s!/!.!g;
7337 $ver =~ s/[^[:alnum:]_.-]//g;
7338
7339 # name = project-version_string
7340 $name = "$name-$ver";
7341
7342 return wantarray ? ($name, $name) : $name;
7343 }
7344
7345 sub exit_if_unmodified_since {
7346 my ($latest_epoch) = @_;
7347 our $cgi;
7348
7349 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7350 if (defined $if_modified) {
7351 my $since;
7352 if (eval { require HTTP::Date; 1; }) {
7353 $since = HTTP::Date::str2time($if_modified);
7354 } elsif (eval { require Time::ParseDate; 1; }) {
7355 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7356 }
7357 if (defined $since && $latest_epoch <= $since) {
7358 my %latest_date = parse_date($latest_epoch);
7359 print $cgi->header(
7360 -last_modified => $latest_date{'rfc2822'},
7361 -status => '304 Not Modified');
7362 goto DONE_GITWEB;
7363 }
7364 }
7365 }
7366
7367 sub git_snapshot {
7368 my $format = $input_params{'snapshot_format'};
7369 if (!@snapshot_fmts) {
7370 die_error(403, "Snapshots not allowed");
7371 }
7372 # default to first supported snapshot format
7373 $format ||= $snapshot_fmts[0];
7374 if ($format !~ m/^[a-z0-9]+$/) {
7375 die_error(400, "Invalid snapshot format parameter");
7376 } elsif (!exists($known_snapshot_formats{$format})) {
7377 die_error(400, "Unknown snapshot format");
7378 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7379 die_error(403, "Snapshot format not allowed");
7380 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7381 die_error(403, "Unsupported snapshot format");
7382 }
7383
7384 my $type = git_get_type("$hash^{}");
7385 if (!$type) {
7386 die_error(404, 'Object does not exist');
7387 } elsif ($type eq 'blob') {
7388 die_error(400, 'Object is not a tree-ish');
7389 }
7390
7391 my ($name, $prefix) = snapshot_name($project, $hash);
7392 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7393
7394 my %co = parse_commit($hash);
7395 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7396
7397 my $cmd = quote_command(
7398 git_cmd(), 'archive',
7399 "--format=$known_snapshot_formats{$format}{'format'}",
7400 "--prefix=$prefix/", $hash);
7401 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7402 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7403 }
7404
7405 $filename =~ s/(["\\])/\\$1/g;
7406 my %latest_date;
7407 if (%co) {
7408 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7409 }
7410
7411 print $cgi->header(
7412 -type => $known_snapshot_formats{$format}{'type'},
7413 -content_disposition => 'inline; filename="' . $filename . '"',
7414 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7415 -status => '200 OK');
7416
7417 open my $fd, "-|", $cmd
7418 or die_error(500, "Execute git-archive failed");
7419 binmode STDOUT, ':raw';
7420 print <$fd>;
7421 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7422 close $fd;
7423 }
7424
7425 sub git_log_generic {
7426 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7427
7428 my $head = git_get_head_hash($project);
7429 if (!defined $base) {
7430 $base = $head;
7431 }
7432 if (!defined $page) {
7433 $page = 0;
7434 }
7435 my $refs = git_get_references();
7436
7437 my $commit_hash = $base;
7438 if (defined $parent) {
7439 $commit_hash = "$parent..$base";
7440 }
7441 my @commitlist =
7442 parse_commits($commit_hash, 101, (100 * $page),
7443 defined $file_name ? ($file_name, "--full-history") : ());
7444
7445 my $ftype;
7446 if (!defined $file_hash && defined $file_name) {
7447 # some commits could have deleted file in question,
7448 # and not have it in tree, but one of them has to have it
7449 for (my $i = 0; $i < @commitlist; $i++) {
7450 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7451 last if defined $file_hash;
7452 }
7453 }
7454 if (defined $file_hash) {
7455 $ftype = git_get_type($file_hash);
7456 }
7457 if (defined $file_name && !defined $ftype) {
7458 die_error(500, "Unknown type of object");
7459 }
7460 my %co;
7461 if (defined $file_name) {
7462 %co = parse_commit($base)
7463 or die_error(404, "Unknown commit object");
7464 }
7465
7466
7467 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7468 my $next_link = '';
7469 if ($#commitlist >= 100) {
7470 $next_link =
7471 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7472 -accesskey => "n", -title => "Alt-n"}, "next");
7473 }
7474 my $patch_max = gitweb_get_feature('patches');
7475 if ($patch_max && !defined $file_name) {
7476 if ($patch_max < 0 || @commitlist <= $patch_max) {
7477 $paging_nav .= " &sdot; " .
7478 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7479 "patches");
7480 }
7481 }
7482
7483 git_header_html();
7484 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7485 if (defined $file_name) {
7486 git_print_header_div('commit', esc_html($co{'title'}), $base);
7487 } else {
7488 git_print_header_div('summary', $project)
7489 }
7490 git_print_page_path($file_name, $ftype, $hash_base)
7491 if (defined $file_name);
7492
7493 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7494 $file_name, $file_hash, $ftype);
7495
7496 git_footer_html();
7497 }
7498
7499 sub git_log {
7500 git_log_generic('log', \&git_log_body,
7501 $hash, $hash_parent);
7502 }
7503
7504 sub git_commit {
7505 $hash ||= $hash_base || "HEAD";
7506 my %co = parse_commit($hash)
7507 or die_error(404, "Unknown commit object");
7508
7509 my $parent = $co{'parent'};
7510 my $parents = $co{'parents'}; # listref
7511
7512 # we need to prepare $formats_nav before any parameter munging
7513 my $formats_nav;
7514 if (!defined $parent) {
7515 # --root commitdiff
7516 $formats_nav .= '(initial)';
7517 } elsif (@$parents == 1) {
7518 # single parent commit
7519 $formats_nav .=
7520 '(parent: ' .
7521 $cgi->a({-href => href(action=>"commit",
7522 hash=>$parent)},
7523 esc_html(substr($parent, 0, 7))) .
7524 ')';
7525 } else {
7526 # merge commit
7527 $formats_nav .=
7528 '(merge: ' .
7529 join(' ', map {
7530 $cgi->a({-href => href(action=>"commit",
7531 hash=>$_)},
7532 esc_html(substr($_, 0, 7)));
7533 } @$parents ) .
7534 ')';
7535 }
7536 if (gitweb_check_feature('patches') && @$parents <= 1) {
7537 $formats_nav .= " | " .
7538 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7539 "patch");
7540 }
7541
7542 if (!defined $parent) {
7543 $parent = "--root";
7544 }
7545 my @difftree;
7546 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7547 @diff_opts,
7548 (@$parents <= 1 ? $parent : '-c'),
7549 $hash, "--"
7550 or die_error(500, "Open git-diff-tree failed");
7551 @difftree = map { chomp; $_ } <$fd>;
7552 close $fd or die_error(404, "Reading git-diff-tree failed");
7553
7554 # non-textual hash id's can be cached
7555 my $expires;
7556 if ($hash =~ m/^$oid_regex$/) {
7557 $expires = "+1d";
7558 }
7559 my $refs = git_get_references();
7560 my $ref = format_ref_marker($refs, $co{'id'});
7561
7562 git_header_html(undef, $expires);
7563 git_print_page_nav('commit', '',
7564 $hash, $co{'tree'}, $hash,
7565 $formats_nav);
7566
7567 if (defined $co{'parent'}) {
7568 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7569 } else {
7570 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7571 }
7572 print "<div class=\"title_text\">\n" .
7573 "<table class=\"object_header\">\n";
7574 git_print_authorship_rows(\%co);
7575 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7576 print "<tr>" .
7577 "<td>tree</td>" .
7578 "<td class=\"sha1\">" .
7579 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7580 class => "list"}, $co{'tree'}) .
7581 "</td>" .
7582 "<td class=\"link\">" .
7583 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7584 "tree");
7585 my $snapshot_links = format_snapshot_links($hash);
7586 if (defined $snapshot_links) {
7587 print " | " . $snapshot_links;
7588 }
7589 print "</td>" .
7590 "</tr>\n";
7591
7592 foreach my $par (@$parents) {
7593 print "<tr>" .
7594 "<td>parent</td>" .
7595 "<td class=\"sha1\">" .
7596 $cgi->a({-href => href(action=>"commit", hash=>$par),
7597 class => "list"}, $par) .
7598 "</td>" .
7599 "<td class=\"link\">" .
7600 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7601 " | " .
7602 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7603 "</td>" .
7604 "</tr>\n";
7605 }
7606 print "</table>".
7607 "</div>\n";
7608
7609 print "<div class=\"page_body\">\n";
7610 git_print_log($co{'comment'});
7611 print "</div>\n";
7612
7613 git_difftree_body(\@difftree, $hash, @$parents);
7614
7615 git_footer_html();
7616 }
7617
7618 sub git_object {
7619 # object is defined by:
7620 # - hash or hash_base alone
7621 # - hash_base and file_name
7622 my $type;
7623
7624 # - hash or hash_base alone
7625 if ($hash || ($hash_base && !defined $file_name)) {
7626 my $object_id = $hash || $hash_base;
7627
7628 open my $fd, "-|", quote_command(
7629 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7630 or die_error(404, "Object does not exist");
7631 $type = <$fd>;
7632 defined $type && chomp $type;
7633 close $fd
7634 or die_error(404, "Object does not exist");
7635
7636 # - hash_base and file_name
7637 } elsif ($hash_base && defined $file_name) {
7638 $file_name =~ s,/+$,,;
7639
7640 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7641 or die_error(404, "Base object does not exist");
7642
7643 # here errors should not happen
7644 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7645 or die_error(500, "Open git-ls-tree failed");
7646 my $line = <$fd>;
7647 close $fd;
7648
7649 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7650 unless ($line && $line =~ m/^([0-9]+) (.+) ($oid_regex)\t/) {
7651 die_error(404, "File or directory for given base does not exist");
7652 }
7653 $type = $2;
7654 $hash = $3;
7655 } else {
7656 die_error(400, "Not enough information to find object");
7657 }
7658
7659 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7660 hash=>$hash, hash_base=>$hash_base,
7661 file_name=>$file_name),
7662 -status => '302 Found');
7663 }
7664
7665 sub git_blobdiff {
7666 my $format = shift || 'html';
7667 my $diff_style = $input_params{'diff_style'} || 'inline';
7668
7669 my $fd;
7670 my @difftree;
7671 my %diffinfo;
7672 my $expires;
7673
7674 # preparing $fd and %diffinfo for git_patchset_body
7675 # new style URI
7676 if (defined $hash_base && defined $hash_parent_base) {
7677 if (defined $file_name) {
7678 # read raw output
7679 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7680 $hash_parent_base, $hash_base,
7681 "--", (defined $file_parent ? $file_parent : ()), $file_name
7682 or die_error(500, "Open git-diff-tree failed");
7683 @difftree = map { chomp; $_ } <$fd>;
7684 close $fd
7685 or die_error(404, "Reading git-diff-tree failed");
7686 @difftree
7687 or die_error(404, "Blob diff not found");
7688
7689 } elsif (defined $hash &&
7690 $hash =~ $oid_regex) {
7691 # try to find filename from $hash
7692
7693 # read filtered raw output
7694 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7695 $hash_parent_base, $hash_base, "--"
7696 or die_error(500, "Open git-diff-tree failed");
7697 @difftree =
7698 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7699 # $hash == to_id
7700 grep { /^:[0-7]{6} [0-7]{6} $oid_regex $hash/ }
7701 map { chomp; $_ } <$fd>;
7702 close $fd
7703 or die_error(404, "Reading git-diff-tree failed");
7704 @difftree
7705 or die_error(404, "Blob diff not found");
7706
7707 } else {
7708 die_error(400, "Missing one of the blob diff parameters");
7709 }
7710
7711 if (@difftree > 1) {
7712 die_error(400, "Ambiguous blob diff specification");
7713 }
7714
7715 %diffinfo = parse_difftree_raw_line($difftree[0]);
7716 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7717 $file_name ||= $diffinfo{'to_file'};
7718
7719 $hash_parent ||= $diffinfo{'from_id'};
7720 $hash ||= $diffinfo{'to_id'};
7721
7722 # non-textual hash id's can be cached
7723 if ($hash_base =~ m/^$oid_regex$/ &&
7724 $hash_parent_base =~ m/^$oid_regex$/) {
7725 $expires = '+1d';
7726 }
7727
7728 # open patch output
7729 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7730 '-p', ($format eq 'html' ? "--full-index" : ()),
7731 $hash_parent_base, $hash_base,
7732 "--", (defined $file_parent ? $file_parent : ()), $file_name
7733 or die_error(500, "Open git-diff-tree failed");
7734 }
7735
7736 # old/legacy style URI -- not generated anymore since 1.4.3.
7737 if (!%diffinfo) {
7738 die_error('404 Not Found', "Missing one of the blob diff parameters")
7739 }
7740
7741 # header
7742 if ($format eq 'html') {
7743 my $formats_nav =
7744 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7745 "raw");
7746 $formats_nav .= diff_style_nav($diff_style);
7747 git_header_html(undef, $expires);
7748 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7749 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7750 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7751 } else {
7752 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7753 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7754 }
7755 if (defined $file_name) {
7756 git_print_page_path($file_name, "blob", $hash_base);
7757 } else {
7758 print "<div class=\"page_path\"></div>\n";
7759 }
7760
7761 } elsif ($format eq 'plain') {
7762 print $cgi->header(
7763 -type => 'text/plain',
7764 -charset => 'utf-8',
7765 -expires => $expires,
7766 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7767
7768 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7769
7770 } else {
7771 die_error(400, "Unknown blobdiff format");
7772 }
7773
7774 # patch
7775 if ($format eq 'html') {
7776 print "<div class=\"page_body\">\n";
7777
7778 git_patchset_body($fd, $diff_style,
7779 [ \%diffinfo ], $hash_base, $hash_parent_base);
7780 close $fd;
7781
7782 print "</div>\n"; # class="page_body"
7783 git_footer_html();
7784
7785 } else {
7786 while (my $line = <$fd>) {
7787 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7788 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7789
7790 print $line;
7791
7792 last if $line =~ m!^\+\+\+!;
7793 }
7794 local $/ = undef;
7795 print <$fd>;
7796 close $fd;
7797 }
7798 }
7799
7800 sub git_blobdiff_plain {
7801 git_blobdiff('plain');
7802 }
7803
7804 # assumes that it is added as later part of already existing navigation,
7805 # so it returns "| foo | bar" rather than just "foo | bar"
7806 sub diff_style_nav {
7807 my ($diff_style, $is_combined) = @_;
7808 $diff_style ||= 'inline';
7809
7810 return "" if ($is_combined);
7811
7812 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7813 my %styles = @styles;
7814 @styles =
7815 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7816
7817 return join '',
7818 map { " | ".$_ }
7819 map {
7820 $_ eq $diff_style ? $styles{$_} :
7821 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7822 } @styles;
7823 }
7824
7825 sub git_commitdiff {
7826 my %params = @_;
7827 my $format = $params{-format} || 'html';
7828 my $diff_style = $input_params{'diff_style'} || 'inline';
7829
7830 my ($patch_max) = gitweb_get_feature('patches');
7831 if ($format eq 'patch') {
7832 die_error(403, "Patch view not allowed") unless $patch_max;
7833 }
7834
7835 $hash ||= $hash_base || "HEAD";
7836 my %co = parse_commit($hash)
7837 or die_error(404, "Unknown commit object");
7838
7839 # choose format for commitdiff for merge
7840 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7841 $hash_parent = '--cc';
7842 }
7843 # we need to prepare $formats_nav before almost any parameter munging
7844 my $formats_nav;
7845 if ($format eq 'html') {
7846 $formats_nav =
7847 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7848 "raw");
7849 if ($patch_max && @{$co{'parents'}} <= 1) {
7850 $formats_nav .= " | " .
7851 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7852 "patch");
7853 }
7854 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7855
7856 if (defined $hash_parent &&
7857 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7858 # commitdiff with two commits given
7859 my $hash_parent_short = $hash_parent;
7860 if ($hash_parent =~ m/^$oid_regex$/) {
7861 $hash_parent_short = substr($hash_parent, 0, 7);
7862 }
7863 $formats_nav .=
7864 ' (from';
7865 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7866 if ($co{'parents'}[$i] eq $hash_parent) {
7867 $formats_nav .= ' parent ' . ($i+1);
7868 last;
7869 }
7870 }
7871 $formats_nav .= ': ' .
7872 $cgi->a({-href => href(-replay=>1,
7873 hash=>$hash_parent, hash_base=>undef)},
7874 esc_html($hash_parent_short)) .
7875 ')';
7876 } elsif (!$co{'parent'}) {
7877 # --root commitdiff
7878 $formats_nav .= ' (initial)';
7879 } elsif (scalar @{$co{'parents'}} == 1) {
7880 # single parent commit
7881 $formats_nav .=
7882 ' (parent: ' .
7883 $cgi->a({-href => href(-replay=>1,
7884 hash=>$co{'parent'}, hash_base=>undef)},
7885 esc_html(substr($co{'parent'}, 0, 7))) .
7886 ')';
7887 } else {
7888 # merge commit
7889 if ($hash_parent eq '--cc') {
7890 $formats_nav .= ' | ' .
7891 $cgi->a({-href => href(-replay=>1,
7892 hash=>$hash, hash_parent=>'-c')},
7893 'combined');
7894 } else { # $hash_parent eq '-c'
7895 $formats_nav .= ' | ' .
7896 $cgi->a({-href => href(-replay=>1,
7897 hash=>$hash, hash_parent=>'--cc')},
7898 'compact');
7899 }
7900 $formats_nav .=
7901 ' (merge: ' .
7902 join(' ', map {
7903 $cgi->a({-href => href(-replay=>1,
7904 hash=>$_, hash_base=>undef)},
7905 esc_html(substr($_, 0, 7)));
7906 } @{$co{'parents'}} ) .
7907 ')';
7908 }
7909 }
7910
7911 my $hash_parent_param = $hash_parent;
7912 if (!defined $hash_parent_param) {
7913 # --cc for multiple parents, --root for parentless
7914 $hash_parent_param =
7915 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7916 }
7917
7918 # read commitdiff
7919 my $fd;
7920 my @difftree;
7921 if ($format eq 'html') {
7922 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7923 "--no-commit-id", "--patch-with-raw", "--full-index",
7924 $hash_parent_param, $hash, "--"
7925 or die_error(500, "Open git-diff-tree failed");
7926
7927 while (my $line = <$fd>) {
7928 chomp $line;
7929 # empty line ends raw part of diff-tree output
7930 last unless $line;
7931 push @difftree, scalar parse_difftree_raw_line($line);
7932 }
7933
7934 } elsif ($format eq 'plain') {
7935 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7936 '-p', $hash_parent_param, $hash, "--"
7937 or die_error(500, "Open git-diff-tree failed");
7938 } elsif ($format eq 'patch') {
7939 # For commit ranges, we limit the output to the number of
7940 # patches specified in the 'patches' feature.
7941 # For single commits, we limit the output to a single patch,
7942 # diverging from the git-format-patch default.
7943 my @commit_spec = ();
7944 if ($hash_parent) {
7945 if ($patch_max > 0) {
7946 push @commit_spec, "-$patch_max";
7947 }
7948 push @commit_spec, '-n', "$hash_parent..$hash";
7949 } else {
7950 if ($params{-single}) {
7951 push @commit_spec, '-1';
7952 } else {
7953 if ($patch_max > 0) {
7954 push @commit_spec, "-$patch_max";
7955 }
7956 push @commit_spec, "-n";
7957 }
7958 push @commit_spec, '--root', $hash;
7959 }
7960 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7961 '--encoding=utf8', '--stdout', @commit_spec
7962 or die_error(500, "Open git-format-patch failed");
7963 } else {
7964 die_error(400, "Unknown commitdiff format");
7965 }
7966
7967 # non-textual hash id's can be cached
7968 my $expires;
7969 if ($hash =~ m/^$oid_regex$/) {
7970 $expires = "+1d";
7971 }
7972
7973 # write commit message
7974 if ($format eq 'html') {
7975 my $refs = git_get_references();
7976 my $ref = format_ref_marker($refs, $co{'id'});
7977
7978 git_header_html(undef, $expires);
7979 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7980 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7981 print "<div class=\"title_text\">\n" .
7982 "<table class=\"object_header\">\n";
7983 git_print_authorship_rows(\%co);
7984 print "</table>".
7985 "</div>\n";
7986 print "<div class=\"page_body\">\n";
7987 if (@{$co{'comment'}} > 1) {
7988 print "<div class=\"log\">\n";
7989 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7990 print "</div>\n"; # class="log"
7991 }
7992
7993 } elsif ($format eq 'plain') {
7994 my $refs = git_get_references("tags");
7995 my $tagname = git_get_rev_name_tags($hash);
7996 my $filename = basename($project) . "-$hash.patch";
7997
7998 print $cgi->header(
7999 -type => 'text/plain',
8000 -charset => 'utf-8',
8001 -expires => $expires,
8002 -content_disposition => 'inline; filename="' . "$filename" . '"');
8003 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8004 print "From: " . to_utf8($co{'author'}) . "\n";
8005 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8006 print "Subject: " . to_utf8($co{'title'}) . "\n";
8007
8008 print "X-Git-Tag: $tagname\n" if $tagname;
8009 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8010
8011 foreach my $line (@{$co{'comment'}}) {
8012 print to_utf8($line) . "\n";
8013 }
8014 print "---\n\n";
8015 } elsif ($format eq 'patch') {
8016 my $filename = basename($project) . "-$hash.patch";
8017
8018 print $cgi->header(
8019 -type => 'text/plain',
8020 -charset => 'utf-8',
8021 -expires => $expires,
8022 -content_disposition => 'inline; filename="' . "$filename" . '"');
8023 }
8024
8025 # write patch
8026 if ($format eq 'html') {
8027 my $use_parents = !defined $hash_parent ||
8028 $hash_parent eq '-c' || $hash_parent eq '--cc';
8029 git_difftree_body(\@difftree, $hash,
8030 $use_parents ? @{$co{'parents'}} : $hash_parent);
8031 print "<br/>\n";
8032
8033 git_patchset_body($fd, $diff_style,
8034 \@difftree, $hash,
8035 $use_parents ? @{$co{'parents'}} : $hash_parent);
8036 close $fd;
8037 print "</div>\n"; # class="page_body"
8038 git_footer_html();
8039
8040 } elsif ($format eq 'plain') {
8041 local $/ = undef;
8042 print <$fd>;
8043 close $fd
8044 or print "Reading git-diff-tree failed\n";
8045 } elsif ($format eq 'patch') {
8046 local $/ = undef;
8047 print <$fd>;
8048 close $fd
8049 or print "Reading git-format-patch failed\n";
8050 }
8051 }
8052
8053 sub git_commitdiff_plain {
8054 git_commitdiff(-format => 'plain');
8055 }
8056
8057 # format-patch-style patches
8058 sub git_patch {
8059 git_commitdiff(-format => 'patch', -single => 1);
8060 }
8061
8062 sub git_patches {
8063 git_commitdiff(-format => 'patch');
8064 }
8065
8066 sub git_history {
8067 git_log_generic('history', \&git_history_body,
8068 $hash_base, $hash_parent_base,
8069 $file_name, $hash);
8070 }
8071
8072 sub git_search {
8073 $searchtype ||= 'commit';
8074
8075 # check if appropriate features are enabled
8076 gitweb_check_feature('search')
8077 or die_error(403, "Search is disabled");
8078 if ($searchtype eq 'pickaxe') {
8079 # pickaxe may take all resources of your box and run for several minutes
8080 # with every query - so decide by yourself how public you make this feature
8081 gitweb_check_feature('pickaxe')
8082 or die_error(403, "Pickaxe search is disabled");
8083 }
8084 if ($searchtype eq 'grep') {
8085 # grep search might be potentially CPU-intensive, too
8086 gitweb_check_feature('grep')
8087 or die_error(403, "Grep search is disabled");
8088 }
8089
8090 if (!defined $searchtext) {
8091 die_error(400, "Text field is empty");
8092 }
8093 if (!defined $hash) {
8094 $hash = git_get_head_hash($project);
8095 }
8096 my %co = parse_commit($hash);
8097 if (!%co) {
8098 die_error(404, "Unknown commit object");
8099 }
8100 if (!defined $page) {
8101 $page = 0;
8102 }
8103
8104 if ($searchtype eq 'commit' ||
8105 $searchtype eq 'author' ||
8106 $searchtype eq 'committer') {
8107 git_search_message(%co);
8108 } elsif ($searchtype eq 'pickaxe') {
8109 git_search_changes(%co);
8110 } elsif ($searchtype eq 'grep') {
8111 git_search_files(%co);
8112 } else {
8113 die_error(400, "Unknown search type");
8114 }
8115 }
8116
8117 sub git_search_help {
8118 git_header_html();
8119 git_print_page_nav('','', $hash,$hash,$hash);
8120 print <<EOT;
8121 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8122 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8123 the pattern entered is recognized as the POSIX extended
8124 <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8125 insensitive).</p>
8126 <dl>
8127 <dt><b>commit</b></dt>
8128 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8129 EOT
8130 my $have_grep = gitweb_check_feature('grep');
8131 if ($have_grep) {
8132 print <<EOT;
8133 <dt><b>grep</b></dt>
8134 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8135 a different one) are searched for the given pattern. On large trees, this search can take
8136 a while and put some strain on the server, so please use it with some consideration. Note that
8137 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8138 case-sensitive.</dd>
8139 EOT
8140 }
8141 print <<EOT;
8142 <dt><b>author</b></dt>
8143 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8144 <dt><b>committer</b></dt>
8145 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8146 EOT
8147 my $have_pickaxe = gitweb_check_feature('pickaxe');
8148 if ($have_pickaxe) {
8149 print <<EOT;
8150 <dt><b>pickaxe</b></dt>
8151 <dd>All commits that caused the string to appear or disappear from any file (changes that
8152 added, removed or "modified" the string) will be listed. This search can take a while and
8153 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8154 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8155 EOT
8156 }
8157 print "</dl>\n";
8158 git_footer_html();
8159 }
8160
8161 sub git_shortlog {
8162 git_log_generic('shortlog', \&git_shortlog_body,
8163 $hash, $hash_parent);
8164 }
8165
8166 ## ......................................................................
8167 ## feeds (RSS, Atom; OPML)
8168
8169 sub git_feed {
8170 my $format = shift || 'atom';
8171 my $have_blame = gitweb_check_feature('blame');
8172
8173 # Atom: http://www.atomenabled.org/developers/syndication/
8174 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8175 if ($format ne 'rss' && $format ne 'atom') {
8176 die_error(400, "Unknown web feed format");
8177 }
8178
8179 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8180 my $head = $hash || 'HEAD';
8181 my @commitlist = parse_commits($head, 150, 0, $file_name);
8182
8183 my %latest_commit;
8184 my %latest_date;
8185 my $content_type = "application/$format+xml";
8186 if (defined $cgi->http('HTTP_ACCEPT') &&
8187 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8188 # browser (feed reader) prefers text/xml
8189 $content_type = 'text/xml';
8190 }
8191 if (defined($commitlist[0])) {
8192 %latest_commit = %{$commitlist[0]};
8193 my $latest_epoch = $latest_commit{'committer_epoch'};
8194 exit_if_unmodified_since($latest_epoch);
8195 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8196 }
8197 print $cgi->header(
8198 -type => $content_type,
8199 -charset => 'utf-8',
8200 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8201 -status => '200 OK');
8202
8203 # Optimization: skip generating the body if client asks only
8204 # for Last-Modified date.
8205 return if ($cgi->request_method() eq 'HEAD');
8206
8207 # header variables
8208 my $title = "$site_name - $project/$action";
8209 my $feed_type = 'log';
8210 if (defined $hash) {
8211 $title .= " - '$hash'";
8212 $feed_type = 'branch log';
8213 if (defined $file_name) {
8214 $title .= " :: $file_name";
8215 $feed_type = 'history';
8216 }
8217 } elsif (defined $file_name) {
8218 $title .= " - $file_name";
8219 $feed_type = 'history';
8220 }
8221 $title .= " $feed_type";
8222 $title = esc_html($title);
8223 my $descr = git_get_project_description($project);
8224 if (defined $descr) {
8225 $descr = esc_html($descr);
8226 } else {
8227 $descr = "$project " .
8228 ($format eq 'rss' ? 'RSS' : 'Atom') .
8229 " feed";
8230 }
8231 my $owner = git_get_project_owner($project);
8232 $owner = esc_html($owner);
8233
8234 #header
8235 my $alt_url;
8236 if (defined $file_name) {
8237 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8238 } elsif (defined $hash) {
8239 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8240 } else {
8241 $alt_url = href(-full=>1, action=>"summary");
8242 }
8243 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8244 if ($format eq 'rss') {
8245 print <<XML;
8246 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8247 <channel>
8248 XML
8249 print "<title>$title</title>\n" .
8250 "<link>$alt_url</link>\n" .
8251 "<description>$descr</description>\n" .
8252 "<language>en</language>\n" .
8253 # project owner is responsible for 'editorial' content
8254 "<managingEditor>$owner</managingEditor>\n";
8255 if (defined $logo || defined $favicon) {
8256 # prefer the logo to the favicon, since RSS
8257 # doesn't allow both
8258 my $img = esc_url($logo || $favicon);
8259 print "<image>\n" .
8260 "<url>$img</url>\n" .
8261 "<title>$title</title>\n" .
8262 "<link>$alt_url</link>\n" .
8263 "</image>\n";
8264 }
8265 if (%latest_date) {
8266 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8267 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8268 }
8269 print "<generator>gitweb v.$version/$git_version</generator>\n";
8270 } elsif ($format eq 'atom') {
8271 print <<XML;
8272 <feed xmlns="http://www.w3.org/2005/Atom">
8273 XML
8274 print "<title>$title</title>\n" .
8275 "<subtitle>$descr</subtitle>\n" .
8276 '<link rel="alternate" type="text/html" href="' .
8277 $alt_url . '" />' . "\n" .
8278 '<link rel="self" type="' . $content_type . '" href="' .
8279 $cgi->self_url() . '" />' . "\n" .
8280 "<id>" . href(-full=>1) . "</id>\n" .
8281 # use project owner for feed author
8282 "<author><name>$owner</name></author>\n";
8283 if (defined $favicon) {
8284 print "<icon>" . esc_url($favicon) . "</icon>\n";
8285 }
8286 if (defined $logo) {
8287 # not twice as wide as tall: 72 x 27 pixels
8288 print "<logo>" . esc_url($logo) . "</logo>\n";
8289 }
8290 if (! %latest_date) {
8291 # dummy date to keep the feed valid until commits trickle in:
8292 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8293 } else {
8294 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8295 }
8296 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8297 }
8298
8299 # contents
8300 for (my $i = 0; $i <= $#commitlist; $i++) {
8301 my %co = %{$commitlist[$i]};
8302 my $commit = $co{'id'};
8303 # we read 150, we always show 30 and the ones more recent than 48 hours
8304 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8305 last;
8306 }
8307 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8308
8309 # get list of changed files
8310 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8311 $co{'parent'} || "--root",
8312 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8313 or next;
8314 my @difftree = map { chomp; $_ } <$fd>;
8315 close $fd
8316 or next;
8317
8318 # print element (entry, item)
8319 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8320 if ($format eq 'rss') {
8321 print "<item>\n" .
8322 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8323 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8324 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8325 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8326 "<link>$co_url</link>\n" .
8327 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8328 "<content:encoded>" .
8329 "<![CDATA[\n";
8330 } elsif ($format eq 'atom') {
8331 print "<entry>\n" .
8332 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8333 "<updated>$cd{'iso-8601'}</updated>\n" .
8334 "<author>\n" .
8335 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8336 if ($co{'author_email'}) {
8337 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8338 }
8339 print "</author>\n" .
8340 # use committer for contributor
8341 "<contributor>\n" .
8342 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8343 if ($co{'committer_email'}) {
8344 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8345 }
8346 print "</contributor>\n" .
8347 "<published>$cd{'iso-8601'}</published>\n" .
8348 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8349 "<id>$co_url</id>\n" .
8350 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8351 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8352 }
8353 my $comment = $co{'comment'};
8354 print "<pre>\n";
8355 foreach my $line (@$comment) {
8356 $line = esc_html($line);
8357 print "$line\n";
8358 }
8359 print "</pre><ul>\n";
8360 foreach my $difftree_line (@difftree) {
8361 my %difftree = parse_difftree_raw_line($difftree_line);
8362 next if !$difftree{'from_id'};
8363
8364 my $file = $difftree{'file'} || $difftree{'to_file'};
8365
8366 print "<li>" .
8367 "[" .
8368 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8369 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8370 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8371 file_name=>$file, file_parent=>$difftree{'from_file'}),
8372 -title => "diff"}, 'D');
8373 if ($have_blame) {
8374 print $cgi->a({-href => href(-full=>1, action=>"blame",
8375 file_name=>$file, hash_base=>$commit),
8376 -title => "blame"}, 'B');
8377 }
8378 # if this is not a feed of a file history
8379 if (!defined $file_name || $file_name ne $file) {
8380 print $cgi->a({-href => href(-full=>1, action=>"history",
8381 file_name=>$file, hash=>$commit),
8382 -title => "history"}, 'H');
8383 }
8384 $file = esc_path($file);
8385 print "] ".
8386 "$file</li>\n";
8387 }
8388 if ($format eq 'rss') {
8389 print "</ul>]]>\n" .
8390 "</content:encoded>\n" .
8391 "</item>\n";
8392 } elsif ($format eq 'atom') {
8393 print "</ul>\n</div>\n" .
8394 "</content>\n" .
8395 "</entry>\n";
8396 }
8397 }
8398
8399 # end of feed
8400 if ($format eq 'rss') {
8401 print "</channel>\n</rss>\n";
8402 } elsif ($format eq 'atom') {
8403 print "</feed>\n";
8404 }
8405 }
8406
8407 sub git_rss {
8408 git_feed('rss');
8409 }
8410
8411 sub git_atom {
8412 git_feed('atom');
8413 }
8414
8415 sub git_opml {
8416 my @list = git_get_projects_list($project_filter, $strict_export);
8417 if (!@list) {
8418 die_error(404, "No projects found");
8419 }
8420
8421 print $cgi->header(
8422 -type => 'text/xml',
8423 -charset => 'utf-8',
8424 -content_disposition => 'inline; filename="opml.xml"');
8425
8426 my $title = esc_html($site_name);
8427 my $filter = " within subdirectory ";
8428 if (defined $project_filter) {
8429 $filter .= esc_html($project_filter);
8430 } else {
8431 $filter = "";
8432 }
8433 print <<XML;
8434 <?xml version="1.0" encoding="utf-8"?>
8435 <opml version="1.0">
8436 <head>
8437 <title>$title OPML Export$filter</title>
8438 </head>
8439 <body>
8440 <outline text="git RSS feeds">
8441 XML
8442
8443 foreach my $pr (@list) {
8444 my %proj = %$pr;
8445 my $head = git_get_head_hash($proj{'path'});
8446 if (!defined $head) {
8447 next;
8448 }
8449 $git_dir = "$projectroot/$proj{'path'}";
8450 my %co = parse_commit($head);
8451 if (!%co) {
8452 next;
8453 }
8454
8455 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8456 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8457 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8458 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8459 }
8460 print <<XML;
8461 </outline>
8462 </body>
8463 </opml>
8464 XML
8465 }
This page took 8.790672 seconds and 5 git commands to generate.