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