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