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