little changes
[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><td colspan="'.($check_forks ? '1' : '2').'">&nbsp;</td>';
5661 print "<td>".($to + 1)." project".($to > 1 ? ($to < 1 ? "" : "s") : "")." found</td><td colspan=\"3\">&nbsp;</td></tr>";
5662 }
5663
5664 sub git_project_list_body {
5665 # actually uses global variable $project
5666 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5667 my @projects = @$projlist;
5668
5669 my $check_forks = gitweb_check_feature('forks');
5670 my $show_ctags = gitweb_check_feature('ctags');
5671 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5672 $check_forks = undef
5673 if ($tagfilter || $search_regexp);
5674
5675 # filtering out forks before filling info allows to do less work
5676 @projects = filter_forks_from_projects_list(\@projects)
5677 if ($check_forks);
5678 # search_projects_list pre-fills required info
5679 @projects = search_projects_list(\@projects,
5680 'search_regexp' => $search_regexp,
5681 'tagfilter' => $tagfilter)
5682 if ($tagfilter || $search_regexp);
5683 # fill the rest
5684 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5685 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5686 push @all_fields, 'owner' unless($omit_owner);
5687 @projects = fill_project_list_info(\@projects, @all_fields);
5688
5689 $order ||= $default_projects_order;
5690 $from = 0 unless defined $from;
5691 $to = $#projects if (!defined $to || $#projects < $to);
5692
5693 # short circuit
5694 if ($from > $to) {
5695 print "<center>\n".
5696 "<b>No such projects found</b><br />\n".
5697 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5698 "</center>\n<br />\n";
5699 return;
5700 }
5701
5702 @projects = sort_projects_list(\@projects, $order);
5703
5704 if ($show_ctags) {
5705 my $ctags = git_gather_all_ctags(\@projects);
5706 my $cloud = git_populate_project_tagcloud($ctags);
5707 print git_show_project_tagcloud($cloud, 64);
5708 }
5709
5710 print "<table class=\"project_list\">\n";
5711 unless ($no_header) {
5712 print "<tr>\n";
5713 if ($check_forks) {
5714 print "<th></th>\n";
5715 }
5716 print_sort_th('project', $order, 'Project');
5717 print_sort_th('descr', $order, 'Description');
5718 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5719 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5720 print "<th></th>\n" . # for links
5721 "</tr>\n";
5722 }
5723
5724 if ($projects_list_group_categories) {
5725 # only display categories with projects in the $from-$to window
5726 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5727 my %categories = build_projlist_by_category(\@projects, $from, $to);
5728 foreach my $cat (sort keys %categories) {
5729 unless ($cat eq "") {
5730 print "<tr>\n";
5731 if ($check_forks) {
5732 print "<td></td>\n";
5733 }
5734 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5735 print "</tr>\n";
5736 }
5737
5738 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5739 }
5740 } else {
5741 git_project_list_rows(\@projects, $from, $to, $check_forks);
5742 }
5743
5744 if (defined $extra) {
5745 print "<tr>\n";
5746 if ($check_forks) {
5747 print "<td></td>\n";
5748 }
5749 print "<td colspan=\"5\">$extra</td>\n" .
5750 "</tr>\n";
5751 }
5752 print "</table>\n";
5753 }
5754
5755 sub git_log_body {
5756 # uses global variable $project
5757 my ($commitlist, $from, $to, $refs, $extra) = @_;
5758
5759 $from = 0 unless defined $from;
5760 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5761
5762 for (my $i = 0; $i <= $to; $i++) {
5763 my %co = %{$commitlist->[$i]};
5764 next if !%co;
5765 my $commit = $co{'id'};
5766 my $ref = format_ref_marker($refs, $commit);
5767 git_print_header_div('commit',
5768 "<span class=\"age\">$co{'age_string'}</span>" .
5769 esc_html($co{'title'}) . $ref,
5770 $commit);
5771 print "<div class=\"title_text\">\n" .
5772 "<div class=\"log_link\">\n" .
5773 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5774 " | " .
5775 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5776 " | " .
5777 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5778 "<br/>\n" .
5779 "</div>\n";
5780 git_print_authorship(\%co, -tag => 'span');
5781 print "<br/>\n</div>\n";
5782
5783 print "<div class=\"log_body\">\n";
5784 git_print_log($co{'comment'}, -final_empty_line=> 1);
5785 print "</div>\n";
5786 }
5787 if ($extra) {
5788 print "<div class=\"page_nav\">\n";
5789 print "$extra\n";
5790 print "</div>\n";
5791 }
5792 }
5793
5794 sub git_shortlog_body {
5795 # uses global variable $project
5796 my ($commitlist, $from, $to, $refs, $extra, $file_name, $file_hash, $ftype, $allrefs) = @_;
5797
5798 $from = 0 unless defined $from;
5799 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5800
5801 print "<table class=\"shortlog\" cellspacing=\"0\" cellpadding=\"0\">\n";
5802 my $alternate = 1;
5803 my $graph_rand = int(rand(99999));
5804 my $head = git_get_head_hash($project);
5805 my $graph_hash;
5806 if (defined $allrefs && $allrefs == 1) {
5807 $graph_hash = "all";
5808 }
5809 if (!defined $hash) {
5810 $hash = $head;
5811 }
5812 if(!defined $graph_hash) {
5813 $graph_hash = $hash;
5814 }
5815 if (!defined $page) {
5816 $page = 0;
5817 }
5818 print "<tr class=\"header\">\n";
5819 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";
5820 print "<td valign=\"bottom\"><b>Author</b></td>\n";
5821 print "<td valign=\"bottom\"><b>Commit</b></td>\n";
5822 print "<td></td>\n";
5823 print "</tr>\n";
5824
5825 for (my $i = $from; $i <= $to; $i++) {
5826 my %co = %{$commitlist->[$i]};
5827 my $commit = $co{'id'};
5828 my $ref = format_ref_marker($refs, $commit);
5829 if ($alternate) {
5830 print "<tr class=\"dark\">\n";
5831 } else {
5832 print "<tr class=\"light\">\n";
5833 }
5834 $alternate ^= 1;
5835 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>";
5836 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5837 print "<td class=\"". age_class($co{'age'}) . "\" title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5838 format_author_html('td', \%co, 10) . "<td>";
5839 print format_subject_html($co{'title'}, $co{'title_short'},
5840 href(action=>"commit", hash=>$commit), $ref);
5841 print "</td>\n" .
5842 "<td class=\"link\">" .
5843 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5844 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5845 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5846 my $snapshot_links = format_snapshot_links($commit);
5847 if (defined $snapshot_links) {
5848 print " | " . $snapshot_links;
5849 }
5850 print "</td>\n" .
5851 "</tr>\n";
5852 }
5853 if (defined $extra) {
5854 print "<tr>\n" .
5855 "<td colspan=\"4\">$extra</td>\n" .
5856 "</tr>\n";
5857 }
5858 print "</table>\n";
5859 }
5860
5861 sub git_history_body {
5862 # Warning: assumes constant type (blob or tree) during history
5863 my ($commitlist, $from, $to, $refs, $extra,
5864 $file_name, $file_hash, $ftype) = @_;
5865
5866 $from = 0 unless defined $from;
5867 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5868
5869 print "<table class=\"history\">\n";
5870 my $alternate = 1;
5871 for (my $i = $from; $i <= $to; $i++) {
5872 my %co = %{$commitlist->[$i]};
5873 if (!%co) {
5874 next;
5875 }
5876 my $commit = $co{'id'};
5877
5878 my $ref = format_ref_marker($refs, $commit);
5879
5880 if ($alternate) {
5881 print "<tr class=\"dark\">\n";
5882 } else {
5883 print "<tr class=\"light\">\n";
5884 }
5885 $alternate ^= 1;
5886 print "<td class=\"". age_class($co{'age'}) . "\" title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5887 # shortlog: format_author_html('td', \%co, 10)
5888 format_author_html('td', \%co, 15, 3) . "<td>";
5889 # originally git_history used chop_str($co{'title'}, 50)
5890 print format_subject_html($co{'title'}, $co{'title_short'},
5891 href(action=>"commit", hash=>$commit), $ref);
5892 print "</td>\n" .
5893 "<td class=\"link\">" .
5894 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5895 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5896
5897 if ($ftype eq 'blob') {
5898 my $blob_current = $file_hash;
5899 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5900 if (defined $blob_current && defined $blob_parent &&
5901 $blob_current ne $blob_parent) {
5902 print " | " .
5903 $cgi->a({-href => href(action=>"blobdiff",
5904 hash=>$blob_current, hash_parent=>$blob_parent,
5905 hash_base=>$hash_base, hash_parent_base=>$commit,
5906 file_name=>$file_name)},
5907 "diff to current");
5908 }
5909 }
5910 print "</td>\n" .
5911 "</tr>\n";
5912 }
5913 if (defined $extra) {
5914 print "<tr>\n" .
5915 "<td colspan=\"4\">$extra</td>\n" .
5916 "</tr>\n";
5917 }
5918 print "</table>\n";
5919 }
5920
5921 sub git_tags_body {
5922 # uses global variable $project
5923 my ($taglist, $from, $to, $extra) = @_;
5924 $from = 0 unless defined $from;
5925 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5926
5927 print "<table class=\"tags\">\n";
5928 my $alternate = 1;
5929 for (my $i = $from; $i <= $to; $i++) {
5930 my $entry = $taglist->[$i];
5931 my %tag = %$entry;
5932 my $comment = $tag{'subject'};
5933 my $comment_short;
5934 if (defined $comment) {
5935 $comment_short = chop_str($comment, 30, 5);
5936 }
5937 if ($alternate) {
5938 print "<tr class=\"dark\">\n";
5939 } else {
5940 print "<tr class=\"light\">\n";
5941 }
5942 $alternate ^= 1;
5943 if (defined $tag{'age'}) {
5944 print "<td><i>$tag{'age'}</i></td>\n";
5945 } else {
5946 print "<td></td>\n";
5947 }
5948 print "<td>" .
5949 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5950 -class => "list name"}, esc_html($tag{'name'})) .
5951 "</td>\n" .
5952 "<td>";
5953 if (defined $comment) {
5954 print format_subject_html($comment, $comment_short,
5955 href(action=>"tag", hash=>$tag{'id'}));
5956 }
5957 print "</td>\n" .
5958 "<td class=\"selflink\">";
5959 if ($tag{'type'} eq "tag") {
5960 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5961 } else {
5962 print "&nbsp;";
5963 }
5964 print "</td>\n" .
5965 "<td class=\"link\">" . " | " .
5966 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5967 if ($tag{'reftype'} eq "commit") {
5968 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5969 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5970 } elsif ($tag{'reftype'} eq "blob") {
5971 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5972 }
5973 print "</td>\n" .
5974 "</tr>";
5975 }
5976 if (defined $extra) {
5977 print "<tr>\n" .
5978 "<td colspan=\"5\">$extra</td>\n" .
5979 "</tr>\n";
5980 }
5981 print "</table>\n";
5982 }
5983
5984 sub git_heads_body {
5985 # uses global variable $project
5986 my ($headlist, $head_at, $from, $to, $extra) = @_;
5987 $from = 0 unless defined $from;
5988 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5989
5990 print "<table class=\"heads\">\n";
5991 my $alternate = 1;
5992 for (my $i = $from; $i <= $to; $i++) {
5993 my $entry = $headlist->[$i];
5994 my %ref = %$entry;
5995 my $curr = defined $head_at && $ref{'id'} eq $head_at;
5996 if ($alternate) {
5997 print "<tr class=\"dark\">\n";
5998 } else {
5999 print "<tr class=\"light\">\n";
6000 }
6001 $alternate ^= 1;
6002 print "<td><i>$ref{'age'}</i></td>\n" .
6003 ($curr ? "<td class=\"current_head\">" : "<td>") .
6004 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6005 -class => "list name"},esc_html($ref{'name'})) .
6006 "</td>\n" .
6007 "<td class=\"link\">" .
6008 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6009 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6010 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6011 "</td>\n" .
6012 "</tr>";
6013 }
6014 if (defined $extra) {
6015 print "<tr>\n" .
6016 "<td colspan=\"3\">$extra</td>\n" .
6017 "</tr>\n";
6018 }
6019 print "</table>\n";
6020 }
6021
6022 # Display a single remote block
6023 sub git_remote_block {
6024 my ($remote, $rdata, $limit, $head) = @_;
6025
6026 my $heads = $rdata->{'heads'};
6027 my $fetch = $rdata->{'fetch'};
6028 my $push = $rdata->{'push'};
6029
6030 my $urls_table = "<table class=\"projects_list\">\n" ;
6031
6032 if (defined $fetch) {
6033 if ($fetch eq $push) {
6034 $urls_table .= format_repo_url("URL", $fetch);
6035 } else {
6036 $urls_table .= format_repo_url("Fetch URL", $fetch);
6037 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6038 }
6039 } elsif (defined $push) {
6040 $urls_table .= format_repo_url("Push URL", $push);
6041 } else {
6042 $urls_table .= format_repo_url("", "No remote URL");
6043 }
6044
6045 $urls_table .= "</table>\n";
6046
6047 my $dots;
6048 if (defined $limit && $limit < @$heads) {
6049 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6050 }
6051
6052 print $urls_table;
6053 git_heads_body($heads, $head, 0, $limit, $dots);
6054 }
6055
6056 # Display a list of remote names with the respective fetch and push URLs
6057 sub git_remotes_list {
6058 my ($remotedata, $limit) = @_;
6059 print "<table class=\"heads\">\n";
6060 my $alternate = 1;
6061 my @remotes = sort keys %$remotedata;
6062
6063 my $limited = $limit && $limit < @remotes;
6064
6065 $#remotes = $limit - 1 if $limited;
6066
6067 while (my $remote = shift @remotes) {
6068 my $rdata = $remotedata->{$remote};
6069 my $fetch = $rdata->{'fetch'};
6070 my $push = $rdata->{'push'};
6071 if ($alternate) {
6072 print "<tr class=\"dark\">\n";
6073 } else {
6074 print "<tr class=\"light\">\n";
6075 }
6076 $alternate ^= 1;
6077 print "<td>" .
6078 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6079 -class=> "list name"},esc_html($remote)) .
6080 "</td>";
6081 print "<td class=\"link\">" .
6082 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6083 " | " .
6084 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6085 "</td>";
6086
6087 print "</tr>\n";
6088 }
6089
6090 if ($limited) {
6091 print "<tr>\n" .
6092 "<td colspan=\"3\">" .
6093 $cgi->a({-href => href(action=>"remotes")}, "...") .
6094 "</td>\n" . "</tr>\n";
6095 }
6096
6097 print "</table>";
6098 }
6099
6100 # Display remote heads grouped by remote, unless there are too many
6101 # remotes, in which case we only display the remote names
6102 sub git_remotes_body {
6103 my ($remotedata, $limit, $head) = @_;
6104 if ($limit and $limit < keys %$remotedata) {
6105 git_remotes_list($remotedata, $limit);
6106 } else {
6107 fill_remote_heads($remotedata);
6108 while (my ($remote, $rdata) = each %$remotedata) {
6109 git_print_section({-class=>"remote", -id=>$remote},
6110 ["remotes", $remote, $remote], sub {
6111 git_remote_block($remote, $rdata, $limit, $head);
6112 });
6113 }
6114 }
6115 }
6116
6117 sub git_search_message {
6118 my %co = @_;
6119
6120 my $greptype;
6121 if ($searchtype eq 'commit') {
6122 $greptype = "--grep=";
6123 } elsif ($searchtype eq 'author') {
6124 $greptype = "--author=";
6125 } elsif ($searchtype eq 'committer') {
6126 $greptype = "--committer=";
6127 }
6128 $greptype .= $searchtext;
6129 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6130 $greptype, '--regexp-ignore-case',
6131 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6132
6133 my $paging_nav = '';
6134 if ($page > 0) {
6135 $paging_nav .=
6136 $cgi->a({-href => href(-replay=>1, page=>undef)},
6137 "first") .
6138 " &sdot; " .
6139 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6140 -accesskey => "p", -title => "Alt-p"}, "prev");
6141 } else {
6142 $paging_nav .= "first &sdot; prev";
6143 }
6144 my $next_link = '';
6145 if ($#commitlist >= 100) {
6146 $next_link =
6147 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6148 -accesskey => "n", -title => "Alt-n"}, "next");
6149 $paging_nav .= " &sdot; $next_link";
6150 } else {
6151 $paging_nav .= " &sdot; next";
6152 }
6153
6154 git_header_html();
6155
6156 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6157 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6158 if ($page == 0 && !@commitlist) {
6159 print "<p>No match.</p>\n";
6160 } else {
6161 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6162 }
6163
6164 git_footer_html();
6165 }
6166
6167 sub git_search_changes {
6168 my %co = @_;
6169
6170 local $/ = "\n";
6171 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6172 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6173 ($search_use_regexp ? '--pickaxe-regex' : ())
6174 or die_error(500, "Open git-log failed");
6175
6176 git_header_html();
6177
6178 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6179 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6180
6181 print "<table class=\"pickaxe search\">\n";
6182 my $alternate = 1;
6183 undef %co;
6184 my @files;
6185 while (my $line = <$fd>) {
6186 chomp $line;
6187 next unless $line;
6188
6189 my %set = parse_difftree_raw_line($line);
6190 if (defined $set{'commit'}) {
6191 # finish previous commit
6192 if (%co) {
6193 print "</td>\n" .
6194 "<td class=\"link\">" .
6195 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6196 "commit") .
6197 " | " .
6198 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6199 hash_base=>$co{'id'})},
6200 "tree") .
6201 "</td>\n" .
6202 "</tr>\n";
6203 }
6204
6205 if ($alternate) {
6206 print "<tr class=\"dark\">\n";
6207 } else {
6208 print "<tr class=\"light\">\n";
6209 }
6210 $alternate ^= 1;
6211 %co = parse_commit($set{'commit'});
6212 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6213 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6214 "<td><i>$author</i></td>\n" .
6215 "<td>" .
6216 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6217 -class => "list subject"},
6218 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6219 } elsif (defined $set{'to_id'}) {
6220 next if ($set{'to_id'} =~ m/^0{40}$/);
6221
6222 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6223 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6224 -class => "list"},
6225 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6226 "<br/>\n";
6227 }
6228 }
6229 close $fd;
6230
6231 # finish last commit (warning: repetition!)
6232 if (%co) {
6233 print "</td>\n" .
6234 "<td class=\"link\">" .
6235 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6236 "commit") .
6237 " | " .
6238 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6239 hash_base=>$co{'id'})},
6240 "tree") .
6241 "</td>\n" .
6242 "</tr>\n";
6243 }
6244
6245 print "</table>\n";
6246
6247 git_footer_html();
6248 }
6249
6250 sub git_search_files {
6251 my %co = @_;
6252
6253 local $/ = "\n";
6254 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6255 $search_use_regexp ? ('-E', '-i') : '-F',
6256 $searchtext, $co{'tree'}
6257 or die_error(500, "Open git-grep failed");
6258
6259 git_header_html();
6260
6261 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6262 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6263
6264 print "<table class=\"grep_search\">\n";
6265 my $alternate = 1;
6266 my $matches = 0;
6267 my $lastfile = '';
6268 my $file_href;
6269 while (my $line = <$fd>) {
6270 chomp $line;
6271 my ($file, $lno, $ltext, $binary);
6272 last if ($matches++ > 1000);
6273 if ($line =~ /^Binary file (.+) matches$/) {
6274 $file = $1;
6275 $binary = 1;
6276 } else {
6277 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6278 $file =~ s/^$co{'tree'}://;
6279 }
6280 if ($file ne $lastfile) {
6281 $lastfile and print "</td></tr>\n";
6282 if ($alternate++) {
6283 print "<tr class=\"dark\">\n";
6284 } else {
6285 print "<tr class=\"light\">\n";
6286 }
6287 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6288 file_name=>$file);
6289 print "<td class=\"list\">".
6290 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6291 print "</td><td>\n";
6292 $lastfile = $file;
6293 }
6294 if ($binary) {
6295 print "<div class=\"binary\">Binary file</div>\n";
6296 } else {
6297 $ltext = untabify($ltext);
6298 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6299 $ltext = esc_html($1, -nbsp=>1);
6300 $ltext .= '<span class="match">';
6301 $ltext .= esc_html($2, -nbsp=>1);
6302 $ltext .= '</span>';
6303 $ltext .= esc_html($3, -nbsp=>1);
6304 } else {
6305 $ltext = esc_html($ltext, -nbsp=>1);
6306 }
6307 print "<div class=\"pre\">" .
6308 $cgi->a({-href => $file_href.'#l'.$lno,
6309 -class => "linenr"}, sprintf('%4i', $lno)) .
6310 ' ' . $ltext . "</div>\n";
6311 }
6312 }
6313 if ($lastfile) {
6314 print "</td></tr>\n";
6315 if ($matches > 1000) {
6316 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6317 }
6318 } else {
6319 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6320 }
6321 close $fd;
6322
6323 print "</table>\n";
6324
6325 git_footer_html();
6326 }
6327
6328 sub git_search_grep_body {
6329 my ($commitlist, $from, $to, $extra) = @_;
6330 $from = 0 unless defined $from;
6331 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6332
6333 print "<table class=\"commit_search\">\n";
6334 my $alternate = 1;
6335 for (my $i = $from; $i <= $to; $i++) {
6336 my %co = %{$commitlist->[$i]};
6337 if (!%co) {
6338 next;
6339 }
6340 my $commit = $co{'id'};
6341 if ($alternate) {
6342 print "<tr class=\"dark\">\n";
6343 } else {
6344 print "<tr class=\"light\">\n";
6345 }
6346 $alternate ^= 1;
6347 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6348 format_author_html('td', \%co, 15, 5) .
6349 "<td>" .
6350 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6351 -class => "list subject"},
6352 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6353 my $comment = $co{'comment'};
6354 foreach my $line (@$comment) {
6355 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6356 my ($lead, $match, $trail) = ($1, $2, $3);
6357 $match = chop_str($match, 70, 5, 'center');
6358 my $contextlen = int((80 - length($match))/2);
6359 $contextlen = 30 if ($contextlen > 30);
6360 $lead = chop_str($lead, $contextlen, 10, 'left');
6361 $trail = chop_str($trail, $contextlen, 10, 'right');
6362
6363 $lead = esc_html($lead);
6364 $match = esc_html($match);
6365 $trail = esc_html($trail);
6366
6367 print "$lead<span class=\"match\">$match</span>$trail<br />";
6368 }
6369 }
6370 print "</td>\n" .
6371 "<td class=\"link\">" .
6372 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6373 " | " .
6374 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6375 " | " .
6376 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6377 print "</td>\n" .
6378 "</tr>\n";
6379 }
6380 if (defined $extra) {
6381 print "<tr>\n" .
6382 "<td colspan=\"3\">$extra</td>\n" .
6383 "</tr>\n";
6384 }
6385 print "</table>\n";
6386 }
6387
6388 ## ======================================================================
6389 ## ======================================================================
6390 ## actions
6391
6392 sub git_project_list {
6393 my $order = $input_params{'order'};
6394 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6395 die_error(400, "Unknown order parameter");
6396 }
6397
6398 my @list = git_get_projects_list($project_filter, $strict_export);
6399 if (!@list) {
6400 die_error(404, "No projects found");
6401 }
6402
6403 git_header_html();
6404 if (defined $home_text && -f $home_text) {
6405 print "<div class=\"index_include\">\n";
6406 insert_file($home_text);
6407 print "</div>\n";
6408 }
6409
6410 git_project_search_form($searchtext, $search_use_regexp);
6411 git_project_list_body(\@list, $order);
6412 git_footer_html();
6413 }
6414
6415 sub git_forks {
6416 my $order = $input_params{'order'};
6417 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6418 die_error(400, "Unknown order parameter");
6419 }
6420
6421 my $filter = $project;
6422 $filter =~ s/\.git$//;
6423 my @list = git_get_projects_list($filter);
6424 if (!@list) {
6425 die_error(404, "No forks found");
6426 }
6427
6428 git_header_html();
6429 git_print_page_nav('','');
6430 git_print_header_div('summary', "$project forks");
6431 git_project_list_body(\@list, $order);
6432 git_footer_html();
6433 }
6434
6435 sub git_project_index {
6436 my @projects = git_get_projects_list($project_filter, $strict_export);
6437 if (!@projects) {
6438 die_error(404, "No projects found");
6439 }
6440
6441 print $cgi->header(
6442 -type => 'text/plain',
6443 -charset => 'utf-8',
6444 -content_disposition => 'inline; filename="index.aux"');
6445
6446 foreach my $pr (@projects) {
6447 if (!exists $pr->{'owner'}) {
6448 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6449 }
6450
6451 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6452 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6453 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6454 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6455 $path =~ s/ /\+/g;
6456 $owner =~ s/ /\+/g;
6457
6458 print "$path $owner\n";
6459 }
6460 }
6461
6462 sub git_summary {
6463 my $descr = git_get_project_description($project) || "none";
6464 my %co = parse_commit("HEAD");
6465 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6466 my $head = $co{'id'};
6467 my $remote_heads = gitweb_check_feature('remote_heads');
6468
6469 my $owner = git_get_project_owner($project);
6470
6471 my $refs = git_get_references();
6472 # These get_*_list functions return one more to allow us to see if
6473 # there are more ...
6474 my @taglist = git_get_tags_list(16);
6475 my @headlist = git_get_heads_list(16);
6476 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6477 my @forklist;
6478 my $check_forks = gitweb_check_feature('forks');
6479
6480 if ($check_forks) {
6481 # find forks of a project
6482 my $filter = $project;
6483 $filter =~ s/\.git$//;
6484 @forklist = git_get_projects_list($filter);
6485 # filter out forks of forks
6486 @forklist = filter_forks_from_projects_list(\@forklist)
6487 if (@forklist);
6488 }
6489
6490 git_header_html();
6491 git_print_page_nav('summary','', $head);
6492
6493 print "<div class=\"title\">&nbsp;</div>\n";
6494 print "<table class=\"projects_list\">\n" .
6495 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6496 unless ($omit_owner) {
6497 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6498 }
6499 if (defined $cd{'rfc2822'}) {
6500 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6501 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6502 }
6503
6504 # use per project git URL list in $projectroot/$project/cloneurl
6505 # or make project git URL from git base URL and project name
6506 my $url_tag = "URL";
6507 my @url_list = git_get_project_url_list($project);
6508 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6509 foreach my $git_url (@url_list) {
6510 next unless $git_url;
6511 print format_repo_url($url_tag, $git_url);
6512 $url_tag = "";
6513 }
6514
6515 # Tag cloud
6516 my $show_ctags = gitweb_check_feature('ctags');
6517 if ($show_ctags) {
6518 my $ctags = git_get_project_ctags($project);
6519 if (%$ctags) {
6520 # without ability to add tags, don't show if there are none
6521 my $cloud = git_populate_project_tagcloud($ctags);
6522 print "<tr id=\"metadata_ctags\">" .
6523 "<td>content tags</td>" .
6524 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6525 "</tr>\n";
6526 }
6527 }
6528
6529 print "</table>\n";
6530
6531 # If XSS prevention is on, we don't include README.html.
6532 # TODO: Allow a readme in some safe format.
6533 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6534 print "<div class=\"title\">readme</div>\n" .
6535 "<div class=\"readme\">\n";
6536 insert_file("$projectroot/$project/README.html");
6537 print "\n</div>\n"; # class="readme"
6538 }
6539
6540 # we need to request one more than 16 (0..15) to check if
6541 # those 16 are all
6542 my @commitlist = $head ? parse_commits("--all", 17) : ();
6543 if (@commitlist) {
6544 git_print_header_div('shortlog');
6545 git_shortlog_body(\@commitlist, 0, 15, $refs,
6546 $#commitlist <= 15 ? undef :
6547 $cgi->a({-href => href(action=>"shortlog")}, "..."), 0, 0, 0, 1);;
6548 }
6549
6550 if (@taglist) {
6551 git_print_header_div('tags');
6552 git_tags_body(\@taglist, 0, 15,
6553 $#taglist <= 15 ? undef :
6554 $cgi->a({-href => href(action=>"tags")}, "..."));
6555 }
6556
6557 if (@headlist) {
6558 git_print_header_div('heads');
6559 git_heads_body(\@headlist, $head, 0, 15,
6560 $#headlist <= 15 ? undef :
6561 $cgi->a({-href => href(action=>"heads")}, "..."));
6562 }
6563
6564 if (%remotedata) {
6565 git_print_header_div('remotes');
6566 git_remotes_body(\%remotedata, 15, $head);
6567 }
6568
6569 if (@forklist) {
6570 git_print_header_div('forks');
6571 git_project_list_body(\@forklist, 'age', 0, 15,
6572 $#forklist <= 15 ? undef :
6573 $cgi->a({-href => href(action=>"forks")}, "..."),
6574 'no_header');
6575 }
6576
6577 git_footer_html();
6578 }
6579
6580 sub git_tag {
6581 my %tag = parse_tag($hash);
6582
6583 if (! %tag) {
6584 die_error(404, "Unknown tag object");
6585 }
6586
6587 my $head = git_get_head_hash($project);
6588 git_header_html();
6589 git_print_page_nav('','', $head,undef,$head);
6590 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6591 print "<div class=\"title_text\">\n" .
6592 "<table class=\"object_header\">\n" .
6593 "<tr>\n" .
6594 "<td>object</td>\n" .
6595 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6596 $tag{'object'}) . "</td>\n" .
6597 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6598 $tag{'type'}) . "</td>\n" .
6599 "</tr>\n";
6600 if (defined($tag{'author'})) {
6601 git_print_authorship_rows(\%tag, 'author');
6602 }
6603 print "</table>\n\n" .
6604 "</div>\n";
6605 print "<div class=\"page_body\">";
6606 my $comment = $tag{'comment'};
6607 foreach my $line (@$comment) {
6608 chomp $line;
6609 print esc_html($line, -nbsp=>1) . "<br/>\n";
6610 }
6611 print "</div>\n";
6612 git_footer_html();
6613 }
6614
6615 sub git_blame_common {
6616 my $format = shift || 'porcelain';
6617 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6618 $format = 'incremental';
6619 $action = 'blame_incremental'; # for page title etc
6620 }
6621
6622 # permissions
6623 gitweb_check_feature('blame')
6624 or die_error(403, "Blame view not allowed");
6625
6626 # error checking
6627 die_error(400, "No file name given") unless $file_name;
6628 $hash_base ||= git_get_head_hash($project);
6629 die_error(404, "Couldn't find base commit") unless $hash_base;
6630 my %co = parse_commit($hash_base)
6631 or die_error(404, "Commit not found");
6632 my $ftype = "blob";
6633 if (!defined $hash) {
6634 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6635 or die_error(404, "Error looking up file");
6636 } else {
6637 $ftype = git_get_type($hash);
6638 if ($ftype !~ "blob") {
6639 die_error(400, "Object is not a blob");
6640 }
6641 }
6642
6643 my $fd;
6644 if ($format eq 'incremental') {
6645 # get file contents (as base)
6646 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6647 or die_error(500, "Open git-cat-file failed");
6648 } elsif ($format eq 'data') {
6649 # run git-blame --incremental
6650 open $fd, "-|", git_cmd(), "blame", "--incremental",
6651 $hash_base, "--", $file_name
6652 or die_error(500, "Open git-blame --incremental failed");
6653 } else {
6654 # run git-blame --porcelain
6655 open $fd, "-|", git_cmd(), "blame", '-p',
6656 $hash_base, '--', $file_name
6657 or die_error(500, "Open git-blame --porcelain failed");
6658 }
6659
6660 # incremental blame data returns early
6661 if ($format eq 'data') {
6662 print $cgi->header(
6663 -type=>"text/plain", -charset => "utf-8",
6664 -status=> "200 OK");
6665 local $| = 1; # output autoflush
6666 while (my $line = <$fd>) {
6667 print to_utf8($line);
6668 }
6669 close $fd
6670 or print "ERROR $!\n";
6671
6672 print 'END';
6673 if (defined $t0 && gitweb_check_feature('timed')) {
6674 print ' '.
6675 tv_interval($t0, [ gettimeofday() ]).
6676 ' '.$number_of_git_cmds;
6677 }
6678 print "\n";
6679
6680 return;
6681 }
6682
6683 # page header
6684 git_header_html();
6685 my $formats_nav =
6686 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6687 "blob") .
6688 " | ";
6689 if ($format eq 'incremental') {
6690 $formats_nav .=
6691 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6692 "blame") . " (non-incremental)";
6693 } else {
6694 $formats_nav .=
6695 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6696 "blame") . " (incremental)";
6697 }
6698 $formats_nav .=
6699 " | " .
6700 $cgi->a({-href => href(action=>"history", -replay=>1)},
6701 "history") .
6702 " | " .
6703 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6704 "HEAD");
6705 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6706 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6707 git_print_page_path($file_name, $ftype, $hash_base);
6708
6709 # page body
6710 if ($format eq 'incremental') {
6711 print "<noscript>\n<div class=\"error\"><center><b>\n".
6712 "This page requires JavaScript to run.\n Use ".
6713 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6714 'this page').
6715 " instead.\n".
6716 "</b></center></div>\n</noscript>\n";
6717
6718 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6719 }
6720
6721 print qq!<div class="page_body">\n!;
6722 print qq!<div id="progress_info">... / ...</div>\n!
6723 if ($format eq 'incremental');
6724 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6725 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6726 qq!<thead>\n!.
6727 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6728 qq!</thead>\n!.
6729 qq!<tbody>\n!;
6730
6731 my @rev_color = qw(light dark);
6732 my $num_colors = scalar(@rev_color);
6733 my $current_color = 0;
6734
6735 if ($format eq 'incremental') {
6736 my $color_class = $rev_color[$current_color];
6737
6738 #contents of a file
6739 my $linenr = 0;
6740 LINE:
6741 while (my $line = <$fd>) {
6742 chomp $line;
6743 $linenr++;
6744
6745 print qq!<tr id="l$linenr" class="$color_class">!.
6746 qq!<td class="sha1"><a href=""> </a></td>!.
6747 qq!<td class="linenr">!.
6748 qq!<a class="linenr" href="">$linenr</a></td>!;
6749 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6750 print qq!</tr>\n!;
6751 }
6752
6753 } else { # porcelain, i.e. ordinary blame
6754 my %metainfo = (); # saves information about commits
6755
6756 # blame data
6757 LINE:
6758 while (my $line = <$fd>) {
6759 chomp $line;
6760 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6761 # no <lines in group> for subsequent lines in group of lines
6762 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6763 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6764 if (!exists $metainfo{$full_rev}) {
6765 $metainfo{$full_rev} = { 'nprevious' => 0 };
6766 }
6767 my $meta = $metainfo{$full_rev};
6768 my $data;
6769 while ($data = <$fd>) {
6770 chomp $data;
6771 last if ($data =~ s/^\t//); # contents of line
6772 if ($data =~ /^(\S+)(?: (.*))?$/) {
6773 $meta->{$1} = $2 unless exists $meta->{$1};
6774 }
6775 if ($data =~ /^previous /) {
6776 $meta->{'nprevious'}++;
6777 }
6778 }
6779 my $short_rev = substr($full_rev, 0, 8);
6780 my $author = $meta->{'author'};
6781 my %date =
6782 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6783 my $date = $date{'iso-tz'};
6784 if ($group_size) {
6785 $current_color = ($current_color + 1) % $num_colors;
6786 }
6787 my $tr_class = $rev_color[$current_color];
6788 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6789 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6790 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6791 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6792 if ($group_size) {
6793 print "<td class=\"sha1\"";
6794 print " title=\"". esc_html($author) . ", $date\"";
6795 print " rowspan=\"$group_size\"" if ($group_size > 1);
6796 print ">";
6797 print $cgi->a({-href => href(action=>"commit",
6798 hash=>$full_rev,
6799 file_name=>$file_name)},
6800 esc_html($short_rev));
6801 if ($group_size >= 2) {
6802 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6803 if (@author_initials) {
6804 print "<br />" .
6805 esc_html(join('', @author_initials));
6806 # or join('.', ...)
6807 }
6808 }
6809 print "</td>\n";
6810 }
6811 # 'previous' <sha1 of parent commit> <filename at commit>
6812 if (exists $meta->{'previous'} &&
6813 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6814 $meta->{'parent'} = $1;
6815 $meta->{'file_parent'} = unquote($2);
6816 }
6817 my $linenr_commit =
6818 exists($meta->{'parent'}) ?
6819 $meta->{'parent'} : $full_rev;
6820 my $linenr_filename =
6821 exists($meta->{'file_parent'}) ?
6822 $meta->{'file_parent'} : unquote($meta->{'filename'});
6823 my $blamed = href(action => 'blame',
6824 file_name => $linenr_filename,
6825 hash_base => $linenr_commit);
6826 print "<td class=\"linenr\">";
6827 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6828 -class => "linenr" },
6829 esc_html($lineno));
6830 print "</td>";
6831 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6832 print "</tr>\n";
6833 } # end while
6834
6835 }
6836
6837 # footer
6838 print "</tbody>\n".
6839 "</table>\n"; # class="blame"
6840 print "</div>\n"; # class="blame_body"
6841 close $fd
6842 or print "Reading blob failed\n";
6843
6844 git_footer_html();
6845 }
6846
6847 sub git_blame {
6848 git_blame_common();
6849 }
6850
6851 sub git_blame_incremental {
6852 git_blame_common('incremental');
6853 }
6854
6855 sub git_blame_data {
6856 git_blame_common('data');
6857 }
6858
6859 sub git_tags {
6860 my $head = git_get_head_hash($project);
6861 git_header_html();
6862 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6863 git_print_header_div('summary', $project);
6864
6865 my @tagslist = git_get_tags_list();
6866 if (@tagslist) {
6867 git_tags_body(\@tagslist);
6868 }
6869 git_footer_html();
6870 }
6871
6872 sub git_heads {
6873 my $head = git_get_head_hash($project);
6874 git_header_html();
6875 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6876 git_print_header_div('summary', $project);
6877
6878 my @headslist = git_get_heads_list();
6879 if (@headslist) {
6880 git_heads_body(\@headslist, $head);
6881 }
6882 git_footer_html();
6883 }
6884
6885 # used both for single remote view and for list of all the remotes
6886 sub git_remotes {
6887 gitweb_check_feature('remote_heads')
6888 or die_error(403, "Remote heads view is disabled");
6889
6890 my $head = git_get_head_hash($project);
6891 my $remote = $input_params{'hash'};
6892
6893 my $remotedata = git_get_remotes_list($remote);
6894 die_error(500, "Unable to get remote information") unless defined $remotedata;
6895
6896 unless (%$remotedata) {
6897 die_error(404, defined $remote ?
6898 "Remote $remote not found" :
6899 "No remotes found");
6900 }
6901
6902 git_header_html(undef, undef, -action_extra => $remote);
6903 git_print_page_nav('', '', $head, undef, $head,
6904 format_ref_views($remote ? '' : 'remotes'));
6905
6906 fill_remote_heads($remotedata);
6907 if (defined $remote) {
6908 git_print_header_div('remotes', "$remote remote for $project");
6909 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6910 } else {
6911 git_print_header_div('summary', "$project remotes");
6912 git_remotes_body($remotedata, undef, $head);
6913 }
6914
6915 git_footer_html();
6916 }
6917
6918 sub git_blob_plain {
6919 my $type = shift;
6920 my $expires;
6921
6922 if (!defined $hash) {
6923 if (defined $file_name) {
6924 my $base = $hash_base || git_get_head_hash($project);
6925 $hash = git_get_hash_by_path($base, $file_name, "blob")
6926 or die_error(404, "Cannot find file");
6927 } else {
6928 die_error(400, "No file name defined");
6929 }
6930 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6931 # blobs defined by non-textual hash id's can be cached
6932 $expires = "+1d";
6933 }
6934
6935 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6936 or die_error(500, "Open git-cat-file blob '$hash' failed");
6937
6938 # content-type (can include charset)
6939 $type = blob_contenttype($fd, $file_name, $type);
6940
6941 # "save as" filename, even when no $file_name is given
6942 my $save_as = "$hash";
6943 if (defined $file_name) {
6944 $save_as = $file_name;
6945 } elsif ($type =~ m/^text\//) {
6946 $save_as .= '.txt';
6947 }
6948
6949 # With XSS prevention on, blobs of all types except a few known safe
6950 # ones are served with "Content-Disposition: attachment" to make sure
6951 # they don't run in our security domain. For certain image types,
6952 # blob view writes an <img> tag referring to blob_plain view, and we
6953 # want to be sure not to break that by serving the image as an
6954 # attachment (though Firefox 3 doesn't seem to care).
6955 my $sandbox = $prevent_xss &&
6956 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
6957
6958 # serve text/* as text/plain
6959 if ($prevent_xss &&
6960 ($type =~ m!^text/[a-z]+\b(.*)$! ||
6961 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
6962 my $rest = $1;
6963 $rest = defined $rest ? $rest : '';
6964 $type = "text/plain$rest";
6965 }
6966
6967 print $cgi->header(
6968 -type => $type,
6969 -expires => $expires,
6970 -content_disposition =>
6971 ($sandbox ? 'attachment' : 'inline')
6972 . '; filename="' . $save_as . '"');
6973 local $/ = undef;
6974 binmode STDOUT, ':raw';
6975 print <$fd>;
6976 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6977 close $fd;
6978 }
6979
6980 sub git_blob {
6981 my $expires;
6982
6983 if (!defined $hash) {
6984 if (defined $file_name) {
6985 my $base = $hash_base || git_get_head_hash($project);
6986 $hash = git_get_hash_by_path($base, $file_name, "blob")
6987 or die_error(404, "Cannot find file");
6988 } else {
6989 die_error(400, "No file name defined");
6990 }
6991 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6992 # blobs defined by non-textual hash id's can be cached
6993 $expires = "+1d";
6994 }
6995
6996 my $have_blame = gitweb_check_feature('blame');
6997 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6998 or die_error(500, "Couldn't cat $file_name, $hash");
6999 my $mimetype = blob_mimetype($fd, $file_name);
7000 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7001 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7002 close $fd;
7003 return git_blob_plain($mimetype);
7004 }
7005 # we can have blame only for text/* mimetype
7006 $have_blame &&= ($mimetype =~ m!^text/!);
7007
7008 my $highlight = gitweb_check_feature('highlight');
7009 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7010 $fd = run_highlighter($fd, $highlight, $syntax)
7011 if $syntax;
7012
7013 git_header_html(undef, $expires);
7014 my $formats_nav = '';
7015 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7016 if (defined $file_name) {
7017 if ($have_blame) {
7018 $formats_nav .=
7019 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7020 "blame") .
7021 " | ";
7022 }
7023 $formats_nav .=
7024 $cgi->a({-href => href(action=>"history", -replay=>1)},
7025 "history") .
7026 " | " .
7027 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7028 "raw") .
7029 " | " .
7030 $cgi->a({-href => href(action=>"blob",
7031 hash_base=>"HEAD", file_name=>$file_name)},
7032 "HEAD");
7033 } else {
7034 $formats_nav .=
7035 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7036 "raw");
7037 }
7038 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7039 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7040 } else {
7041 print "<div class=\"page_nav\">\n" .
7042 "<br/><br/></div>\n" .
7043 "<div class=\"title\">".esc_html($hash)."</div>\n";
7044 }
7045 git_print_page_path($file_name, "blob", $hash_base);
7046 print "<div class=\"page_body\">\n";
7047 if ($mimetype =~ m!^image/!) {
7048 print qq!<img type="!.esc_attr($mimetype).qq!"!;
7049 if ($file_name) {
7050 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7051 }
7052 print qq! src="! .
7053 href(action=>"blob_plain", hash=>$hash,
7054 hash_base=>$hash_base, file_name=>$file_name) .
7055 qq!" />\n!;
7056 } else {
7057 my $nr;
7058 while (my $line = <$fd>) {
7059 chomp $line;
7060 $nr++;
7061 $line = untabify($line);
7062 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7063 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7064 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7065 }
7066 }
7067 close $fd
7068 or print "Reading blob failed.\n";
7069 print "</div>";
7070 git_footer_html();
7071 }
7072
7073 sub git_tree {
7074 if (!defined $hash_base) {
7075 $hash_base = "HEAD";
7076 }
7077 if (!defined $hash) {
7078 if (defined $file_name) {
7079 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7080 } else {
7081 $hash = $hash_base;
7082 }
7083 }
7084 die_error(404, "No such tree") unless defined($hash);
7085
7086 my $show_sizes = gitweb_check_feature('show-sizes');
7087 my $have_blame = gitweb_check_feature('blame');
7088
7089 my @entries = ();
7090 {
7091 local $/ = "\0";
7092 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7093 ($show_sizes ? '-l' : ()), @extra_options, $hash
7094 or die_error(500, "Open git-ls-tree failed");
7095 @entries = map { chomp; $_ } <$fd>;
7096 close $fd
7097 or die_error(404, "Reading tree failed");
7098 }
7099
7100 my $refs = git_get_references();
7101 my $ref = format_ref_marker($refs, $hash_base);
7102 git_header_html();
7103 my $basedir = '';
7104 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7105 my @views_nav = ();
7106 if (defined $file_name) {
7107 push @views_nav,
7108 $cgi->a({-href => href(action=>"history", -replay=>1)},
7109 "history"),
7110 $cgi->a({-href => href(action=>"tree",
7111 hash_base=>"HEAD", file_name=>$file_name)},
7112 "HEAD"),
7113 }
7114 my $snapshot_links = format_snapshot_links($hash);
7115 if (defined $snapshot_links) {
7116 # FIXME: Should be available when we have no hash base as well.
7117 push @views_nav, $snapshot_links;
7118 }
7119 git_print_page_nav('tree','', $hash_base, undef, undef,
7120 join(' | ', @views_nav));
7121 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7122 } else {
7123 undef $hash_base;
7124 print "<div class=\"page_nav\">\n";
7125 print "<br/><br/></div>\n";
7126 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7127 }
7128 if (defined $file_name) {
7129 $basedir = $file_name;
7130 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7131 $basedir .= '/';
7132 }
7133 git_print_page_path($file_name, 'tree', $hash_base);
7134 }
7135 print "<div class=\"page_body\">\n";
7136 print "<table class=\"tree\">\n";
7137 my $alternate = 1;
7138 # '..' (top directory) link if possible
7139 if (defined $hash_base &&
7140 defined $file_name && $file_name =~ m![^/]+$!) {
7141 if ($alternate) {
7142 print "<tr class=\"dark\">\n";
7143 } else {
7144 print "<tr class=\"light\">\n";
7145 }
7146 $alternate ^= 1;
7147
7148 my $up = $file_name;
7149 $up =~ s!/?[^/]+$!!;
7150 undef $up unless $up;
7151 # based on git_print_tree_entry
7152 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7153 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7154 print '<td class="list">';
7155 print $cgi->a({-href => href(action=>"tree",
7156 hash_base=>$hash_base,
7157 file_name=>$up)},
7158 "..");
7159 print "</td>\n";
7160 print "<td class=\"link\"></td>\n";
7161
7162 print "</tr>\n";
7163 }
7164 foreach my $line (@entries) {
7165 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7166
7167 if ($alternate) {
7168 print "<tr class=\"dark\">\n";
7169 } else {
7170 print "<tr class=\"light\">\n";
7171 }
7172 $alternate ^= 1;
7173
7174 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7175
7176 print "</tr>\n";
7177 }
7178 print "</table>\n" .
7179 "</div>";
7180 git_footer_html();
7181 }
7182
7183 sub snapshot_name {
7184 my ($project, $hash) = @_;
7185
7186 # path/to/project.git -> project
7187 # path/to/project/.git -> project
7188 my $name = to_utf8($project);
7189 $name =~ s,([^/])/*\.git$,$1,;
7190 $name = basename($name);
7191 # sanitize name
7192 $name =~ s/[[:cntrl:]]/?/g;
7193
7194 my $ver = $hash;
7195 if ($hash =~ /^[0-9a-fA-F]+$/) {
7196 # shorten SHA-1 hash
7197 my $full_hash = git_get_full_hash($project, $hash);
7198 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7199 $ver = git_get_short_hash($project, $hash);
7200 }
7201 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7202 # tags don't need shortened SHA-1 hash
7203 $ver = $1;
7204 } else {
7205 # branches and other need shortened SHA-1 hash
7206 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
7207 $ver = $1;
7208 }
7209 $ver .= '-' . git_get_short_hash($project, $hash);
7210 }
7211 # in case of hierarchical branch names
7212 $ver =~ s!/!.!g;
7213
7214 # name = project-version_string
7215 $name = "$name-$ver";
7216
7217 return wantarray ? ($name, $name) : $name;
7218 }
7219
7220 sub exit_if_unmodified_since {
7221 my ($latest_epoch) = @_;
7222 our $cgi;
7223
7224 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7225 if (defined $if_modified) {
7226 my $since;
7227 if (eval { require HTTP::Date; 1; }) {
7228 $since = HTTP::Date::str2time($if_modified);
7229 } elsif (eval { require Time::ParseDate; 1; }) {
7230 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7231 }
7232 if (defined $since && $latest_epoch <= $since) {
7233 my %latest_date = parse_date($latest_epoch);
7234 print $cgi->header(
7235 -last_modified => $latest_date{'rfc2822'},
7236 -status => '304 Not Modified');
7237 goto DONE_GITWEB;
7238 }
7239 }
7240 }
7241
7242 sub git_snapshot {
7243 my $format = $input_params{'snapshot_format'};
7244 if (!@snapshot_fmts) {
7245 die_error(403, "Snapshots not allowed");
7246 }
7247 # default to first supported snapshot format
7248 $format ||= $snapshot_fmts[0];
7249 if ($format !~ m/^[a-z0-9]+$/) {
7250 die_error(400, "Invalid snapshot format parameter");
7251 } elsif (!exists($known_snapshot_formats{$format})) {
7252 die_error(400, "Unknown snapshot format");
7253 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7254 die_error(403, "Snapshot format not allowed");
7255 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7256 die_error(403, "Unsupported snapshot format");
7257 }
7258
7259 my $type = git_get_type("$hash^{}");
7260 if (!$type) {
7261 die_error(404, 'Object does not exist');
7262 } elsif ($type eq 'blob') {
7263 die_error(400, 'Object is not a tree-ish');
7264 }
7265
7266 my ($name, $prefix) = snapshot_name($project, $hash);
7267 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7268
7269 my %co = parse_commit($hash);
7270 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7271
7272 my $cmd = quote_command(
7273 git_cmd(), 'archive',
7274 "--format=$known_snapshot_formats{$format}{'format'}",
7275 "--prefix=$prefix/", $hash);
7276 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7277 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7278 }
7279
7280 $filename =~ s/(["\\])/\\$1/g;
7281 my %latest_date;
7282 if (%co) {
7283 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7284 }
7285
7286 print $cgi->header(
7287 -type => $known_snapshot_formats{$format}{'type'},
7288 -content_disposition => 'inline; filename="' . $filename . '"',
7289 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7290 -status => '200 OK');
7291
7292 open my $fd, "-|", $cmd
7293 or die_error(500, "Execute git-archive failed");
7294 binmode STDOUT, ':raw';
7295 print <$fd>;
7296 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7297 close $fd;
7298 }
7299
7300 sub git_log_generic {
7301 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7302
7303 my $head = git_get_head_hash($project);
7304 my $allrefs;
7305 if (!defined $base) {
7306 $base = $head;
7307 $allrefs = 1;
7308 }
7309 if (!defined $page) {
7310 $page = 0;
7311 }
7312 my $refs = git_get_references();
7313
7314 my $commit_hash = $base;
7315 if (defined $allrefs) {
7316 $commit_hash = "--all";
7317 }
7318 if (defined $parent) {
7319 $commit_hash = "$parent..$base";
7320 }
7321 my @commitlist =
7322 parse_commits($commit_hash, 101, (100 * $page),
7323 defined $file_name ? ($file_name, "--full-history") : ());
7324
7325 my $ftype;
7326 if (!defined $file_hash && defined $file_name) {
7327 # some commits could have deleted file in question,
7328 # and not have it in tree, but one of them has to have it
7329 for (my $i = 0; $i < @commitlist; $i++) {
7330 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7331 last if defined $file_hash;
7332 }
7333 }
7334 if (defined $file_hash) {
7335 $ftype = git_get_type($file_hash);
7336 }
7337 if (defined $file_name && !defined $ftype) {
7338 die_error(500, "Unknown type of object");
7339 }
7340 my %co;
7341 if (defined $file_name) {
7342 %co = parse_commit($base)
7343 or die_error(404, "Unknown commit object");
7344 }
7345
7346
7347 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7348 my $next_link = '';
7349 if ($#commitlist >= 100) {
7350 $next_link =
7351 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7352 -accesskey => "n", -title => "Alt-n"}, "next");
7353 }
7354 my $patch_max = gitweb_get_feature('patches');
7355 if ($patch_max && !defined $file_name) {
7356 if ($patch_max < 0 || @commitlist <= $patch_max) {
7357 $paging_nav .= " &sdot; " .
7358 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7359 "patches");
7360 }
7361 }
7362
7363 git_header_html();
7364 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7365 if (defined $file_name) {
7366 git_print_header_div('commit', esc_html($co{'title'}), $base);
7367 } else {
7368 git_print_header_div('summary', $project)
7369 }
7370 git_print_page_path($file_name, $ftype, $hash_base)
7371 if (defined $file_name);
7372
7373 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7374 $file_name, $file_hash, $ftype, $allrefs);
7375
7376 git_footer_html();
7377 }
7378
7379 sub git_log {
7380 git_log_generic('log', \&git_log_body,
7381 $hash, $hash_parent);
7382 }
7383
7384 sub git_commit {
7385 $hash ||= $hash_base || "HEAD";
7386 my %co = parse_commit($hash)
7387 or die_error(404, "Unknown commit object");
7388
7389 my $parent = $co{'parent'};
7390 my $parents = $co{'parents'}; # listref
7391
7392 # we need to prepare $formats_nav before any parameter munging
7393 my $formats_nav;
7394 if (!defined $parent) {
7395 # --root commitdiff
7396 $formats_nav .= '(initial)';
7397 } elsif (@$parents == 1) {
7398 # single parent commit
7399 $formats_nav .=
7400 '(parent: ' .
7401 $cgi->a({-href => href(action=>"commit",
7402 hash=>$parent)},
7403 esc_html(substr($parent, 0, 7))) .
7404 ')';
7405 } else {
7406 # merge commit
7407 $formats_nav .=
7408 '(merge: ' .
7409 join(' ', map {
7410 $cgi->a({-href => href(action=>"commit",
7411 hash=>$_)},
7412 esc_html(substr($_, 0, 7)));
7413 } @$parents ) .
7414 ')';
7415 }
7416 if (gitweb_check_feature('patches') && @$parents <= 1) {
7417 $formats_nav .= " | " .
7418 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7419 "patch");
7420 }
7421
7422 if (!defined $parent) {
7423 $parent = "--root";
7424 }
7425 my @difftree;
7426 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7427 @diff_opts,
7428 (@$parents <= 1 ? $parent : '-c'),
7429 $hash, "--"
7430 or die_error(500, "Open git-diff-tree failed");
7431 @difftree = map { chomp; $_ } <$fd>;
7432 close $fd or die_error(404, "Reading git-diff-tree failed");
7433
7434 # non-textual hash id's can be cached
7435 my $expires;
7436 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7437 $expires = "+1d";
7438 }
7439 my $refs = git_get_references();
7440 my $ref = format_ref_marker($refs, $co{'id'});
7441
7442 git_header_html(undef, $expires);
7443 git_print_page_nav('commit', '',
7444 $hash, $co{'tree'}, $hash,
7445 $formats_nav);
7446
7447 if (defined $co{'parent'}) {
7448 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7449 } else {
7450 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7451 }
7452 print "<div class=\"title_text\">\n" .
7453 "<table class=\"object_header\">\n";
7454 git_print_authorship_rows(\%co);
7455 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7456 print "<tr>" .
7457 "<td>tree</td>" .
7458 "<td class=\"sha1\">" .
7459 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7460 class => "list"}, $co{'tree'}) .
7461 "</td>" .
7462 "<td class=\"link\">" .
7463 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7464 "tree");
7465 my $snapshot_links = format_snapshot_links($hash);
7466 if (defined $snapshot_links) {
7467 print " | " . $snapshot_links;
7468 }
7469 print "</td>" .
7470 "</tr>\n";
7471
7472 foreach my $par (@$parents) {
7473 print "<tr>" .
7474 "<td>parent</td>" .
7475 "<td class=\"sha1\">" .
7476 $cgi->a({-href => href(action=>"commit", hash=>$par),
7477 class => "list"}, $par) .
7478 "</td>" .
7479 "<td class=\"link\">" .
7480 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7481 " | " .
7482 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7483 "</td>" .
7484 "</tr>\n";
7485 }
7486 print "</table>".
7487 "</div>\n";
7488
7489 print "<div class=\"page_body\">\n";
7490 git_print_log($co{'comment'});
7491 print "</div>\n";
7492
7493 git_difftree_body(\@difftree, $hash, @$parents);
7494
7495 git_footer_html();
7496 }
7497
7498 sub git_object {
7499 # object is defined by:
7500 # - hash or hash_base alone
7501 # - hash_base and file_name
7502 my $type;
7503
7504 # - hash or hash_base alone
7505 if ($hash || ($hash_base && !defined $file_name)) {
7506 my $object_id = $hash || $hash_base;
7507
7508 open my $fd, "-|", quote_command(
7509 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7510 or die_error(404, "Object does not exist");
7511 $type = <$fd>;
7512 chomp $type;
7513 close $fd
7514 or die_error(404, "Object does not exist");
7515
7516 # - hash_base and file_name
7517 } elsif ($hash_base && defined $file_name) {
7518 $file_name =~ s,/+$,,;
7519
7520 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7521 or die_error(404, "Base object does not exist");
7522
7523 # here errors should not hapen
7524 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7525 or die_error(500, "Open git-ls-tree failed");
7526 my $line = <$fd>;
7527 close $fd;
7528
7529 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7530 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7531 die_error(404, "File or directory for given base does not exist");
7532 }
7533 $type = $2;
7534 $hash = $3;
7535 } else {
7536 die_error(400, "Not enough information to find object");
7537 }
7538
7539 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7540 hash=>$hash, hash_base=>$hash_base,
7541 file_name=>$file_name),
7542 -status => '302 Found');
7543 }
7544
7545 sub git_blobdiff {
7546 my $format = shift || 'html';
7547 my $diff_style = $input_params{'diff_style'} || 'inline';
7548
7549 my $fd;
7550 my @difftree;
7551 my %diffinfo;
7552 my $expires;
7553
7554 # preparing $fd and %diffinfo for git_patchset_body
7555 # new style URI
7556 if (defined $hash_base && defined $hash_parent_base) {
7557 if (defined $file_name) {
7558 # read raw output
7559 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7560 $hash_parent_base, $hash_base,
7561 "--", (defined $file_parent ? $file_parent : ()), $file_name
7562 or die_error(500, "Open git-diff-tree failed");
7563 @difftree = map { chomp; $_ } <$fd>;
7564 close $fd
7565 or die_error(404, "Reading git-diff-tree failed");
7566 @difftree
7567 or die_error(404, "Blob diff not found");
7568
7569 } elsif (defined $hash &&
7570 $hash =~ /[0-9a-fA-F]{40}/) {
7571 # try to find filename from $hash
7572
7573 # read filtered raw output
7574 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7575 $hash_parent_base, $hash_base, "--"
7576 or die_error(500, "Open git-diff-tree failed");
7577 @difftree =
7578 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7579 # $hash == to_id
7580 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7581 map { chomp; $_ } <$fd>;
7582 close $fd
7583 or die_error(404, "Reading git-diff-tree failed");
7584 @difftree
7585 or die_error(404, "Blob diff not found");
7586
7587 } else {
7588 die_error(400, "Missing one of the blob diff parameters");
7589 }
7590
7591 if (@difftree > 1) {
7592 die_error(400, "Ambiguous blob diff specification");
7593 }
7594
7595 %diffinfo = parse_difftree_raw_line($difftree[0]);
7596 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7597 $file_name ||= $diffinfo{'to_file'};
7598
7599 $hash_parent ||= $diffinfo{'from_id'};
7600 $hash ||= $diffinfo{'to_id'};
7601
7602 # non-textual hash id's can be cached
7603 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7604 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7605 $expires = '+1d';
7606 }
7607
7608 # open patch output
7609 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7610 '-p', ($format eq 'html' ? "--full-index" : ()),
7611 $hash_parent_base, $hash_base,
7612 "--", (defined $file_parent ? $file_parent : ()), $file_name
7613 or die_error(500, "Open git-diff-tree failed");
7614 }
7615
7616 # old/legacy style URI -- not generated anymore since 1.4.3.
7617 if (!%diffinfo) {
7618 die_error('404 Not Found', "Missing one of the blob diff parameters")
7619 }
7620
7621 # header
7622 if ($format eq 'html') {
7623 my $formats_nav =
7624 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7625 "raw");
7626 $formats_nav .= diff_style_nav($diff_style);
7627 git_header_html(undef, $expires);
7628 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7629 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7630 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7631 } else {
7632 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7633 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7634 }
7635 if (defined $file_name) {
7636 git_print_page_path($file_name, "blob", $hash_base);
7637 } else {
7638 print "<div class=\"page_path\"></div>\n";
7639 }
7640
7641 } elsif ($format eq 'plain') {
7642 print $cgi->header(
7643 -type => 'text/plain',
7644 -charset => 'utf-8',
7645 -expires => $expires,
7646 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7647
7648 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7649
7650 } else {
7651 die_error(400, "Unknown blobdiff format");
7652 }
7653
7654 # patch
7655 if ($format eq 'html') {
7656 print "<div class=\"page_body\">\n";
7657
7658 git_patchset_body($fd, $diff_style,
7659 [ \%diffinfo ], $hash_base, $hash_parent_base);
7660 close $fd;
7661
7662 print "</div>\n"; # class="page_body"
7663 git_footer_html();
7664
7665 } else {
7666 while (my $line = <$fd>) {
7667 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7668 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7669
7670 print $line;
7671
7672 last if $line =~ m!^\+\+\+!;
7673 }
7674 local $/ = undef;
7675 print <$fd>;
7676 close $fd;
7677 }
7678 }
7679
7680 sub git_blobdiff_plain {
7681 git_blobdiff('plain');
7682 }
7683
7684 # assumes that it is added as later part of already existing navigation,
7685 # so it returns "| foo | bar" rather than just "foo | bar"
7686 sub diff_style_nav {
7687 my ($diff_style, $is_combined) = @_;
7688 $diff_style ||= 'inline';
7689
7690 return "" if ($is_combined);
7691
7692 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7693 my %styles = @styles;
7694 @styles =
7695 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7696
7697 return join '',
7698 map { " | ".$_ }
7699 map {
7700 $_ eq $diff_style ? $styles{$_} :
7701 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7702 } @styles;
7703 }
7704
7705 sub git_commitdiff {
7706 my %params = @_;
7707 my $format = $params{-format} || 'html';
7708 my $diff_style = $input_params{'diff_style'} || 'inline';
7709
7710 my ($patch_max) = gitweb_get_feature('patches');
7711 if ($format eq 'patch') {
7712 die_error(403, "Patch view not allowed") unless $patch_max;
7713 }
7714
7715 $hash ||= $hash_base || "HEAD";
7716 my %co = parse_commit($hash)
7717 or die_error(404, "Unknown commit object");
7718
7719 # choose format for commitdiff for merge
7720 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7721 $hash_parent = '--cc';
7722 }
7723 # we need to prepare $formats_nav before almost any parameter munging
7724 my $formats_nav;
7725 if ($format eq 'html') {
7726 $formats_nav =
7727 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7728 "raw");
7729 if ($patch_max && @{$co{'parents'}} <= 1) {
7730 $formats_nav .= " | " .
7731 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7732 "patch");
7733 }
7734 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7735
7736 if (defined $hash_parent &&
7737 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7738 # commitdiff with two commits given
7739 my $hash_parent_short = $hash_parent;
7740 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7741 $hash_parent_short = substr($hash_parent, 0, 7);
7742 }
7743 $formats_nav .=
7744 ' (from';
7745 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7746 if ($co{'parents'}[$i] eq $hash_parent) {
7747 $formats_nav .= ' parent ' . ($i+1);
7748 last;
7749 }
7750 }
7751 $formats_nav .= ': ' .
7752 $cgi->a({-href => href(-replay=>1,
7753 hash=>$hash_parent, hash_base=>undef)},
7754 esc_html($hash_parent_short)) .
7755 ')';
7756 } elsif (!$co{'parent'}) {
7757 # --root commitdiff
7758 $formats_nav .= ' (initial)';
7759 } elsif (scalar @{$co{'parents'}} == 1) {
7760 # single parent commit
7761 $formats_nav .=
7762 ' (parent: ' .
7763 $cgi->a({-href => href(-replay=>1,
7764 hash=>$co{'parent'}, hash_base=>undef)},
7765 esc_html(substr($co{'parent'}, 0, 7))) .
7766 ')';
7767 } else {
7768 # merge commit
7769 if ($hash_parent eq '--cc') {
7770 $formats_nav .= ' | ' .
7771 $cgi->a({-href => href(-replay=>1,
7772 hash=>$hash, hash_parent=>'-c')},
7773 'combined');
7774 } else { # $hash_parent eq '-c'
7775 $formats_nav .= ' | ' .
7776 $cgi->a({-href => href(-replay=>1,
7777 hash=>$hash, hash_parent=>'--cc')},
7778 'compact');
7779 }
7780 $formats_nav .=
7781 ' (merge: ' .
7782 join(' ', map {
7783 $cgi->a({-href => href(-replay=>1,
7784 hash=>$_, hash_base=>undef)},
7785 esc_html(substr($_, 0, 7)));
7786 } @{$co{'parents'}} ) .
7787 ')';
7788 }
7789 }
7790
7791 my $hash_parent_param = $hash_parent;
7792 if (!defined $hash_parent_param) {
7793 # --cc for multiple parents, --root for parentless
7794 $hash_parent_param =
7795 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7796 }
7797
7798 # read commitdiff
7799 my $fd;
7800 my @difftree;
7801 if ($format eq 'html') {
7802 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7803 "--no-commit-id", "--patch-with-raw", "--full-index",
7804 $hash_parent_param, $hash, "--"
7805 or die_error(500, "Open git-diff-tree failed");
7806
7807 while (my $line = <$fd>) {
7808 chomp $line;
7809 # empty line ends raw part of diff-tree output
7810 last unless $line;
7811 push @difftree, scalar parse_difftree_raw_line($line);
7812 }
7813
7814 } elsif ($format eq 'plain') {
7815 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7816 '-p', $hash_parent_param, $hash, "--"
7817 or die_error(500, "Open git-diff-tree failed");
7818 } elsif ($format eq 'patch') {
7819 # For commit ranges, we limit the output to the number of
7820 # patches specified in the 'patches' feature.
7821 # For single commits, we limit the output to a single patch,
7822 # diverging from the git-format-patch default.
7823 my @commit_spec = ();
7824 if ($hash_parent) {
7825 if ($patch_max > 0) {
7826 push @commit_spec, "-$patch_max";
7827 }
7828 push @commit_spec, '-n', "$hash_parent..$hash";
7829 } else {
7830 if ($params{-single}) {
7831 push @commit_spec, '-1';
7832 } else {
7833 if ($patch_max > 0) {
7834 push @commit_spec, "-$patch_max";
7835 }
7836 push @commit_spec, "-n";
7837 }
7838 push @commit_spec, '--root', $hash;
7839 }
7840 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7841 '--encoding=utf8', '--stdout', @commit_spec
7842 or die_error(500, "Open git-format-patch failed");
7843 } else {
7844 die_error(400, "Unknown commitdiff format");
7845 }
7846
7847 # non-textual hash id's can be cached
7848 my $expires;
7849 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7850 $expires = "+1d";
7851 }
7852
7853 # write commit message
7854 if ($format eq 'html') {
7855 my $refs = git_get_references();
7856 my $ref = format_ref_marker($refs, $co{'id'});
7857
7858 git_header_html(undef, $expires);
7859 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7860 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7861 print "<div class=\"title_text\">\n" .
7862 "<table class=\"object_header\">\n";
7863 git_print_authorship_rows(\%co);
7864 print "</table>".
7865 "</div>\n";
7866 print "<div class=\"page_body\">\n";
7867 if (@{$co{'comment'}} > 1) {
7868 print "<div class=\"log\">\n";
7869 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7870 print "</div>\n"; # class="log"
7871 }
7872
7873 } elsif ($format eq 'plain') {
7874 my $refs = git_get_references("tags");
7875 my $tagname = git_get_rev_name_tags($hash);
7876 my $filename = basename($project) . "-$hash.patch";
7877
7878 print $cgi->header(
7879 -type => 'text/plain',
7880 -charset => 'utf-8',
7881 -expires => $expires,
7882 -content_disposition => 'inline; filename="' . "$filename" . '"');
7883 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7884 print "From: " . to_utf8($co{'author'}) . "\n";
7885 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7886 print "Subject: " . to_utf8($co{'title'}) . "\n";
7887
7888 print "X-Git-Tag: $tagname\n" if $tagname;
7889 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7890
7891 foreach my $line (@{$co{'comment'}}) {
7892 print to_utf8($line) . "\n";
7893 }
7894 print "---\n\n";
7895 } elsif ($format eq 'patch') {
7896 my $filename = basename($project) . "-$hash.patch";
7897
7898 print $cgi->header(
7899 -type => 'text/plain',
7900 -charset => 'utf-8',
7901 -expires => $expires,
7902 -content_disposition => 'inline; filename="' . "$filename" . '"');
7903 }
7904
7905 # write patch
7906 if ($format eq 'html') {
7907 my $use_parents = !defined $hash_parent ||
7908 $hash_parent eq '-c' || $hash_parent eq '--cc';
7909 git_difftree_body(\@difftree, $hash,
7910 $use_parents ? @{$co{'parents'}} : $hash_parent);
7911 print "<br/>\n";
7912
7913 git_patchset_body($fd, $diff_style,
7914 \@difftree, $hash,
7915 $use_parents ? @{$co{'parents'}} : $hash_parent);
7916 close $fd;
7917 print "</div>\n"; # class="page_body"
7918 git_footer_html();
7919
7920 } elsif ($format eq 'plain') {
7921 local $/ = undef;
7922 print <$fd>;
7923 close $fd
7924 or print "Reading git-diff-tree failed\n";
7925 } elsif ($format eq 'patch') {
7926 local $/ = undef;
7927 print <$fd>;
7928 close $fd
7929 or print "Reading git-format-patch failed\n";
7930 }
7931 }
7932
7933 sub git_commitdiff_plain {
7934 git_commitdiff(-format => 'plain');
7935 }
7936
7937 # format-patch-style patches
7938 sub git_patch {
7939 git_commitdiff(-format => 'patch', -single => 1);
7940 }
7941
7942 sub git_patches {
7943 git_commitdiff(-format => 'patch');
7944 }
7945
7946 sub git_history {
7947 git_log_generic('history', \&git_history_body,
7948 $hash_base, $hash_parent_base,
7949 $file_name, $hash);
7950 }
7951
7952 sub git_search {
7953 $searchtype ||= 'commit';
7954
7955 # check if appropriate features are enabled
7956 gitweb_check_feature('search')
7957 or die_error(403, "Search is disabled");
7958 if ($searchtype eq 'pickaxe') {
7959 # pickaxe may take all resources of your box and run for several minutes
7960 # with every query - so decide by yourself how public you make this feature
7961 gitweb_check_feature('pickaxe')
7962 or die_error(403, "Pickaxe search is disabled");
7963 }
7964 if ($searchtype eq 'grep') {
7965 # grep search might be potentially CPU-intensive, too
7966 gitweb_check_feature('grep')
7967 or die_error(403, "Grep search is disabled");
7968 }
7969
7970 if (!defined $searchtext) {
7971 die_error(400, "Text field is empty");
7972 }
7973 if (!defined $hash) {
7974 $hash = git_get_head_hash($project);
7975 }
7976 my %co = parse_commit($hash);
7977 if (!%co) {
7978 die_error(404, "Unknown commit object");
7979 }
7980 if (!defined $page) {
7981 $page = 0;
7982 }
7983
7984 if ($searchtype eq 'commit' ||
7985 $searchtype eq 'author' ||
7986 $searchtype eq 'committer') {
7987 git_search_message(%co);
7988 } elsif ($searchtype eq 'pickaxe') {
7989 git_search_changes(%co);
7990 } elsif ($searchtype eq 'grep') {
7991 git_search_files(%co);
7992 } else {
7993 die_error(400, "Unknown search type");
7994 }
7995 }
7996
7997 sub git_search_help {
7998 git_header_html();
7999 git_print_page_nav('','', $hash,$hash,$hash);
8000 print <<EOT;
8001 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8002 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8003 the pattern entered is recognized as the POSIX extended
8004 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8005 insensitive).</p>
8006 <dl>
8007 <dt><b>commit</b></dt>
8008 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8009 EOT
8010 my $have_grep = gitweb_check_feature('grep');
8011 if ($have_grep) {
8012 print <<EOT;
8013 <dt><b>grep</b></dt>
8014 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8015 a different one) are searched for the given pattern. On large trees, this search can take
8016 a while and put some strain on the server, so please use it with some consideration. Note that
8017 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8018 case-sensitive.</dd>
8019 EOT
8020 }
8021 print <<EOT;
8022 <dt><b>author</b></dt>
8023 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8024 <dt><b>committer</b></dt>
8025 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8026 EOT
8027 my $have_pickaxe = gitweb_check_feature('pickaxe');
8028 if ($have_pickaxe) {
8029 print <<EOT;
8030 <dt><b>pickaxe</b></dt>
8031 <dd>All commits that caused the string to appear or disappear from any file (changes that
8032 added, removed or "modified" the string) will be listed. This search can take a while and
8033 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8034 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8035 EOT
8036 }
8037 print "</dl>\n";
8038 git_footer_html();
8039 }
8040
8041 sub git_shortlog {
8042 git_log_generic('shortlog', \&git_shortlog_body,
8043 $hash, $hash_parent);
8044 }
8045
8046 ## ......................................................................
8047 ## feeds (RSS, Atom; OPML)
8048
8049 sub git_feed {
8050 my $format = shift || 'atom';
8051 my $have_blame = gitweb_check_feature('blame');
8052
8053 # Atom: http://www.atomenabled.org/developers/syndication/
8054 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8055 if ($format ne 'rss' && $format ne 'atom') {
8056 die_error(400, "Unknown web feed format");
8057 }
8058
8059 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8060 my $head = $hash || 'HEAD';
8061 my @commitlist = parse_commits($head, 150, 0, $file_name);
8062
8063 my %latest_commit;
8064 my %latest_date;
8065 my $content_type = "application/$format+xml";
8066 if (defined $cgi->http('HTTP_ACCEPT') &&
8067 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8068 # browser (feed reader) prefers text/xml
8069 $content_type = 'text/xml';
8070 }
8071 if (defined($commitlist[0])) {
8072 %latest_commit = %{$commitlist[0]};
8073 my $latest_epoch = $latest_commit{'committer_epoch'};
8074 exit_if_unmodified_since($latest_epoch);
8075 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8076 }
8077 print $cgi->header(
8078 -type => $content_type,
8079 -charset => 'utf-8',
8080 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8081 -status => '200 OK');
8082
8083 # Optimization: skip generating the body if client asks only
8084 # for Last-Modified date.
8085 return if ($cgi->request_method() eq 'HEAD');
8086
8087 # header variables
8088 my $title = "$site_name - $project/$action";
8089 my $feed_type = 'log';
8090 if (defined $hash) {
8091 $title .= " - '$hash'";
8092 $feed_type = 'branch log';
8093 if (defined $file_name) {
8094 $title .= " :: $file_name";
8095 $feed_type = 'history';
8096 }
8097 } elsif (defined $file_name) {
8098 $title .= " - $file_name";
8099 $feed_type = 'history';
8100 }
8101 $title .= " $feed_type";
8102 $title = esc_html($title);
8103 my $descr = git_get_project_description($project);
8104 if (defined $descr) {
8105 $descr = esc_html($descr);
8106 } else {
8107 $descr = "$project " .
8108 ($format eq 'rss' ? 'RSS' : 'Atom') .
8109 " feed";
8110 }
8111 my $owner = git_get_project_owner($project);
8112 $owner = esc_html($owner);
8113
8114 #header
8115 my $alt_url;
8116 if (defined $file_name) {
8117 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8118 } elsif (defined $hash) {
8119 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8120 } else {
8121 $alt_url = href(-full=>1, action=>"summary");
8122 }
8123 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8124 if ($format eq 'rss') {
8125 print <<XML;
8126 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8127 <channel>
8128 XML
8129 print "<title>$title</title>\n" .
8130 "<link>$alt_url</link>\n" .
8131 "<description>$descr</description>\n" .
8132 "<language>en</language>\n" .
8133 # project owner is responsible for 'editorial' content
8134 "<managingEditor>$owner</managingEditor>\n";
8135 if (defined $logo || defined $favicon) {
8136 # prefer the logo to the favicon, since RSS
8137 # doesn't allow both
8138 my $img = esc_url($logo || $favicon);
8139 print "<image>\n" .
8140 "<url>$img</url>\n" .
8141 "<title>$title</title>\n" .
8142 "<link>$alt_url</link>\n" .
8143 "</image>\n";
8144 }
8145 if (%latest_date) {
8146 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8147 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8148 }
8149 print "<generator>gitweb v.$version/$git_version</generator>\n";
8150 } elsif ($format eq 'atom') {
8151 print <<XML;
8152 <feed xmlns="http://www.w3.org/2005/Atom">
8153 XML
8154 print "<title>$title</title>\n" .
8155 "<subtitle>$descr</subtitle>\n" .
8156 '<link rel="alternate" type="text/html" href="' .
8157 $alt_url . '" />' . "\n" .
8158 '<link rel="self" type="' . $content_type . '" href="' .
8159 $cgi->self_url() . '" />' . "\n" .
8160 "<id>" . href(-full=>1) . "</id>\n" .
8161 # use project owner for feed author
8162 "<author><name>$owner</name></author>\n";
8163 if (defined $favicon) {
8164 print "<icon>" . esc_url($favicon) . "</icon>\n";
8165 }
8166 if (defined $logo) {
8167 # not twice as wide as tall: 72 x 27 pixels
8168 print "<logo>" . esc_url($logo) . "</logo>\n";
8169 }
8170 if (! %latest_date) {
8171 # dummy date to keep the feed valid until commits trickle in:
8172 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8173 } else {
8174 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8175 }
8176 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8177 }
8178
8179 # contents
8180 for (my $i = 0; $i <= $#commitlist; $i++) {
8181 my %co = %{$commitlist[$i]};
8182 my $commit = $co{'id'};
8183 # we read 150, we always show 30 and the ones more recent than 48 hours
8184 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8185 last;
8186 }
8187 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8188
8189 # get list of changed files
8190 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8191 $co{'parent'} || "--root",
8192 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8193 or next;
8194 my @difftree = map { chomp; $_ } <$fd>;
8195 close $fd
8196 or next;
8197
8198 # print element (entry, item)
8199 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8200 if ($format eq 'rss') {
8201 print "<item>\n" .
8202 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8203 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8204 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8205 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8206 "<link>$co_url</link>\n" .
8207 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8208 "<content:encoded>" .
8209 "<![CDATA[\n";
8210 } elsif ($format eq 'atom') {
8211 print "<entry>\n" .
8212 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8213 "<updated>$cd{'iso-8601'}</updated>\n" .
8214 "<author>\n" .
8215 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8216 if ($co{'author_email'}) {
8217 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8218 }
8219 print "</author>\n" .
8220 # use committer for contributor
8221 "<contributor>\n" .
8222 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8223 if ($co{'committer_email'}) {
8224 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8225 }
8226 print "</contributor>\n" .
8227 "<published>$cd{'iso-8601'}</published>\n" .
8228 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8229 "<id>$co_url</id>\n" .
8230 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8231 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8232 }
8233 my $comment = $co{'comment'};
8234 print "<pre>\n";
8235 foreach my $line (@$comment) {
8236 $line = esc_html($line);
8237 print "$line\n";
8238 }
8239 print "</pre><ul>\n";
8240 foreach my $difftree_line (@difftree) {
8241 my %difftree = parse_difftree_raw_line($difftree_line);
8242 next if !$difftree{'from_id'};
8243
8244 my $file = $difftree{'file'} || $difftree{'to_file'};
8245
8246 print "<li>" .
8247 "[" .
8248 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8249 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8250 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8251 file_name=>$file, file_parent=>$difftree{'from_file'}),
8252 -title => "diff"}, 'D');
8253 if ($have_blame) {
8254 print $cgi->a({-href => href(-full=>1, action=>"blame",
8255 file_name=>$file, hash_base=>$commit),
8256 -title => "blame"}, 'B');
8257 }
8258 # if this is not a feed of a file history
8259 if (!defined $file_name || $file_name ne $file) {
8260 print $cgi->a({-href => href(-full=>1, action=>"history",
8261 file_name=>$file, hash=>$commit),
8262 -title => "history"}, 'H');
8263 }
8264 $file = esc_path($file);
8265 print "] ".
8266 "$file</li>\n";
8267 }
8268 if ($format eq 'rss') {
8269 print "</ul>]]>\n" .
8270 "</content:encoded>\n" .
8271 "</item>\n";
8272 } elsif ($format eq 'atom') {
8273 print "</ul>\n</div>\n" .
8274 "</content>\n" .
8275 "</entry>\n";
8276 }
8277 }
8278
8279 # end of feed
8280 if ($format eq 'rss') {
8281 print "</channel>\n</rss>\n";
8282 } elsif ($format eq 'atom') {
8283 print "</feed>\n";
8284 }
8285 }
8286
8287 sub git_rss {
8288 git_feed('rss');
8289 }
8290
8291 sub git_atom {
8292 git_feed('atom');
8293 }
8294
8295 sub git_opml {
8296 my @list = git_get_projects_list($project_filter, $strict_export);
8297 if (!@list) {
8298 die_error(404, "No projects found");
8299 }
8300
8301 print $cgi->header(
8302 -type => 'text/xml',
8303 -charset => 'utf-8',
8304 -content_disposition => 'inline; filename="opml.xml"');
8305
8306 my $title = esc_html($site_name);
8307 my $filter = " within subdirectory ";
8308 if (defined $project_filter) {
8309 $filter .= esc_html($project_filter);
8310 } else {
8311 $filter = "";
8312 }
8313 print <<XML;
8314 <?xml version="1.0" encoding="utf-8"?>
8315 <opml version="1.0">
8316 <head>
8317 <title>$title OPML Export$filter</title>
8318 </head>
8319 <body>
8320 <outline text="git RSS feeds">
8321 XML
8322
8323 foreach my $pr (@list) {
8324 my %proj = %$pr;
8325 my $head = git_get_head_hash($proj{'path'});
8326 if (!defined $head) {
8327 next;
8328 }
8329 $git_dir = "$projectroot/$proj{'path'}";
8330 my %co = parse_commit($head);
8331 if (!%co) {
8332 next;
8333 }
8334
8335 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8336 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8337 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8338 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8339 }
8340 print <<XML;
8341 </outline>
8342 </body>
8343 </opml>
8344 XML
8345 }