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