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