]> Lady’s Gitweb - Gitweb/blob - gitweb.perl
5fe7fdcf9b4033b253ee7b62f5ed88328e1ac315bece5f2cf89ba0af68b72205
[Gitweb] / gitweb.perl
1 #!/usr/bin/perl
2
3 # gitweb - simple web interface to track changes in git repositories
4 #
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
7 #
8 # This program is licensed under the GPLv2
9
10 use 5.008;
11 use strict;
12 use warnings;
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
19 use File::Basename qw(basename);
20 use Time::HiRes qw(gettimeofday tv_interval);
21 binmode STDOUT, ':utf8';
22
23 our $t0 = [ gettimeofday() ];
24 our $number_of_git_cmds = 0;
25
26 BEGIN {
27 CGI->compile() if $ENV{'MOD_PERL'};
28 }
29
30 our $version = "++GIT_VERSION++";
31
32 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
33 sub evaluate_uri {
34 our $cgi;
35
36 our $my_url = $cgi->url();
37 our $my_uri = $cgi->url(-absolute => 1);
38
39 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
40 # needed and used only for URLs with nonempty PATH_INFO
41 our $base_url = $my_url;
42
43 # When the script is used as DirectoryIndex, the URL does not contain the name
44 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
45 # have to do it ourselves. We make $path_info global because it's also used
46 # later on.
47 #
48 # Another issue with the script being the DirectoryIndex is that the resulting
49 # $my_url data is not the full script URL: this is good, because we want
50 # generated links to keep implying the script name if it wasn't explicitly
51 # indicated in the URL we're handling, but it means that $my_url cannot be used
52 # as base URL.
53 # Therefore, if we needed to strip PATH_INFO, then we know that we have
54 # to build the base URL ourselves:
55 our $path_info = decode_utf8($ENV{"PATH_INFO"});
56 if ($path_info) {
57 # $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 = "++GIT_BINDIR++/git";
76
77 # absolute fs-path which will be prepended to the project path
78 #our $projectroot = "/pub/scm";
79 our $projectroot = "++GITWEB_PROJECTROOT++";
80
81 # fs traversing limit for getting project list
82 # the number is relative to the projectroot
83 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
84
85 # string of the home link on top of all pages
86 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
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 = "++GITWEB_SITENAME++"
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 = "++GITWEB_SITE_HTML_HEAD_STRING++";
95 # filename of html text to include at top of each page
96 our $site_header = "++GITWEB_SITE_HEADER++";
97 # html text to include at home page
98 our $home_text = "++GITWEB_HOMETEXT++";
99 # filename of html text to include at bottom of each page
100 our $site_footer = "++GITWEB_SITE_FOOTER++";
101
102 # URI of stylesheets
103 our @stylesheets = ("++GITWEB_CSS++");
104 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
105 our $stylesheet = undef;
106
107 # URI of GIT logo (72x27 size)
108 our $logo = "++GITWEB_LOGO++";
109 # URI of GIT favicon, assumed to be image/png type
110 our $favicon = "++GITWEB_FAVICON++";
111 # URI of gitweb.js (JavaScript code for gitweb)
112 our $javascript = "++GITWEB_JS++";
113
114 # URI and label (title) of GIT logo link
115 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
116 #our $logo_label = "git documentation";
117 our $logo_url = "http://git-scm.com/";
118 our $logo_label = "git homepage";
119
120 # source of projects list
121 our $projects_list = "++GITWEB_LIST++";
122
123 # the width (in characters) of the projects list "Description" column
124 our $projects_list_description_width = 25;
125
126 # group projects by category on the projects list
127 # (enabled if this variable evaluates to true)
128 our $projects_list_group_categories = 0;
129
130 # default category if none specified
131 # (leave the empty string for no category)
132 our $project_list_default_category = "";
133
134 # default order of projects list
135 # valid values are none, project, descr, owner, and age
136 our $default_projects_order = "project";
137
138 # show repository only if this file exists
139 # (only effective if this variable evaluates to true)
140 our $export_ok = "++GITWEB_EXPORT_OK++";
141
142 # don't generate age column on the projects list page
143 our $omit_age_column = 0;
144
145 # don't generate information about owners of repositories
146 our $omit_owner=0;
147
148 # show repository only if this subroutine returns true
149 # when given the path to the project, for example:
150 # sub { return -e "$_[0]/git-daemon-export-ok"; }
151 our $export_auth_hook = undef;
152
153 # only allow viewing of repositories also shown on the overview page
154 our $strict_export = "++GITWEB_STRICT_EXPORT++";
155
156 # list of git base URLs used for URL to where fetch project from,
157 # i.e. full URL is "$git_base_url/$project"
158 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
159
160 # default blob_plain mimetype and default charset for text/plain blob
161 our $default_blob_plain_mimetype = 'text/plain';
162 our $default_text_plain_charset = undef;
163
164 # file to use for guessing MIME types before trying /etc/mime.types
165 # (relative to the current git repository)
166 our $mimetypes_file = undef;
167
168 # assume this charset if line contains non-UTF-8 characters;
169 # it should be valid encoding (see Encoding::Supported(3pm) for list),
170 # for which encoding all byte sequences are valid, for example
171 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
172 # could be even 'utf-8' for the old behavior)
173 our $fallback_encoding = 'latin1';
174
175 # rename detection options for git-diff and git-diff-tree
176 # - default is '-M', with the cost proportional to
177 # (number of removed files) * (number of new files).
178 # - more costly is '-C' (which implies '-M'), with the cost proportional to
179 # (number of changed files + number of removed files) * (number of new files)
180 # - even more costly is '-C', '--find-copies-harder' with cost
181 # (number of files in the original tree) * (number of new files)
182 # - one might want to include '-B' option, e.g. '-B', '-M'
183 our @diff_opts = ('-M'); # taken from git_commit
184
185 # Disables features that would allow repository owners to inject script into
186 # the gitweb domain.
187 our $prevent_xss = 0;
188
189 # Path to the highlight executable to use (must be the one from
190 # http://www.andre-simon.de due to assumptions about parameters and output).
191 # Useful if highlight is not installed on your webserver's PATH.
192 # [Default: highlight]
193 our $highlight_bin = "++HIGHLIGHT_BIN++";
194
195 # information about snapshot formats that gitweb is capable of serving
196 our %known_snapshot_formats = (
197 # name => {
198 # 'display' => display name,
199 # 'type' => mime type,
200 # 'suffix' => filename suffix,
201 # 'format' => --format for git-archive,
202 # 'compressor' => [compressor command and arguments]
203 # (array reference, optional)
204 # 'disabled' => boolean (optional)}
205 #
206 'tgz' => {
207 'display' => 'tar.gz',
208 'type' => 'application/x-gzip',
209 'suffix' => '.tar.gz',
210 'format' => 'tar',
211 'compressor' => ['gzip', '-n']},
212
213 'tbz2' => {
214 'display' => 'tar.bz2',
215 'type' => 'application/x-bzip2',
216 'suffix' => '.tar.bz2',
217 'format' => 'tar',
218 'compressor' => ['bzip2']},
219
220 'txz' => {
221 'display' => 'tar.xz',
222 'type' => 'application/x-xz',
223 'suffix' => '.tar.xz',
224 'format' => 'tar',
225 'compressor' => ['xz'],
226 'disabled' => 1},
227
228 'zip' => {
229 'display' => 'zip',
230 'type' => 'application/x-zip',
231 'suffix' => '.zip',
232 'format' => 'zip'},
233 );
234
235 # Aliases so we understand old gitweb.snapshot values in repository
236 # configuration.
237 our %known_snapshot_format_aliases = (
238 'gzip' => 'tgz',
239 'bzip2' => 'tbz2',
240 'xz' => 'txz',
241
242 # backward compatibility: legacy gitweb config support
243 'x-gzip' => undef, 'gz' => undef,
244 'x-bzip2' => undef, 'bz2' => undef,
245 'x-zip' => undef, '' => undef,
246 );
247
248 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
249 # are changed, it may be appropriate to change these values too via
250 # $GITWEB_CONFIG.
251 our %avatar_size = (
252 'default' => 16,
253 'double' => 32
254 );
255
256 # Used to set the maximum load that we will still respond to gitweb queries.
257 # If server load exceed this value then return "503 server busy" error.
258 # If gitweb cannot determined server load, it is taken to be 0.
259 # Leave it undefined (or set to 'undef') to turn off load checking.
260 our $maxload = 300;
261
262 # configuration for 'highlight' (http://www.andre-simon.de/)
263 # match by basename
264 our %highlight_basename = (
265 #'Program' => 'py',
266 #'Library' => 'py',
267 'SConstruct' => 'py', # SCons equivalent of Makefile
268 'Makefile' => 'make',
269 );
270 # match by extension
271 our %highlight_ext = (
272 # main extensions, defining name of syntax;
273 # see files in /usr/share/highlight/langDefs/ directory
274 map { $_ => $_ }
275 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make),
276 # alternate extensions, see /etc/highlight/filetypes.conf
277 'h' => 'c',
278 map { $_ => 'sh' } qw(bash zsh ksh),
279 map { $_ => 'cpp' } qw(cxx c++ cc),
280 map { $_ => 'php' } qw(php3 php4 php5 phps),
281 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
282 map { $_ => 'make'} qw(mak mk),
283 map { $_ => 'xml' } qw(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.remote_heads = 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++";
685 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
686 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
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:]])|($1 =~ /[\t\n\r]/ ? $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 $key = join(".", lc($hi), $mi, lc($lo));
2702 } else {
2703 $key = lc($key);
2704 }
2705 $key =~ s/^gitweb\.//;
2706 return if ($key =~ m/\W/);
2707
2708 # type sanity check
2709 if (defined $type) {
2710 $type =~ s/^--//;
2711 $type = undef
2712 unless ($type eq 'bool' || $type eq 'int');
2713 }
2714
2715 # get config
2716 if (!defined $config_file ||
2717 $config_file ne "$git_dir/config") {
2718 %config = git_parse_project_config('gitweb');
2719 $config_file = "$git_dir/config";
2720 }
2721
2722 # check if config variable (key) exists
2723 return unless exists $config{"gitweb.$key"};
2724
2725 # ensure given type
2726 if (!defined $type) {
2727 return $config{"gitweb.$key"};
2728 } elsif ($type eq 'bool') {
2729 # backward compatibility: 'git config --bool' returns true/false
2730 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2731 } elsif ($type eq 'int') {
2732 return config_to_int($config{"gitweb.$key"});
2733 }
2734 return $config{"gitweb.$key"};
2735 }
2736
2737 # get hash of given path at given ref
2738 sub git_get_hash_by_path {
2739 my $base = shift;
2740 my $path = shift || return undef;
2741 my $type = shift;
2742
2743 $path =~ s,/+$,,;
2744
2745 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2746 or die_error(500, "Open git-ls-tree failed");
2747 my $line = <$fd>;
2748 close $fd or return undef;
2749
2750 if (!defined $line) {
2751 # there is no tree or hash given by $path at $base
2752 return undef;
2753 }
2754
2755 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2756 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2757 if (defined $type && $type ne $2) {
2758 # type doesn't match
2759 return undef;
2760 }
2761 return $3;
2762 }
2763
2764 # get path of entry with given hash at given tree-ish (ref)
2765 # used to get 'from' filename for combined diff (merge commit) for renames
2766 sub git_get_path_by_hash {
2767 my $base = shift || return;
2768 my $hash = shift || return;
2769
2770 local $/ = "\0";
2771
2772 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2773 or return undef;
2774 while (my $line = <$fd>) {
2775 chomp $line;
2776
2777 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2778 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2779 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2780 close $fd;
2781 return $1;
2782 }
2783 }
2784 close $fd;
2785 return undef;
2786 }
2787
2788 ## ......................................................................
2789 ## git utility functions, directly accessing git repository
2790
2791 # get the value of config variable either from file named as the variable
2792 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2793 # configuration variable in the repository config file.
2794 sub git_get_file_or_project_config {
2795 my ($path, $name) = @_;
2796
2797 $git_dir = "$projectroot/$path";
2798 open my $fd, '<', "$git_dir/$name"
2799 or return git_get_project_config($name);
2800 my $conf = <$fd>;
2801 close $fd;
2802 if (defined $conf) {
2803 chomp $conf;
2804 }
2805 return $conf;
2806 }
2807
2808 sub git_get_project_description {
2809 my $path = shift;
2810 return git_get_file_or_project_config($path, 'description');
2811 }
2812
2813 sub git_get_project_category {
2814 my $path = shift;
2815 return git_get_file_or_project_config($path, 'category');
2816 }
2817
2818
2819 # supported formats:
2820 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2821 # - if its contents is a number, use it as tag weight,
2822 # - otherwise add a tag with weight 1
2823 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2824 # the same value multiple times increases tag weight
2825 # * `gitweb.ctag' multi-valued repo config variable
2826 sub git_get_project_ctags {
2827 my $project = shift;
2828 my $ctags = {};
2829
2830 $git_dir = "$projectroot/$project";
2831 if (opendir my $dh, "$git_dir/ctags") {
2832 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2833 foreach my $tagfile (@files) {
2834 open my $ct, '<', $tagfile
2835 or next;
2836 my $val = <$ct>;
2837 chomp $val if $val;
2838 close $ct;
2839
2840 (my $ctag = $tagfile) =~ s#.*/##;
2841 if ($val =~ /^\d+$/) {
2842 $ctags->{$ctag} = $val;
2843 } else {
2844 $ctags->{$ctag} = 1;
2845 }
2846 }
2847 closedir $dh;
2848
2849 } elsif (open my $fh, '<', "$git_dir/ctags") {
2850 while (my $line = <$fh>) {
2851 chomp $line;
2852 $ctags->{$line}++ if $line;
2853 }
2854 close $fh;
2855
2856 } else {
2857 my $taglist = config_to_multi(git_get_project_config('ctag'));
2858 foreach my $tag (@$taglist) {
2859 $ctags->{$tag}++;
2860 }
2861 }
2862
2863 return $ctags;
2864 }
2865
2866 # return hash, where keys are content tags ('ctags'),
2867 # and values are sum of weights of given tag in every project
2868 sub git_gather_all_ctags {
2869 my $projects = shift;
2870 my $ctags = {};
2871
2872 foreach my $p (@$projects) {
2873 foreach my $ct (keys %{$p->{'ctags'}}) {
2874 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2875 }
2876 }
2877
2878 return $ctags;
2879 }
2880
2881 sub git_populate_project_tagcloud {
2882 my $ctags = shift;
2883
2884 # First, merge different-cased tags; tags vote on casing
2885 my %ctags_lc;
2886 foreach (keys %$ctags) {
2887 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2888 if (not $ctags_lc{lc $_}->{topcount}
2889 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2890 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2891 $ctags_lc{lc $_}->{topname} = $_;
2892 }
2893 }
2894
2895 my $cloud;
2896 my $matched = $input_params{'ctag'};
2897 if (eval { require HTML::TagCloud; 1; }) {
2898 $cloud = HTML::TagCloud->new;
2899 foreach my $ctag (sort keys %ctags_lc) {
2900 # Pad the title with spaces so that the cloud looks
2901 # less crammed.
2902 my $title = esc_html($ctags_lc{$ctag}->{topname});
2903 $title =~ s/ /&nbsp;/g;
2904 $title =~ s/^/&nbsp;/g;
2905 $title =~ s/$/&nbsp;/g;
2906 if (defined $matched && $matched eq $ctag) {
2907 $title = qq(<span class="match">$title</span>);
2908 }
2909 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2910 $ctags_lc{$ctag}->{count});
2911 }
2912 } else {
2913 $cloud = {};
2914 foreach my $ctag (keys %ctags_lc) {
2915 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
2916 if (defined $matched && $matched eq $ctag) {
2917 $title = qq(<span class="match">$title</span>);
2918 }
2919 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
2920 $cloud->{$ctag}{ctag} =
2921 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
2922 }
2923 }
2924 return $cloud;
2925 }
2926
2927 sub git_show_project_tagcloud {
2928 my ($cloud, $count) = @_;
2929 if (ref $cloud eq 'HTML::TagCloud') {
2930 return $cloud->html_and_css($count);
2931 } else {
2932 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
2933 return
2934 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
2935 join (', ', map {
2936 $cloud->{$_}->{'ctag'}
2937 } splice(@tags, 0, $count)) .
2938 '</div>';
2939 }
2940 }
2941
2942 sub git_get_project_url_list {
2943 my $path = shift;
2944
2945 $git_dir = "$projectroot/$path";
2946 open my $fd, '<', "$git_dir/cloneurl"
2947 or return wantarray ?
2948 @{ config_to_multi(git_get_project_config('url')) } :
2949 config_to_multi(git_get_project_config('url'));
2950 my @git_project_url_list = map { chomp; $_ } <$fd>;
2951 close $fd;
2952
2953 return wantarray ? @git_project_url_list : \@git_project_url_list;
2954 }
2955
2956 sub git_get_projects_list {
2957 my $filter = shift || '';
2958 my $paranoid = shift;
2959 my @list;
2960
2961 if (-d $projects_list) {
2962 # search in directory
2963 my $dir = $projects_list;
2964 # remove the trailing "/"
2965 $dir =~ s!/+$!!;
2966 my $pfxlen = length("$dir");
2967 my $pfxdepth = ($dir =~ tr!/!!);
2968 # when filtering, search only given subdirectory
2969 if ($filter && !$paranoid) {
2970 $dir .= "/$filter";
2971 $dir =~ s!/+$!!;
2972 }
2973
2974 File::Find::find({
2975 follow_fast => 1, # follow symbolic links
2976 follow_skip => 2, # ignore duplicates
2977 dangling_symlinks => 0, # ignore dangling symlinks, silently
2978 wanted => sub {
2979 # global variables
2980 our $project_maxdepth;
2981 our $projectroot;
2982 # skip project-list toplevel, if we get it.
2983 return if (m!^[/.]$!);
2984 # only directories can be git repositories
2985 return unless (-d $_);
2986 # don't traverse too deep (Find is super slow on os x)
2987 # $project_maxdepth excludes depth of $projectroot
2988 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2989 $File::Find::prune = 1;
2990 return;
2991 }
2992
2993 my $path = substr($File::Find::name, $pfxlen + 1);
2994 # paranoidly only filter here
2995 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
2996 next;
2997 }
2998 # we check related file in $projectroot
2999 if (check_export_ok("$projectroot/$path")) {
3000 push @list, { path => $path };
3001 $File::Find::prune = 1;
3002 }
3003 },
3004 }, "$dir");
3005
3006 } elsif (-f $projects_list) {
3007 # read from file(url-encoded):
3008 # 'git%2Fgit.git Linus+Torvalds'
3009 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3010 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3011 open my $fd, '<', $projects_list or return;
3012 PROJECT:
3013 while (my $line = <$fd>) {
3014 chomp $line;
3015 my ($path, $owner) = split ' ', $line;
3016 $path = unescape($path);
3017 $owner = unescape($owner);
3018 if (!defined $path) {
3019 next;
3020 }
3021 # if $filter is rpovided, check if $path begins with $filter
3022 if ($filter && $path !~ m!^\Q$filter\E/!) {
3023 next;
3024 }
3025 if (check_export_ok("$projectroot/$path")) {
3026 my $pr = {
3027 path => $path
3028 };
3029 if ($owner) {
3030 $pr->{'owner'} = to_utf8($owner);
3031 }
3032 push @list, $pr;
3033 }
3034 }
3035 close $fd;
3036 }
3037 return @list;
3038 }
3039
3040 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3041 # as side effects it sets 'forks' field to list of forks for forked projects
3042 sub filter_forks_from_projects_list {
3043 my $projects = shift;
3044
3045 my %trie; # prefix tree of directories (path components)
3046 # generate trie out of those directories that might contain forks
3047 foreach my $pr (@$projects) {
3048 my $path = $pr->{'path'};
3049 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3050 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3051 next unless ($path); # skip '.git' repository: tests, git-instaweb
3052 next unless (-d "$projectroot/$path"); # containing directory exists
3053 $pr->{'forks'} = []; # there can be 0 or more forks of project
3054
3055 # add to trie
3056 my @dirs = split('/', $path);
3057 # walk the trie, until either runs out of components or out of trie
3058 my $ref = \%trie;
3059 while (scalar @dirs &&
3060 exists($ref->{$dirs[0]})) {
3061 $ref = $ref->{shift @dirs};
3062 }
3063 # create rest of trie structure from rest of components
3064 foreach my $dir (@dirs) {
3065 $ref = $ref->{$dir} = {};
3066 }
3067 # create end marker, store $pr as a data
3068 $ref->{''} = $pr if (!exists $ref->{''});
3069 }
3070
3071 # filter out forks, by finding shortest prefix match for paths
3072 my @filtered;
3073 PROJECT:
3074 foreach my $pr (@$projects) {
3075 # trie lookup
3076 my $ref = \%trie;
3077 DIR:
3078 foreach my $dir (split('/', $pr->{'path'})) {
3079 if (exists $ref->{''}) {
3080 # found [shortest] prefix, is a fork - skip it
3081 push @{$ref->{''}{'forks'}}, $pr;
3082 next PROJECT;
3083 }
3084 if (!exists $ref->{$dir}) {
3085 # not in trie, cannot have prefix, not a fork
3086 push @filtered, $pr;
3087 next PROJECT;
3088 }
3089 # If the dir is there, we just walk one step down the trie.
3090 $ref = $ref->{$dir};
3091 }
3092 # we ran out of trie
3093 # (shouldn't happen: it's either no match, or end marker)
3094 push @filtered, $pr;
3095 }
3096
3097 return @filtered;
3098 }
3099
3100 # note: fill_project_list_info must be run first,
3101 # for 'descr_long' and 'ctags' to be filled
3102 sub search_projects_list {
3103 my ($projlist, %opts) = @_;
3104 my $tagfilter = $opts{'tagfilter'};
3105 my $search_re = $opts{'search_regexp'};
3106
3107 return @$projlist
3108 unless ($tagfilter || $search_re);
3109
3110 # searching projects require filling to be run before it;
3111 fill_project_list_info($projlist,
3112 $tagfilter ? 'ctags' : (),
3113 $search_re ? ('path', 'descr') : ());
3114 my @projects;
3115 PROJECT:
3116 foreach my $pr (@$projlist) {
3117
3118 if ($tagfilter) {
3119 next unless ref($pr->{'ctags'}) eq 'HASH';
3120 next unless
3121 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3122 }
3123
3124 if ($search_re) {
3125 next unless
3126 $pr->{'path'} =~ /$search_re/ ||
3127 $pr->{'descr_long'} =~ /$search_re/;
3128 }
3129
3130 push @projects, $pr;
3131 }
3132
3133 return @projects;
3134 }
3135
3136 our $gitweb_project_owner = undef;
3137 sub git_get_project_list_from_file {
3138
3139 return if (defined $gitweb_project_owner);
3140
3141 $gitweb_project_owner = {};
3142 # read from file (url-encoded):
3143 # 'git%2Fgit.git Linus+Torvalds'
3144 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3145 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3146 if (-f $projects_list) {
3147 open(my $fd, '<', $projects_list);
3148 while (my $line = <$fd>) {
3149 chomp $line;
3150 my ($pr, $ow) = split ' ', $line;
3151 $pr = unescape($pr);
3152 $ow = unescape($ow);
3153 $gitweb_project_owner->{$pr} = to_utf8($ow);
3154 }
3155 close $fd;
3156 }
3157 }
3158
3159 sub git_get_project_owner {
3160 my $project = shift;
3161 my $owner;
3162
3163 return undef unless $project;
3164 $git_dir = "$projectroot/$project";
3165
3166 if (!defined $gitweb_project_owner) {
3167 git_get_project_list_from_file();
3168 }
3169
3170 if (exists $gitweb_project_owner->{$project}) {
3171 $owner = $gitweb_project_owner->{$project};
3172 }
3173 if (!defined $owner){
3174 $owner = git_get_project_config('owner');
3175 }
3176 if (!defined $owner) {
3177 $owner = get_file_owner("$git_dir");
3178 }
3179
3180 return $owner;
3181 }
3182
3183 sub git_get_last_activity {
3184 my ($path) = @_;
3185 my $fd;
3186
3187 $git_dir = "$projectroot/$path";
3188 open($fd, "-|", git_cmd(), 'for-each-ref',
3189 '--format=%(committer)',
3190 '--sort=-committerdate',
3191 '--count=1',
3192 'refs/heads') or return;
3193 my $most_recent = <$fd>;
3194 close $fd or return;
3195 if (defined $most_recent &&
3196 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3197 my $timestamp = $1;
3198 my $age = time - $timestamp;
3199 return ($age, age_string($age));
3200 }
3201 return (undef, undef);
3202 }
3203
3204 # Implementation note: when a single remote is wanted, we cannot use 'git
3205 # remote show -n' because that command always work (assuming it's a remote URL
3206 # if it's not defined), and we cannot use 'git remote show' because that would
3207 # try to make a network roundtrip. So the only way to find if that particular
3208 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3209 # and when we find what we want.
3210 sub git_get_remotes_list {
3211 my $wanted = shift;
3212 my %remotes = ();
3213
3214 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3215 return unless $fd;
3216 while (my $remote = <$fd>) {
3217 chomp $remote;
3218 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3219 next if $wanted and not $remote eq $wanted;
3220 my ($url, $key) = ($1, $2);
3221
3222 $remotes{$remote} ||= { 'heads' => () };
3223 $remotes{$remote}{$key} = $url;
3224 }
3225 close $fd or return;
3226 return wantarray ? %remotes : \%remotes;
3227 }
3228
3229 # Takes a hash of remotes as first parameter and fills it by adding the
3230 # available remote heads for each of the indicated remotes.
3231 sub fill_remote_heads {
3232 my $remotes = shift;
3233 my @heads = map { "remotes/$_" } keys %$remotes;
3234 my @remoteheads = git_get_heads_list(undef, @heads);
3235 foreach my $remote (keys %$remotes) {
3236 $remotes->{$remote}{'heads'} = [ grep {
3237 $_->{'name'} =~ s!^$remote/!!
3238 } @remoteheads ];
3239 }
3240 }
3241
3242 sub git_get_references {
3243 my $type = shift || "";
3244 my %refs;
3245 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3246 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3247 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3248 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3249 or return;
3250
3251 while (my $line = <$fd>) {
3252 chomp $line;
3253 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3254 if (defined $refs{$1}) {
3255 push @{$refs{$1}}, $2;
3256 } else {
3257 $refs{$1} = [ $2 ];
3258 }
3259 }
3260 }
3261 close $fd or return;
3262 return \%refs;
3263 }
3264
3265 sub git_get_rev_name_tags {
3266 my $hash = shift || return undef;
3267
3268 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3269 or return;
3270 my $name_rev = <$fd>;
3271 close $fd;
3272
3273 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3274 return $1;
3275 } else {
3276 # catches also '$hash undefined' output
3277 return undef;
3278 }
3279 }
3280
3281 ## ----------------------------------------------------------------------
3282 ## parse to hash functions
3283
3284 sub parse_date {
3285 my $epoch = shift;
3286 my $tz = shift || "-0000";
3287
3288 my %date;
3289 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3290 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3291 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3292 $date{'hour'} = $hour;
3293 $date{'minute'} = $min;
3294 $date{'mday'} = $mday;
3295 $date{'day'} = $days[$wday];
3296 $date{'month'} = $months[$mon];
3297 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3298 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3299 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3300 $mday, $months[$mon], $hour ,$min;
3301 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3302 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3303
3304 my ($tz_sign, $tz_hour, $tz_min) =
3305 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3306 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3307 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3308 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3309 $date{'hour_local'} = $hour;
3310 $date{'minute_local'} = $min;
3311 $date{'tz_local'} = $tz;
3312 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3313 1900+$year, $mon+1, $mday,
3314 $hour, $min, $sec, $tz);
3315 return %date;
3316 }
3317
3318 sub parse_tag {
3319 my $tag_id = shift;
3320 my %tag;
3321 my @comment;
3322
3323 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3324 $tag{'id'} = $tag_id;
3325 while (my $line = <$fd>) {
3326 chomp $line;
3327 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3328 $tag{'object'} = $1;
3329 } elsif ($line =~ m/^type (.+)$/) {
3330 $tag{'type'} = $1;
3331 } elsif ($line =~ m/^tag (.+)$/) {
3332 $tag{'name'} = $1;
3333 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3334 $tag{'author'} = $1;
3335 $tag{'author_epoch'} = $2;
3336 $tag{'author_tz'} = $3;
3337 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3338 $tag{'author_name'} = $1;
3339 $tag{'author_email'} = $2;
3340 } else {
3341 $tag{'author_name'} = $tag{'author'};
3342 }
3343 } elsif ($line =~ m/--BEGIN/) {
3344 push @comment, $line;
3345 last;
3346 } elsif ($line eq "") {
3347 last;
3348 }
3349 }
3350 push @comment, <$fd>;
3351 $tag{'comment'} = \@comment;
3352 close $fd or return;
3353 if (!defined $tag{'name'}) {
3354 return
3355 };
3356 return %tag
3357 }
3358
3359 sub parse_commit_text {
3360 my ($commit_text, $withparents) = @_;
3361 my @commit_lines = split '\n', $commit_text;
3362 my %co;
3363
3364 pop @commit_lines; # Remove '\0'
3365
3366 if (! @commit_lines) {
3367 return;
3368 }
3369
3370 my $header = shift @commit_lines;
3371 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3372 return;
3373 }
3374 ($co{'id'}, my @parents) = split ' ', $header;
3375 while (my $line = shift @commit_lines) {
3376 last if $line eq "\n";
3377 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3378 $co{'tree'} = $1;
3379 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3380 push @parents, $1;
3381 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3382 $co{'author'} = to_utf8($1);
3383 $co{'author_epoch'} = $2;
3384 $co{'author_tz'} = $3;
3385 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3386 $co{'author_name'} = $1;
3387 $co{'author_email'} = $2;
3388 } else {
3389 $co{'author_name'} = $co{'author'};
3390 }
3391 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3392 $co{'committer'} = to_utf8($1);
3393 $co{'committer_epoch'} = $2;
3394 $co{'committer_tz'} = $3;
3395 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3396 $co{'committer_name'} = $1;
3397 $co{'committer_email'} = $2;
3398 } else {
3399 $co{'committer_name'} = $co{'committer'};
3400 }
3401 }
3402 }
3403 if (!defined $co{'tree'}) {
3404 return;
3405 };
3406 $co{'parents'} = \@parents;
3407 $co{'parent'} = $parents[0];
3408
3409 foreach my $title (@commit_lines) {
3410 $title =~ s/^ //;
3411 if ($title ne "") {
3412 $co{'title'} = chop_str($title, 80, 5);
3413 # remove leading stuff of merges to make the interesting part visible
3414 if (length($title) > 50) {
3415 $title =~ s/^Automatic //;
3416 $title =~ s/^merge (of|with) /Merge ... /i;
3417 if (length($title) > 50) {
3418 $title =~ s/(http|rsync):\/\///;
3419 }
3420 if (length($title) > 50) {
3421 $title =~ s/(master|www|rsync)\.//;
3422 }
3423 if (length($title) > 50) {
3424 $title =~ s/kernel.org:?//;
3425 }
3426 if (length($title) > 50) {
3427 $title =~ s/\/pub\/scm//;
3428 }
3429 }
3430 $co{'title_short'} = chop_str($title, 50, 5);
3431 last;
3432 }
3433 }
3434 if (! defined $co{'title'} || $co{'title'} eq "") {
3435 $co{'title'} = $co{'title_short'} = '(no commit message)';
3436 }
3437 # remove added spaces
3438 foreach my $line (@commit_lines) {
3439 $line =~ s/^ //;
3440 }
3441 $co{'comment'} = \@commit_lines;
3442
3443 my $age = time - $co{'committer_epoch'};
3444 $co{'age'} = $age;
3445 $co{'age_string'} = age_string($age);
3446 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3447 if ($age > 60*60*24*7*2) {
3448 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3449 $co{'age_string_age'} = $co{'age_string'};
3450 } else {
3451 $co{'age_string_date'} = $co{'age_string'};
3452 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3453 }
3454 return %co;
3455 }
3456
3457 sub parse_commit {
3458 my ($commit_id) = @_;
3459 my %co;
3460
3461 local $/ = "\0";
3462
3463 open my $fd, "-|", git_cmd(), "rev-list",
3464 "--parents",
3465 "--header",
3466 "--max-count=1",
3467 $commit_id,
3468 "--",
3469 or die_error(500, "Open git-rev-list failed");
3470 %co = parse_commit_text(<$fd>, 1);
3471 close $fd;
3472
3473 return %co;
3474 }
3475
3476 sub parse_commits {
3477 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3478 my @cos;
3479
3480 $maxcount ||= 1;
3481 $skip ||= 0;
3482
3483 local $/ = "\0";
3484
3485 open my $fd, "-|", git_cmd(), "rev-list",
3486 "--header",
3487 @args,
3488 ("--max-count=" . $maxcount),
3489 ("--skip=" . $skip),
3490 @extra_options,
3491 $commit_id,
3492 "--",
3493 ($filename ? ($filename) : ())
3494 or die_error(500, "Open git-rev-list failed");
3495 while (my $line = <$fd>) {
3496 my %co = parse_commit_text($line);
3497 push @cos, \%co;
3498 }
3499 close $fd;
3500
3501 return wantarray ? @cos : \@cos;
3502 }
3503
3504 # parse line of git-diff-tree "raw" output
3505 sub parse_difftree_raw_line {
3506 my $line = shift;
3507 my %res;
3508
3509 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3510 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3511 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3512 $res{'from_mode'} = $1;
3513 $res{'to_mode'} = $2;
3514 $res{'from_id'} = $3;
3515 $res{'to_id'} = $4;
3516 $res{'status'} = $5;
3517 $res{'similarity'} = $6;
3518 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3519 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3520 } else {
3521 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3522 }
3523 }
3524 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3525 # combined diff (for merge commit)
3526 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3527 $res{'nparents'} = length($1);
3528 $res{'from_mode'} = [ split(' ', $2) ];
3529 $res{'to_mode'} = pop @{$res{'from_mode'}};
3530 $res{'from_id'} = [ split(' ', $3) ];
3531 $res{'to_id'} = pop @{$res{'from_id'}};
3532 $res{'status'} = [ split('', $4) ];
3533 $res{'to_file'} = unquote($5);
3534 }
3535 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3536 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3537 $res{'commit'} = $1;
3538 }
3539
3540 return wantarray ? %res : \%res;
3541 }
3542
3543 # wrapper: return parsed line of git-diff-tree "raw" output
3544 # (the argument might be raw line, or parsed info)
3545 sub parsed_difftree_line {
3546 my $line_or_ref = shift;
3547
3548 if (ref($line_or_ref) eq "HASH") {
3549 # pre-parsed (or generated by hand)
3550 return $line_or_ref;
3551 } else {
3552 return parse_difftree_raw_line($line_or_ref);
3553 }
3554 }
3555
3556 # parse line of git-ls-tree output
3557 sub parse_ls_tree_line {
3558 my $line = shift;
3559 my %opts = @_;
3560 my %res;
3561
3562 if ($opts{'-l'}) {
3563 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3564 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3565
3566 $res{'mode'} = $1;
3567 $res{'type'} = $2;
3568 $res{'hash'} = $3;
3569 $res{'size'} = $4;
3570 if ($opts{'-z'}) {
3571 $res{'name'} = $5;
3572 } else {
3573 $res{'name'} = unquote($5);
3574 }
3575 } else {
3576 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3577 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3578
3579 $res{'mode'} = $1;
3580 $res{'type'} = $2;
3581 $res{'hash'} = $3;
3582 if ($opts{'-z'}) {
3583 $res{'name'} = $4;
3584 } else {
3585 $res{'name'} = unquote($4);
3586 }
3587 }
3588
3589 return wantarray ? %res : \%res;
3590 }
3591
3592 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3593 sub parse_from_to_diffinfo {
3594 my ($diffinfo, $from, $to, @parents) = @_;
3595
3596 if ($diffinfo->{'nparents'}) {
3597 # combined diff
3598 $from->{'file'} = [];
3599 $from->{'href'} = [];
3600 fill_from_file_info($diffinfo, @parents)
3601 unless exists $diffinfo->{'from_file'};
3602 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3603 $from->{'file'}[$i] =
3604 defined $diffinfo->{'from_file'}[$i] ?
3605 $diffinfo->{'from_file'}[$i] :
3606 $diffinfo->{'to_file'};
3607 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3608 $from->{'href'}[$i] = href(action=>"blob",
3609 hash_base=>$parents[$i],
3610 hash=>$diffinfo->{'from_id'}[$i],
3611 file_name=>$from->{'file'}[$i]);
3612 } else {
3613 $from->{'href'}[$i] = undef;
3614 }
3615 }
3616 } else {
3617 # ordinary (not combined) diff
3618 $from->{'file'} = $diffinfo->{'from_file'};
3619 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3620 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3621 hash=>$diffinfo->{'from_id'},
3622 file_name=>$from->{'file'});
3623 } else {
3624 delete $from->{'href'};
3625 }
3626 }
3627
3628 $to->{'file'} = $diffinfo->{'to_file'};
3629 if (!is_deleted($diffinfo)) { # file exists in result
3630 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3631 hash=>$diffinfo->{'to_id'},
3632 file_name=>$to->{'file'});
3633 } else {
3634 delete $to->{'href'};
3635 }
3636 }
3637
3638 ## ......................................................................
3639 ## parse to array of hashes functions
3640
3641 sub git_get_heads_list {
3642 my ($limit, @classes) = @_;
3643 @classes = ('heads') unless @classes;
3644 my @patterns = map { "refs/$_" } @classes;
3645 my @headslist;
3646
3647 open my $fd, '-|', git_cmd(), 'for-each-ref',
3648 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3649 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3650 @patterns
3651 or return;
3652 while (my $line = <$fd>) {
3653 my %ref_item;
3654
3655 chomp $line;
3656 my ($refinfo, $committerinfo) = split(/\0/, $line);
3657 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3658 my ($committer, $epoch, $tz) =
3659 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3660 $ref_item{'fullname'} = $name;
3661 $name =~ s!^refs/(?:head|remote)s/!!;
3662
3663 $ref_item{'name'} = $name;
3664 $ref_item{'id'} = $hash;
3665 $ref_item{'title'} = $title || '(no commit message)';
3666 $ref_item{'epoch'} = $epoch;
3667 if ($epoch) {
3668 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3669 } else {
3670 $ref_item{'age'} = "unknown";
3671 }
3672
3673 push @headslist, \%ref_item;
3674 }
3675 close $fd;
3676
3677 return wantarray ? @headslist : \@headslist;
3678 }
3679
3680 sub git_get_tags_list {
3681 my $limit = shift;
3682 my @tagslist;
3683
3684 open my $fd, '-|', git_cmd(), 'for-each-ref',
3685 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3686 '--format=%(objectname) %(objecttype) %(refname) '.
3687 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3688 'refs/tags'
3689 or return;
3690 while (my $line = <$fd>) {
3691 my %ref_item;
3692
3693 chomp $line;
3694 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3695 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3696 my ($creator, $epoch, $tz) =
3697 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3698 $ref_item{'fullname'} = $name;
3699 $name =~ s!^refs/tags/!!;
3700
3701 $ref_item{'type'} = $type;
3702 $ref_item{'id'} = $id;
3703 $ref_item{'name'} = $name;
3704 if ($type eq "tag") {
3705 $ref_item{'subject'} = $title;
3706 $ref_item{'reftype'} = $reftype;
3707 $ref_item{'refid'} = $refid;
3708 } else {
3709 $ref_item{'reftype'} = $type;
3710 $ref_item{'refid'} = $id;
3711 }
3712
3713 if ($type eq "tag" || $type eq "commit") {
3714 $ref_item{'epoch'} = $epoch;
3715 if ($epoch) {
3716 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3717 } else {
3718 $ref_item{'age'} = "unknown";
3719 }
3720 }
3721
3722 push @tagslist, \%ref_item;
3723 }
3724 close $fd;
3725
3726 return wantarray ? @tagslist : \@tagslist;
3727 }
3728
3729 ## ----------------------------------------------------------------------
3730 ## filesystem-related functions
3731
3732 sub get_file_owner {
3733 my $path = shift;
3734
3735 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3736 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3737 if (!defined $gcos) {
3738 return undef;
3739 }
3740 my $owner = $gcos;
3741 $owner =~ s/[,;].*$//;
3742 return to_utf8($owner);
3743 }
3744
3745 # assume that file exists
3746 sub insert_file {
3747 my $filename = shift;
3748
3749 open my $fd, '<', $filename;
3750 print map { to_utf8($_) } <$fd>;
3751 close $fd;
3752 }
3753
3754 ## ......................................................................
3755 ## mimetype related functions
3756
3757 sub mimetype_guess_file {
3758 my $filename = shift;
3759 my $mimemap = shift;
3760 -r $mimemap or return undef;
3761
3762 my %mimemap;
3763 open(my $mh, '<', $mimemap) or return undef;
3764 while (<$mh>) {
3765 next if m/^#/; # skip comments
3766 my ($mimetype, @exts) = split(/\s+/);
3767 foreach my $ext (@exts) {
3768 $mimemap{$ext} = $mimetype;
3769 }
3770 }
3771 close($mh);
3772
3773 $filename =~ /\.([^.]*)$/;
3774 return $mimemap{$1};
3775 }
3776
3777 sub mimetype_guess {
3778 my $filename = shift;
3779 my $mime;
3780 $filename =~ /\./ or return undef;
3781
3782 if ($mimetypes_file) {
3783 my $file = $mimetypes_file;
3784 if ($file !~ m!^/!) { # if it is relative path
3785 # it is relative to project
3786 $file = "$projectroot/$project/$file";
3787 }
3788 $mime = mimetype_guess_file($filename, $file);
3789 }
3790 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3791 return $mime;
3792 }
3793
3794 sub blob_mimetype {
3795 my $fd = shift;
3796 my $filename = shift;
3797
3798 if ($filename) {
3799 my $mime = mimetype_guess($filename);
3800 $mime and return $mime;
3801 }
3802
3803 # just in case
3804 return $default_blob_plain_mimetype unless $fd;
3805
3806 if (-T $fd) {
3807 return 'text/plain';
3808 } elsif (! $filename) {
3809 return 'application/octet-stream';
3810 } elsif ($filename =~ m/\.png$/i) {
3811 return 'image/png';
3812 } elsif ($filename =~ m/\.gif$/i) {
3813 return 'image/gif';
3814 } elsif ($filename =~ m/\.jpe?g$/i) {
3815 return 'image/jpeg';
3816 } else {
3817 return 'application/octet-stream';
3818 }
3819 }
3820
3821 sub blob_contenttype {
3822 my ($fd, $file_name, $type) = @_;
3823
3824 $type ||= blob_mimetype($fd, $file_name);
3825 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3826 $type .= "; charset=$default_text_plain_charset";
3827 }
3828
3829 return $type;
3830 }
3831
3832 # guess file syntax for syntax highlighting; return undef if no highlighting
3833 # the name of syntax can (in the future) depend on syntax highlighter used
3834 sub guess_file_syntax {
3835 my ($highlight, $mimetype, $file_name) = @_;
3836 return undef unless ($highlight && defined $file_name);
3837 my $basename = basename($file_name, '.in');
3838 return $highlight_basename{$basename}
3839 if exists $highlight_basename{$basename};
3840
3841 $basename =~ /\.([^.]*)$/;
3842 my $ext = $1 or return undef;
3843 return $highlight_ext{$ext}
3844 if exists $highlight_ext{$ext};
3845
3846 return undef;
3847 }
3848
3849 # run highlighter and return FD of its output,
3850 # or return original FD if no highlighting
3851 sub run_highlighter {
3852 my ($fd, $highlight, $syntax) = @_;
3853 return $fd unless ($highlight && defined $syntax);
3854
3855 close $fd;
3856 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3857 quote_command($highlight_bin).
3858 " --replace-tabs=8 --fragment --syntax $syntax |"
3859 or die_error(500, "Couldn't open file or run syntax highlighter");
3860 return $fd;
3861 }
3862
3863 ## ======================================================================
3864 ## functions printing HTML: header, footer, error page
3865
3866 sub get_page_title {
3867 my $title = to_utf8($site_name);
3868
3869 unless (defined $project) {
3870 if (defined $project_filter) {
3871 $title .= " - projects in '" . esc_path($project_filter) . "'";
3872 }
3873 return $title;
3874 }
3875 $title .= " - " . to_utf8($project);
3876
3877 return $title unless (defined $action);
3878 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3879
3880 return $title unless (defined $file_name);
3881 $title .= " - " . esc_path($file_name);
3882 if ($action eq "tree" && $file_name !~ m|/$|) {
3883 $title .= "/";
3884 }
3885
3886 return $title;
3887 }
3888
3889 sub get_content_type_html {
3890 # require explicit support from the UA if we are to send the page as
3891 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3892 # we have to do this because MSIE sometimes globs '*/*', pretending to
3893 # support xhtml+xml but choking when it gets what it asked for.
3894 if (defined $cgi->http('HTTP_ACCEPT') &&
3895 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3896 $cgi->Accept('application/xhtml+xml') != 0) {
3897 return 'application/xhtml+xml';
3898 } else {
3899 return 'text/html';
3900 }
3901 }
3902
3903 sub print_feed_meta {
3904 if (defined $project) {
3905 my %href_params = get_feed_info();
3906 if (!exists $href_params{'-title'}) {
3907 $href_params{'-title'} = 'log';
3908 }
3909
3910 foreach my $format (qw(RSS Atom)) {
3911 my $type = lc($format);
3912 my %link_attr = (
3913 '-rel' => 'alternate',
3914 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3915 '-type' => "application/$type+xml"
3916 );
3917
3918 $href_params{'extra_options'} = undef;
3919 $href_params{'action'} = $type;
3920 $link_attr{'-href'} = href(%href_params);
3921 print "<link ".
3922 "rel=\"$link_attr{'-rel'}\" ".
3923 "title=\"$link_attr{'-title'}\" ".
3924 "href=\"$link_attr{'-href'}\" ".
3925 "type=\"$link_attr{'-type'}\" ".
3926 "/>\n";
3927
3928 $href_params{'extra_options'} = '--no-merges';
3929 $link_attr{'-href'} = href(%href_params);
3930 $link_attr{'-title'} .= ' (no merges)';
3931 print "<link ".
3932 "rel=\"$link_attr{'-rel'}\" ".
3933 "title=\"$link_attr{'-title'}\" ".
3934 "href=\"$link_attr{'-href'}\" ".
3935 "type=\"$link_attr{'-type'}\" ".
3936 "/>\n";
3937 }
3938
3939 } else {
3940 printf('<link rel="alternate" title="%s projects list" '.
3941 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3942 esc_attr($site_name), href(project=>undef, action=>"project_index"));
3943 printf('<link rel="alternate" title="%s projects feeds" '.
3944 'href="%s" type="text/x-opml" />'."\n",
3945 esc_attr($site_name), href(project=>undef, action=>"opml"));
3946 }
3947 }
3948
3949 sub print_header_links {
3950 my $status = shift;
3951
3952 # print out each stylesheet that exist, providing backwards capability
3953 # for those people who defined $stylesheet in a config file
3954 if (defined $stylesheet) {
3955 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3956 } else {
3957 foreach my $stylesheet (@stylesheets) {
3958 next unless $stylesheet;
3959 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3960 }
3961 }
3962 print_feed_meta()
3963 if ($status eq '200 OK');
3964 if (defined $favicon) {
3965 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
3966 }
3967 }
3968
3969 sub print_nav_breadcrumbs_path {
3970 my $dirprefix = undef;
3971 while (my $part = shift) {
3972 $dirprefix .= "/" if defined $dirprefix;
3973 $dirprefix .= $part;
3974 print $cgi->a({-href => href(project => undef,
3975 project_filter => $dirprefix,
3976 action => "project_list")},
3977 esc_html($part)) . " / ";
3978 }
3979 }
3980
3981 sub print_nav_breadcrumbs {
3982 my %opts = @_;
3983
3984 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3985 if (defined $project) {
3986 my @dirname = split '/', $project;
3987 my $projectbasename = pop @dirname;
3988 print_nav_breadcrumbs_path(@dirname);
3989 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
3990 if (defined $action) {
3991 my $action_print = $action ;
3992 if (defined $opts{-action_extra}) {
3993 $action_print = $cgi->a({-href => href(action=>$action)},
3994 $action);
3995 }
3996 print " / $action_print";
3997 }
3998 if (defined $opts{-action_extra}) {
3999 print " / $opts{-action_extra}";
4000 }
4001 print "\n";
4002 } elsif (defined $project_filter) {
4003 print_nav_breadcrumbs_path(split '/', $project_filter);
4004 }
4005 }
4006
4007 sub print_search_form {
4008 if (!defined $searchtext) {
4009 $searchtext = "";
4010 }
4011 my $search_hash;
4012 if (defined $hash_base) {
4013 $search_hash = $hash_base;
4014 } elsif (defined $hash) {
4015 $search_hash = $hash;
4016 } else {
4017 $search_hash = "HEAD";
4018 }
4019 my $action = $my_uri;
4020 my $use_pathinfo = gitweb_check_feature('pathinfo');
4021 if ($use_pathinfo) {
4022 $action .= "/".esc_url($project);
4023 }
4024 print $cgi->startform(-method => "get", -action => $action) .
4025 "<div class=\"search\">\n" .
4026 (!$use_pathinfo &&
4027 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4028 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4029 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4030 $cgi->popup_menu(-name => 'st', -default => 'commit',
4031 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4032 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
4033 " search:\n",
4034 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4035 "<span title=\"Extended regular expression\">" .
4036 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4037 -checked => $search_use_regexp) .
4038 "</span>" .
4039 "</div>" .
4040 $cgi->end_form() . "\n";
4041 }
4042
4043 sub git_header_html {
4044 my $status = shift || "200 OK";
4045 my $expires = shift;
4046 my %opts = @_;
4047
4048 my $title = get_page_title();
4049 my $content_type = get_content_type_html();
4050 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4051 -status=> $status, -expires => $expires)
4052 unless ($opts{'-no_http_header'});
4053 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4054 print <<EOF;
4055 <?xml version="1.0" encoding="utf-8"?>
4056 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4057 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4058 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4059 <!-- git core binaries version $git_version -->
4060 <head>
4061 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4062 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4063 <meta name="robots" content="index, nofollow"/>
4064 <title>$title</title>
4065 EOF
4066 # the stylesheet, favicon etc urls won't work correctly with path_info
4067 # unless we set the appropriate base URL
4068 if ($ENV{'PATH_INFO'}) {
4069 print "<base href=\"".esc_url($base_url)."\" />\n";
4070 }
4071 print_header_links($status);
4072
4073 if (defined $site_html_head_string) {
4074 print to_utf8($site_html_head_string);
4075 }
4076
4077 print "</head>\n" .
4078 "<body>\n";
4079
4080 if (defined $site_header && -f $site_header) {
4081 insert_file($site_header);
4082 }
4083
4084 print "<div class=\"page_header\">\n";
4085 if (defined $logo) {
4086 print $cgi->a({-href => esc_url($logo_url),
4087 -title => $logo_label},
4088 $cgi->img({-src => esc_url($logo),
4089 -width => 72, -height => 27,
4090 -alt => "git",
4091 -class => "logo"}));
4092 }
4093 print_nav_breadcrumbs(%opts);
4094 print "</div>\n";
4095
4096 my $have_search = gitweb_check_feature('search');
4097 if (defined $project && $have_search) {
4098 print_search_form();
4099 }
4100 }
4101
4102 sub git_footer_html {
4103 my $feed_class = 'rss_logo';
4104
4105 print "<div class=\"page_footer\">\n";
4106 if (defined $project) {
4107 my $descr = git_get_project_description($project);
4108 if (defined $descr) {
4109 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4110 }
4111
4112 my %href_params = get_feed_info();
4113 if (!%href_params) {
4114 $feed_class .= ' generic';
4115 }
4116 $href_params{'-title'} ||= 'log';
4117
4118 foreach my $format (qw(RSS Atom)) {
4119 $href_params{'action'} = lc($format);
4120 print $cgi->a({-href => href(%href_params),
4121 -title => "$href_params{'-title'} $format feed",
4122 -class => $feed_class}, $format)."\n";
4123 }
4124
4125 } else {
4126 print $cgi->a({-href => href(project=>undef, action=>"opml",
4127 project_filter => $project_filter),
4128 -class => $feed_class}, "OPML") . " ";
4129 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4130 project_filter => $project_filter),
4131 -class => $feed_class}, "TXT") . "\n";
4132 }
4133 print "</div>\n"; # class="page_footer"
4134
4135 if (defined $t0 && gitweb_check_feature('timed')) {
4136 print "<div id=\"generating_info\">\n";
4137 print 'This page took '.
4138 '<span id="generating_time" class="time_span">'.
4139 tv_interval($t0, [ gettimeofday() ]).
4140 ' seconds </span>'.
4141 ' and '.
4142 '<span id="generating_cmd">'.
4143 $number_of_git_cmds.
4144 '</span> git commands '.
4145 " to generate.\n";
4146 print "</div>\n"; # class="page_footer"
4147 }
4148
4149 if (defined $site_footer && -f $site_footer) {
4150 insert_file($site_footer);
4151 }
4152
4153 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4154 if (defined $action &&
4155 $action eq 'blame_incremental') {
4156 print qq!<script type="text/javascript">\n!.
4157 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4158 qq! "!. href() .qq!");\n!.
4159 qq!</script>\n!;
4160 } else {
4161 my ($jstimezone, $tz_cookie, $datetime_class) =
4162 gitweb_get_feature('javascript-timezone');
4163
4164 print qq!<script type="text/javascript">\n!.
4165 qq!window.onload = function () {\n!;
4166 if (gitweb_check_feature('javascript-actions')) {
4167 print qq! fixLinks();\n!;
4168 }
4169 if ($jstimezone && $tz_cookie && $datetime_class) {
4170 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4171 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4172 }
4173 print qq!};\n!.
4174 qq!</script>\n!;
4175 }
4176
4177 print "</body>\n" .
4178 "</html>";
4179 }
4180
4181 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4182 # Example: die_error(404, 'Hash not found')
4183 # By convention, use the following status codes (as defined in RFC 2616):
4184 # 400: Invalid or missing CGI parameters, or
4185 # requested object exists but has wrong type.
4186 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4187 # this server or project.
4188 # 404: Requested object/revision/project doesn't exist.
4189 # 500: The server isn't configured properly, or
4190 # an internal error occurred (e.g. failed assertions caused by bugs), or
4191 # an unknown error occurred (e.g. the git binary died unexpectedly).
4192 # 503: The server is currently unavailable (because it is overloaded,
4193 # or down for maintenance). Generally, this is a temporary state.
4194 sub die_error {
4195 my $status = shift || 500;
4196 my $error = esc_html(shift) || "Internal Server Error";
4197 my $extra = shift;
4198 my %opts = @_;
4199
4200 my %http_responses = (
4201 400 => '400 Bad Request',
4202 403 => '403 Forbidden',
4203 404 => '404 Not Found',
4204 500 => '500 Internal Server Error',
4205 503 => '503 Service Unavailable',
4206 );
4207 git_header_html($http_responses{$status}, undef, %opts);
4208 print <<EOF;
4209 <div class="page_body">
4210 <br /><br />
4211 $status - $error
4212 <br />
4213 EOF
4214 if (defined $extra) {
4215 print "<hr />\n" .
4216 "$extra\n";
4217 }
4218 print "</div>\n";
4219
4220 git_footer_html();
4221 goto DONE_GITWEB
4222 unless ($opts{'-error_handler'});
4223 }
4224
4225 ## ----------------------------------------------------------------------
4226 ## functions printing or outputting HTML: navigation
4227
4228 sub git_print_page_nav {
4229 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4230 $extra = '' if !defined $extra; # pager or formats
4231
4232 my @navs = qw(summary shortlog log commit commitdiff tree);
4233 if ($suppress) {
4234 @navs = grep { $_ ne $suppress } @navs;
4235 }
4236
4237 my %arg = map { $_ => {action=>$_} } @navs;
4238 if (defined $head) {
4239 for (qw(commit commitdiff)) {
4240 $arg{$_}{'hash'} = $head;
4241 }
4242 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4243 for (qw(shortlog log)) {
4244 $arg{$_}{'hash'} = $head;
4245 }
4246 }
4247 }
4248
4249 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4250 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4251
4252 my @actions = gitweb_get_feature('actions');
4253 my %repl = (
4254 '%' => '%',
4255 'n' => $project, # project name
4256 'f' => $git_dir, # project path within filesystem
4257 'h' => $treehead || '', # current hash ('h' parameter)
4258 'b' => $treebase || '', # hash base ('hb' parameter)
4259 );
4260 while (@actions) {
4261 my ($label, $link, $pos) = splice(@actions,0,3);
4262 # insert
4263 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4264 # munch munch
4265 $link =~ s/%([%nfhb])/$repl{$1}/g;
4266 $arg{$label}{'_href'} = $link;
4267 }
4268
4269 print "<div class=\"page_nav\">\n" .
4270 (join " | ",
4271 map { $_ eq $current ?
4272 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4273 } @navs);
4274 print "<br/>\n$extra<br/>\n" .
4275 "</div>\n";
4276 }
4277
4278 # returns a submenu for the nagivation of the refs views (tags, heads,
4279 # remotes) with the current view disabled and the remotes view only
4280 # available if the feature is enabled
4281 sub format_ref_views {
4282 my ($current) = @_;
4283 my @ref_views = qw{tags heads};
4284 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4285 return join " | ", map {
4286 $_ eq $current ? $_ :
4287 $cgi->a({-href => href(action=>$_)}, $_)
4288 } @ref_views
4289 }
4290
4291 sub format_paging_nav {
4292 my ($action, $page, $has_next_link) = @_;
4293 my $paging_nav;
4294
4295
4296 if ($page > 0) {
4297 $paging_nav .=
4298 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4299 " &sdot; " .
4300 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4301 -accesskey => "p", -title => "Alt-p"}, "prev");
4302 } else {
4303 $paging_nav .= "first &sdot; prev";
4304 }
4305
4306 if ($has_next_link) {
4307 $paging_nav .= " &sdot; " .
4308 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4309 -accesskey => "n", -title => "Alt-n"}, "next");
4310 } else {
4311 $paging_nav .= " &sdot; next";
4312 }
4313
4314 return $paging_nav;
4315 }
4316
4317 ## ......................................................................
4318 ## functions printing or outputting HTML: div
4319
4320 sub git_print_header_div {
4321 my ($action, $title, $hash, $hash_base) = @_;
4322 my %args = ();
4323
4324 $args{'action'} = $action;
4325 $args{'hash'} = $hash if $hash;
4326 $args{'hash_base'} = $hash_base if $hash_base;
4327
4328 print "<div class=\"header\">\n" .
4329 $cgi->a({-href => href(%args), -class => "title"},
4330 $title ? $title : $action) .
4331 "\n</div>\n";
4332 }
4333
4334 sub format_repo_url {
4335 my ($name, $url) = @_;
4336 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4337 }
4338
4339 # Group output by placing it in a DIV element and adding a header.
4340 # Options for start_div() can be provided by passing a hash reference as the
4341 # first parameter to the function.
4342 # Options to git_print_header_div() can be provided by passing an array
4343 # reference. This must follow the options to start_div if they are present.
4344 # The content can be a scalar, which is output as-is, a scalar reference, which
4345 # is output after html escaping, an IO handle passed either as *handle or
4346 # *handle{IO}, or a function reference. In the latter case all following
4347 # parameters will be taken as argument to the content function call.
4348 sub git_print_section {
4349 my ($div_args, $header_args, $content);
4350 my $arg = shift;
4351 if (ref($arg) eq 'HASH') {
4352 $div_args = $arg;
4353 $arg = shift;
4354 }
4355 if (ref($arg) eq 'ARRAY') {
4356 $header_args = $arg;
4357 $arg = shift;
4358 }
4359 $content = $arg;
4360
4361 print $cgi->start_div($div_args);
4362 git_print_header_div(@$header_args);
4363
4364 if (ref($content) eq 'CODE') {
4365 $content->(@_);
4366 } elsif (ref($content) eq 'SCALAR') {
4367 print esc_html($$content);
4368 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4369 print <$content>;
4370 } elsif (!ref($content) && defined($content)) {
4371 print $content;
4372 }
4373
4374 print $cgi->end_div;
4375 }
4376
4377 sub format_timestamp_html {
4378 my $date = shift;
4379 my $strtime = $date->{'rfc2822'};
4380
4381 my (undef, undef, $datetime_class) =
4382 gitweb_get_feature('javascript-timezone');
4383 if ($datetime_class) {
4384 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4385 }
4386
4387 my $localtime_format = '(%02d:%02d %s)';
4388 if ($date->{'hour_local'} < 6) {
4389 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4390 }
4391 $strtime .= ' ' .
4392 sprintf($localtime_format,
4393 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4394
4395 return $strtime;
4396 }
4397
4398 # Outputs the author name and date in long form
4399 sub git_print_authorship {
4400 my $co = shift;
4401 my %opts = @_;
4402 my $tag = $opts{-tag} || 'div';
4403 my $author = $co->{'author_name'};
4404
4405 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4406 print "<$tag class=\"author_date\">" .
4407 format_search_author($author, "author", esc_html($author)) .
4408 " [".format_timestamp_html(\%ad)."]".
4409 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4410 "</$tag>\n";
4411 }
4412
4413 # Outputs table rows containing the full author or committer information,
4414 # in the format expected for 'commit' view (& similar).
4415 # Parameters are a commit hash reference, followed by the list of people
4416 # to output information for. If the list is empty it defaults to both
4417 # author and committer.
4418 sub git_print_authorship_rows {
4419 my $co = shift;
4420 # too bad we can't use @people = @_ || ('author', 'committer')
4421 my @people = @_;
4422 @people = ('author', 'committer') unless @people;
4423 foreach my $who (@people) {
4424 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4425 print "<tr><td>$who</td><td>" .
4426 format_search_author($co->{"${who}_name"}, $who,
4427 esc_html($co->{"${who}_name"})) . " " .
4428 format_search_author($co->{"${who}_email"}, $who,
4429 esc_html("<" . $co->{"${who}_email"} . ">")) .
4430 "</td><td rowspan=\"2\">" .
4431 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4432 "</td></tr>\n" .
4433 "<tr>" .
4434 "<td></td><td>" .
4435 format_timestamp_html(\%wd) .
4436 "</td>" .
4437 "</tr>\n";
4438 }
4439 }
4440
4441 sub git_print_page_path {
4442 my $name = shift;
4443 my $type = shift;
4444 my $hb = shift;
4445
4446
4447 print "<div class=\"page_path\">";
4448 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4449 -title => 'tree root'}, to_utf8("[$project]"));
4450 print " / ";
4451 if (defined $name) {
4452 my @dirname = split '/', $name;
4453 my $basename = pop @dirname;
4454 my $fullname = '';
4455
4456 foreach my $dir (@dirname) {
4457 $fullname .= ($fullname ? '/' : '') . $dir;
4458 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4459 hash_base=>$hb),
4460 -title => $fullname}, esc_path($dir));
4461 print " / ";
4462 }
4463 if (defined $type && $type eq 'blob') {
4464 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4465 hash_base=>$hb),
4466 -title => $name}, esc_path($basename));
4467 } elsif (defined $type && $type eq 'tree') {
4468 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4469 hash_base=>$hb),
4470 -title => $name}, esc_path($basename));
4471 print " / ";
4472 } else {
4473 print esc_path($basename);
4474 }
4475 }
4476 print "<br/></div>\n";
4477 }
4478
4479 sub git_print_log {
4480 my $log = shift;
4481 my %opts = @_;
4482
4483 if ($opts{'-remove_title'}) {
4484 # remove title, i.e. first line of log
4485 shift @$log;
4486 }
4487 # remove leading empty lines
4488 while (defined $log->[0] && $log->[0] eq "") {
4489 shift @$log;
4490 }
4491
4492 # print log
4493 my $skip_blank_line = 0;
4494 foreach my $line (@$log) {
4495 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4496 if (! $opts{'-remove_signoff'}) {
4497 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4498 $skip_blank_line = 1;
4499 }
4500 next;
4501 }
4502
4503 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4504 if (! $opts{'-remove_signoff'}) {
4505 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4506 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4507 "</span><br/>\n";
4508 $skip_blank_line = 1;
4509 }
4510 next;
4511 }
4512
4513 # print only one empty line
4514 # do not print empty line after signoff
4515 if ($line eq "") {
4516 next if ($skip_blank_line);
4517 $skip_blank_line = 1;
4518 } else {
4519 $skip_blank_line = 0;
4520 }
4521
4522 print format_log_line_html($line) . "<br/>\n";
4523 }
4524
4525 if ($opts{'-final_empty_line'}) {
4526 # end with single empty line
4527 print "<br/>\n" unless $skip_blank_line;
4528 }
4529 }
4530
4531 # return link target (what link points to)
4532 sub git_get_link_target {
4533 my $hash = shift;
4534 my $link_target;
4535
4536 # read link
4537 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4538 or return;
4539 {
4540 local $/ = undef;
4541 $link_target = <$fd>;
4542 }
4543 close $fd
4544 or return;
4545
4546 return $link_target;
4547 }
4548
4549 # given link target, and the directory (basedir) the link is in,
4550 # return target of link relative to top directory (top tree);
4551 # return undef if it is not possible (including absolute links).
4552 sub normalize_link_target {
4553 my ($link_target, $basedir) = @_;
4554
4555 # absolute symlinks (beginning with '/') cannot be normalized
4556 return if (substr($link_target, 0, 1) eq '/');
4557
4558 # normalize link target to path from top (root) tree (dir)
4559 my $path;
4560 if ($basedir) {
4561 $path = $basedir . '/' . $link_target;
4562 } else {
4563 # we are in top (root) tree (dir)
4564 $path = $link_target;
4565 }
4566
4567 # remove //, /./, and /../
4568 my @path_parts;
4569 foreach my $part (split('/', $path)) {
4570 # discard '.' and ''
4571 next if (!$part || $part eq '.');
4572 # handle '..'
4573 if ($part eq '..') {
4574 if (@path_parts) {
4575 pop @path_parts;
4576 } else {
4577 # link leads outside repository (outside top dir)
4578 return;
4579 }
4580 } else {
4581 push @path_parts, $part;
4582 }
4583 }
4584 $path = join('/', @path_parts);
4585
4586 return $path;
4587 }
4588
4589 # print tree entry (row of git_tree), but without encompassing <tr> element
4590 sub git_print_tree_entry {
4591 my ($t, $basedir, $hash_base, $have_blame) = @_;
4592
4593 my %base_key = ();
4594 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4595
4596 # The format of a table row is: mode list link. Where mode is
4597 # the mode of the entry, list is the name of the entry, an href,
4598 # and link is the action links of the entry.
4599
4600 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4601 if (exists $t->{'size'}) {
4602 print "<td class=\"size\">$t->{'size'}</td>\n";
4603 }
4604 if ($t->{'type'} eq "blob") {
4605 print "<td class=\"list\">" .
4606 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4607 file_name=>"$basedir$t->{'name'}", %base_key),
4608 -class => "list"}, esc_path($t->{'name'}));
4609 if (S_ISLNK(oct $t->{'mode'})) {
4610 my $link_target = git_get_link_target($t->{'hash'});
4611 if ($link_target) {
4612 my $norm_target = normalize_link_target($link_target, $basedir);
4613 if (defined $norm_target) {
4614 print " -> " .
4615 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4616 file_name=>$norm_target),
4617 -title => $norm_target}, esc_path($link_target));
4618 } else {
4619 print " -> " . esc_path($link_target);
4620 }
4621 }
4622 }
4623 print "</td>\n";
4624 print "<td class=\"link\">";
4625 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4626 file_name=>"$basedir$t->{'name'}", %base_key)},
4627 "blob");
4628 if ($have_blame) {
4629 print " | " .
4630 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4631 file_name=>"$basedir$t->{'name'}", %base_key)},
4632 "blame");
4633 }
4634 if (defined $hash_base) {
4635 print " | " .
4636 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4637 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4638 "history");
4639 }
4640 print " | " .
4641 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4642 file_name=>"$basedir$t->{'name'}")},
4643 "raw");
4644 print "</td>\n";
4645
4646 } elsif ($t->{'type'} eq "tree") {
4647 print "<td class=\"list\">";
4648 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4649 file_name=>"$basedir$t->{'name'}",
4650 %base_key)},
4651 esc_path($t->{'name'}));
4652 print "</td>\n";
4653 print "<td class=\"link\">";
4654 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4655 file_name=>"$basedir$t->{'name'}",
4656 %base_key)},
4657 "tree");
4658 if (defined $hash_base) {
4659 print " | " .
4660 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4661 file_name=>"$basedir$t->{'name'}")},
4662 "history");
4663 }
4664 print "</td>\n";
4665 } else {
4666 # unknown object: we can only present history for it
4667 # (this includes 'commit' object, i.e. submodule support)
4668 print "<td class=\"list\">" .
4669 esc_path($t->{'name'}) .
4670 "</td>\n";
4671 print "<td class=\"link\">";
4672 if (defined $hash_base) {
4673 print $cgi->a({-href => href(action=>"history",
4674 hash_base=>$hash_base,
4675 file_name=>"$basedir$t->{'name'}")},
4676 "history");
4677 }
4678 print "</td>\n";
4679 }
4680 }
4681
4682 ## ......................................................................
4683 ## functions printing large fragments of HTML
4684
4685 # get pre-image filenames for merge (combined) diff
4686 sub fill_from_file_info {
4687 my ($diff, @parents) = @_;
4688
4689 $diff->{'from_file'} = [ ];
4690 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4691 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4692 if ($diff->{'status'}[$i] eq 'R' ||
4693 $diff->{'status'}[$i] eq 'C') {
4694 $diff->{'from_file'}[$i] =
4695 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4696 }
4697 }
4698
4699 return $diff;
4700 }
4701
4702 # is current raw difftree line of file deletion
4703 sub is_deleted {
4704 my $diffinfo = shift;
4705
4706 return $diffinfo->{'to_id'} eq ('0' x 40);
4707 }
4708
4709 # does patch correspond to [previous] difftree raw line
4710 # $diffinfo - hashref of parsed raw diff format
4711 # $patchinfo - hashref of parsed patch diff format
4712 # (the same keys as in $diffinfo)
4713 sub is_patch_split {
4714 my ($diffinfo, $patchinfo) = @_;
4715
4716 return defined $diffinfo && defined $patchinfo
4717 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4718 }
4719
4720
4721 sub git_difftree_body {
4722 my ($difftree, $hash, @parents) = @_;
4723 my ($parent) = $parents[0];
4724 my $have_blame = gitweb_check_feature('blame');
4725 print "<div class=\"list_head\">\n";
4726 if ($#{$difftree} > 10) {
4727 print(($#{$difftree} + 1) . " files changed:\n");
4728 }
4729 print "</div>\n";
4730
4731 print "<table class=\"" .
4732 (@parents > 1 ? "combined " : "") .
4733 "diff_tree\">\n";
4734
4735 # header only for combined diff in 'commitdiff' view
4736 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4737 if ($has_header) {
4738 # table header
4739 print "<thead><tr>\n" .
4740 "<th></th><th></th>\n"; # filename, patchN link
4741 for (my $i = 0; $i < @parents; $i++) {
4742 my $par = $parents[$i];
4743 print "<th>" .
4744 $cgi->a({-href => href(action=>"commitdiff",
4745 hash=>$hash, hash_parent=>$par),
4746 -title => 'commitdiff to parent number ' .
4747 ($i+1) . ': ' . substr($par,0,7)},
4748 $i+1) .
4749 "&nbsp;</th>\n";
4750 }
4751 print "</tr></thead>\n<tbody>\n";
4752 }
4753
4754 my $alternate = 1;
4755 my $patchno = 0;
4756 foreach my $line (@{$difftree}) {
4757 my $diff = parsed_difftree_line($line);
4758
4759 if ($alternate) {
4760 print "<tr class=\"dark\">\n";
4761 } else {
4762 print "<tr class=\"light\">\n";
4763 }
4764 $alternate ^= 1;
4765
4766 if (exists $diff->{'nparents'}) { # combined diff
4767
4768 fill_from_file_info($diff, @parents)
4769 unless exists $diff->{'from_file'};
4770
4771 if (!is_deleted($diff)) {
4772 # file exists in the result (child) commit
4773 print "<td>" .
4774 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4775 file_name=>$diff->{'to_file'},
4776 hash_base=>$hash),
4777 -class => "list"}, esc_path($diff->{'to_file'})) .
4778 "</td>\n";
4779 } else {
4780 print "<td>" .
4781 esc_path($diff->{'to_file'}) .
4782 "</td>\n";
4783 }
4784
4785 if ($action eq 'commitdiff') {
4786 # link to patch
4787 $patchno++;
4788 print "<td class=\"link\">" .
4789 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4790 "patch") .
4791 " | " .
4792 "</td>\n";
4793 }
4794
4795 my $has_history = 0;
4796 my $not_deleted = 0;
4797 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4798 my $hash_parent = $parents[$i];
4799 my $from_hash = $diff->{'from_id'}[$i];
4800 my $from_path = $diff->{'from_file'}[$i];
4801 my $status = $diff->{'status'}[$i];
4802
4803 $has_history ||= ($status ne 'A');
4804 $not_deleted ||= ($status ne 'D');
4805
4806 if ($status eq 'A') {
4807 print "<td class=\"link\" align=\"right\"> | </td>\n";
4808 } elsif ($status eq 'D') {
4809 print "<td class=\"link\">" .
4810 $cgi->a({-href => href(action=>"blob",
4811 hash_base=>$hash,
4812 hash=>$from_hash,
4813 file_name=>$from_path)},
4814 "blob" . ($i+1)) .
4815 " | </td>\n";
4816 } else {
4817 if ($diff->{'to_id'} eq $from_hash) {
4818 print "<td class=\"link nochange\">";
4819 } else {
4820 print "<td class=\"link\">";
4821 }
4822 print $cgi->a({-href => href(action=>"blobdiff",
4823 hash=>$diff->{'to_id'},
4824 hash_parent=>$from_hash,
4825 hash_base=>$hash,
4826 hash_parent_base=>$hash_parent,
4827 file_name=>$diff->{'to_file'},
4828 file_parent=>$from_path)},
4829 "diff" . ($i+1)) .
4830 " | </td>\n";
4831 }
4832 }
4833
4834 print "<td class=\"link\">";
4835 if ($not_deleted) {
4836 print $cgi->a({-href => href(action=>"blob",
4837 hash=>$diff->{'to_id'},
4838 file_name=>$diff->{'to_file'},
4839 hash_base=>$hash)},
4840 "blob");
4841 print " | " if ($has_history);
4842 }
4843 if ($has_history) {
4844 print $cgi->a({-href => href(action=>"history",
4845 file_name=>$diff->{'to_file'},
4846 hash_base=>$hash)},
4847 "history");
4848 }
4849 print "</td>\n";
4850
4851 print "</tr>\n";
4852 next; # instead of 'else' clause, to avoid extra indent
4853 }
4854 # else ordinary diff
4855
4856 my ($to_mode_oct, $to_mode_str, $to_file_type);
4857 my ($from_mode_oct, $from_mode_str, $from_file_type);
4858 if ($diff->{'to_mode'} ne ('0' x 6)) {
4859 $to_mode_oct = oct $diff->{'to_mode'};
4860 if (S_ISREG($to_mode_oct)) { # only for regular file
4861 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4862 }
4863 $to_file_type = file_type($diff->{'to_mode'});
4864 }
4865 if ($diff->{'from_mode'} ne ('0' x 6)) {
4866 $from_mode_oct = oct $diff->{'from_mode'};
4867 if (S_ISREG($from_mode_oct)) { # only for regular file
4868 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4869 }
4870 $from_file_type = file_type($diff->{'from_mode'});
4871 }
4872
4873 if ($diff->{'status'} eq "A") { # created
4874 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4875 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4876 $mode_chng .= "]</span>";
4877 print "<td>";
4878 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4879 hash_base=>$hash, file_name=>$diff->{'file'}),
4880 -class => "list"}, esc_path($diff->{'file'}));
4881 print "</td>\n";
4882 print "<td>$mode_chng</td>\n";
4883 print "<td class=\"link\">";
4884 if ($action eq 'commitdiff') {
4885 # link to patch
4886 $patchno++;
4887 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4888 "patch") .
4889 " | ";
4890 }
4891 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4892 hash_base=>$hash, file_name=>$diff->{'file'})},
4893 "blob");
4894 print "</td>\n";
4895
4896 } elsif ($diff->{'status'} eq "D") { # deleted
4897 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4898 print "<td>";
4899 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4900 hash_base=>$parent, file_name=>$diff->{'file'}),
4901 -class => "list"}, esc_path($diff->{'file'}));
4902 print "</td>\n";
4903 print "<td>$mode_chng</td>\n";
4904 print "<td class=\"link\">";
4905 if ($action eq 'commitdiff') {
4906 # link to patch
4907 $patchno++;
4908 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4909 "patch") .
4910 " | ";
4911 }
4912 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4913 hash_base=>$parent, file_name=>$diff->{'file'})},
4914 "blob") . " | ";
4915 if ($have_blame) {
4916 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4917 file_name=>$diff->{'file'})},
4918 "blame") . " | ";
4919 }
4920 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4921 file_name=>$diff->{'file'})},
4922 "history");
4923 print "</td>\n";
4924
4925 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4926 my $mode_chnge = "";
4927 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4928 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4929 if ($from_file_type ne $to_file_type) {
4930 $mode_chnge .= " from $from_file_type to $to_file_type";
4931 }
4932 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4933 if ($from_mode_str && $to_mode_str) {
4934 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4935 } elsif ($to_mode_str) {
4936 $mode_chnge .= " mode: $to_mode_str";
4937 }
4938 }
4939 $mode_chnge .= "]</span>\n";
4940 }
4941 print "<td>";
4942 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4943 hash_base=>$hash, file_name=>$diff->{'file'}),
4944 -class => "list"}, esc_path($diff->{'file'}));
4945 print "</td>\n";
4946 print "<td>$mode_chnge</td>\n";
4947 print "<td class=\"link\">";
4948 if ($action eq 'commitdiff') {
4949 # link to patch
4950 $patchno++;
4951 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4952 "patch") .
4953 " | ";
4954 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4955 # "commit" view and modified file (not onlu mode changed)
4956 print $cgi->a({-href => href(action=>"blobdiff",
4957 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4958 hash_base=>$hash, hash_parent_base=>$parent,
4959 file_name=>$diff->{'file'})},
4960 "diff") .
4961 " | ";
4962 }
4963 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4964 hash_base=>$hash, file_name=>$diff->{'file'})},
4965 "blob") . " | ";
4966 if ($have_blame) {
4967 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4968 file_name=>$diff->{'file'})},
4969 "blame") . " | ";
4970 }
4971 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4972 file_name=>$diff->{'file'})},
4973 "history");
4974 print "</td>\n";
4975
4976 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4977 my %status_name = ('R' => 'moved', 'C' => 'copied');
4978 my $nstatus = $status_name{$diff->{'status'}};
4979 my $mode_chng = "";
4980 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4981 # mode also for directories, so we cannot use $to_mode_str
4982 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4983 }
4984 print "<td>" .
4985 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4986 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4987 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4988 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4989 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4990 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4991 -class => "list"}, esc_path($diff->{'from_file'})) .
4992 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4993 "<td class=\"link\">";
4994 if ($action eq 'commitdiff') {
4995 # link to patch
4996 $patchno++;
4997 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4998 "patch") .
4999 " | ";
5000 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5001 # "commit" view and modified file (not only pure rename or copy)
5002 print $cgi->a({-href => href(action=>"blobdiff",
5003 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5004 hash_base=>$hash, hash_parent_base=>$parent,
5005 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5006 "diff") .
5007 " | ";
5008 }
5009 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5010 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5011 "blob") . " | ";
5012 if ($have_blame) {
5013 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5014 file_name=>$diff->{'to_file'})},
5015 "blame") . " | ";
5016 }
5017 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5018 file_name=>$diff->{'to_file'})},
5019 "history");
5020 print "</td>\n";
5021
5022 } # we should not encounter Unmerged (U) or Unknown (X) status
5023 print "</tr>\n";
5024 }
5025 print "</tbody>" if $has_header;
5026 print "</table>\n";
5027 }
5028
5029 # Print context lines and then rem/add lines in a side-by-side manner.
5030 sub print_sidebyside_diff_lines {
5031 my ($ctx, $rem, $add) = @_;
5032
5033 # print context block before add/rem block
5034 if (@$ctx) {
5035 print join '',
5036 '<div class="chunk_block ctx">',
5037 '<div class="old">',
5038 @$ctx,
5039 '</div>',
5040 '<div class="new">',
5041 @$ctx,
5042 '</div>',
5043 '</div>';
5044 }
5045
5046 if (!@$add) {
5047 # pure removal
5048 print join '',
5049 '<div class="chunk_block rem">',
5050 '<div class="old">',
5051 @$rem,
5052 '</div>',
5053 '</div>';
5054 } elsif (!@$rem) {
5055 # pure addition
5056 print join '',
5057 '<div class="chunk_block add">',
5058 '<div class="new">',
5059 @$add,
5060 '</div>',
5061 '</div>';
5062 } else {
5063 print join '',
5064 '<div class="chunk_block chg">',
5065 '<div class="old">',
5066 @$rem,
5067 '</div>',
5068 '<div class="new">',
5069 @$add,
5070 '</div>',
5071 '</div>';
5072 }
5073 }
5074
5075 # Print context lines and then rem/add lines in inline manner.
5076 sub print_inline_diff_lines {
5077 my ($ctx, $rem, $add) = @_;
5078
5079 print @$ctx, @$rem, @$add;
5080 }
5081
5082 # Format removed and added line, mark changed part and HTML-format them.
5083 # Implementation is based on contrib/diff-highlight
5084 sub format_rem_add_lines_pair {
5085 my ($rem, $add, $num_parents) = @_;
5086
5087 # We need to untabify lines before split()'ing them;
5088 # otherwise offsets would be invalid.
5089 chomp $rem;
5090 chomp $add;
5091 $rem = untabify($rem);
5092 $add = untabify($add);
5093
5094 my @rem = split(//, $rem);
5095 my @add = split(//, $add);
5096 my ($esc_rem, $esc_add);
5097 # Ignore leading +/- characters for each parent.
5098 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5099 my ($prefix_has_nonspace, $suffix_has_nonspace);
5100
5101 my $shorter = (@rem < @add) ? @rem : @add;
5102 while ($prefix_len < $shorter) {
5103 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5104
5105 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5106 $prefix_len++;
5107 }
5108
5109 while ($prefix_len + $suffix_len < $shorter) {
5110 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5111
5112 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5113 $suffix_len++;
5114 }
5115
5116 # Mark lines that are different from each other, but have some common
5117 # part that isn't whitespace. If lines are completely different, don't
5118 # mark them because that would make output unreadable, especially if
5119 # diff consists of multiple lines.
5120 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5121 $esc_rem = esc_html_hl_regions($rem, 'marked',
5122 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5123 $esc_add = esc_html_hl_regions($add, 'marked',
5124 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5125 } else {
5126 $esc_rem = esc_html($rem, -nbsp=>1);
5127 $esc_add = esc_html($add, -nbsp=>1);
5128 }
5129
5130 return format_diff_line(\$esc_rem, 'rem'),
5131 format_diff_line(\$esc_add, 'add');
5132 }
5133
5134 # HTML-format diff context, removed and added lines.
5135 sub format_ctx_rem_add_lines {
5136 my ($ctx, $rem, $add, $num_parents) = @_;
5137 my (@new_ctx, @new_rem, @new_add);
5138 my $can_highlight = 0;
5139 my $is_combined = ($num_parents > 1);
5140
5141 # Highlight if every removed line has a corresponding added line.
5142 if (@$add > 0 && @$add == @$rem) {
5143 $can_highlight = 1;
5144
5145 # Highlight lines in combined diff only if the chunk contains
5146 # diff between the same version, e.g.
5147 #
5148 # - a
5149 # - b
5150 # + c
5151 # + d
5152 #
5153 # Otherwise the highlightling would be confusing.
5154 if ($is_combined) {
5155 for (my $i = 0; $i < @$add; $i++) {
5156 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5157 my $prefix_add = substr($add->[$i], 0, $num_parents);
5158
5159 $prefix_rem =~ s/-/+/g;
5160
5161 if ($prefix_rem ne $prefix_add) {
5162 $can_highlight = 0;
5163 last;
5164 }
5165 }
5166 }
5167 }
5168
5169 if ($can_highlight) {
5170 for (my $i = 0; $i < @$add; $i++) {
5171 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5172 $rem->[$i], $add->[$i], $num_parents);
5173 push @new_rem, $line_rem;
5174 push @new_add, $line_add;
5175 }
5176 } else {
5177 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5178 @new_add = map { format_diff_line($_, 'add') } @$add;
5179 }
5180
5181 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5182
5183 return (\@new_ctx, \@new_rem, \@new_add);
5184 }
5185
5186 # Print context lines and then rem/add lines.
5187 sub print_diff_lines {
5188 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5189 my $is_combined = $num_parents > 1;
5190
5191 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5192 $num_parents);
5193
5194 if ($diff_style eq 'sidebyside' && !$is_combined) {
5195 print_sidebyside_diff_lines($ctx, $rem, $add);
5196 } else {
5197 # default 'inline' style and unknown styles
5198 print_inline_diff_lines($ctx, $rem, $add);
5199 }
5200 }
5201
5202 sub print_diff_chunk {
5203 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5204 my (@ctx, @rem, @add);
5205
5206 # The class of the previous line.
5207 my $prev_class = '';
5208
5209 return unless @chunk;
5210
5211 # incomplete last line might be among removed or added lines,
5212 # or both, or among context lines: find which
5213 for (my $i = 1; $i < @chunk; $i++) {
5214 if ($chunk[$i][0] eq 'incomplete') {
5215 $chunk[$i][0] = $chunk[$i-1][0];
5216 }
5217 }
5218
5219 # guardian
5220 push @chunk, ["", ""];
5221
5222 foreach my $line_info (@chunk) {
5223 my ($class, $line) = @$line_info;
5224
5225 # print chunk headers
5226 if ($class && $class eq 'chunk_header') {
5227 print format_diff_line($line, $class, $from, $to);
5228 next;
5229 }
5230
5231 ## print from accumulator when have some add/rem lines or end
5232 # of chunk (flush context lines), or when have add and rem
5233 # lines and new block is reached (otherwise add/rem lines could
5234 # be reordered)
5235 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5236 (@rem && @add && $class ne $prev_class)) {
5237 print_diff_lines(\@ctx, \@rem, \@add,
5238 $diff_style, $num_parents);
5239 @ctx = @rem = @add = ();
5240 }
5241
5242 ## adding lines to accumulator
5243 # guardian value
5244 last unless $line;
5245 # rem, add or change
5246 if ($class eq 'rem') {
5247 push @rem, $line;
5248 } elsif ($class eq 'add') {
5249 push @add, $line;
5250 }
5251 # context line
5252 if ($class eq 'ctx') {
5253 push @ctx, $line;
5254 }
5255
5256 $prev_class = $class;
5257 }
5258 }
5259
5260 sub git_patchset_body {
5261 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5262 my ($hash_parent) = $hash_parents[0];
5263
5264 my $is_combined = (@hash_parents > 1);
5265 my $patch_idx = 0;
5266 my $patch_number = 0;
5267 my $patch_line;
5268 my $diffinfo;
5269 my $to_name;
5270 my (%from, %to);
5271 my @chunk; # for side-by-side diff
5272
5273 print "<div class=\"patchset\">\n";
5274
5275 # skip to first patch
5276 while ($patch_line = <$fd>) {
5277 chomp $patch_line;
5278
5279 last if ($patch_line =~ m/^diff /);
5280 }
5281
5282 PATCH:
5283 while ($patch_line) {
5284
5285 # parse "git diff" header line
5286 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5287 # $1 is from_name, which we do not use
5288 $to_name = unquote($2);
5289 $to_name =~ s!^b/!!;
5290 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5291 # $1 is 'cc' or 'combined', which we do not use
5292 $to_name = unquote($2);
5293 } else {
5294 $to_name = undef;
5295 }
5296
5297 # check if current patch belong to current raw line
5298 # and parse raw git-diff line if needed
5299 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5300 # this is continuation of a split patch
5301 print "<div class=\"patch cont\">\n";
5302 } else {
5303 # advance raw git-diff output if needed
5304 $patch_idx++ if defined $diffinfo;
5305
5306 # read and prepare patch information
5307 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5308
5309 # compact combined diff output can have some patches skipped
5310 # find which patch (using pathname of result) we are at now;
5311 if ($is_combined) {
5312 while ($to_name ne $diffinfo->{'to_file'}) {
5313 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5314 format_diff_cc_simplified($diffinfo, @hash_parents) .
5315 "</div>\n"; # class="patch"
5316
5317 $patch_idx++;
5318 $patch_number++;
5319
5320 last if $patch_idx > $#$difftree;
5321 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5322 }
5323 }
5324
5325 # modifies %from, %to hashes
5326 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5327
5328 # this is first patch for raw difftree line with $patch_idx index
5329 # we index @$difftree array from 0, but number patches from 1
5330 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5331 }
5332
5333 # git diff header
5334 #assert($patch_line =~ m/^diff /) if DEBUG;
5335 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5336 $patch_number++;
5337 # print "git diff" header
5338 print format_git_diff_header_line($patch_line, $diffinfo,
5339 \%from, \%to);
5340
5341 # print extended diff header
5342 print "<div class=\"diff extended_header\">\n";
5343 EXTENDED_HEADER:
5344 while ($patch_line = <$fd>) {
5345 chomp $patch_line;
5346
5347 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5348
5349 print format_extended_diff_header_line($patch_line, $diffinfo,
5350 \%from, \%to);
5351 }
5352 print "</div>\n"; # class="diff extended_header"
5353
5354 # from-file/to-file diff header
5355 if (! $patch_line) {
5356 print "</div>\n"; # class="patch"
5357 last PATCH;
5358 }
5359 next PATCH if ($patch_line =~ m/^diff /);
5360 #assert($patch_line =~ m/^---/) if DEBUG;
5361
5362 my $last_patch_line = $patch_line;
5363 $patch_line = <$fd>;
5364 chomp $patch_line;
5365 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5366
5367 print format_diff_from_to_header($last_patch_line, $patch_line,
5368 $diffinfo, \%from, \%to,
5369 @hash_parents);
5370
5371 # the patch itself
5372 LINE:
5373 while ($patch_line = <$fd>) {
5374 chomp $patch_line;
5375
5376 next PATCH if ($patch_line =~ m/^diff /);
5377
5378 my $class = diff_line_class($patch_line, \%from, \%to);
5379
5380 if ($class eq 'chunk_header') {
5381 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5382 @chunk = ();
5383 }
5384
5385 push @chunk, [ $class, $patch_line ];
5386 }
5387
5388 } continue {
5389 if (@chunk) {
5390 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5391 @chunk = ();
5392 }
5393 print "</div>\n"; # class="patch"
5394 }
5395
5396 # for compact combined (--cc) format, with chunk and patch simplification
5397 # the patchset might be empty, but there might be unprocessed raw lines
5398 for (++$patch_idx if $patch_number > 0;
5399 $patch_idx < @$difftree;
5400 ++$patch_idx) {
5401 # read and prepare patch information
5402 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5403
5404 # generate anchor for "patch" links in difftree / whatchanged part
5405 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5406 format_diff_cc_simplified($diffinfo, @hash_parents) .
5407 "</div>\n"; # class="patch"
5408
5409 $patch_number++;
5410 }
5411
5412 if ($patch_number == 0) {
5413 if (@hash_parents > 1) {
5414 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5415 } else {
5416 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5417 }
5418 }
5419
5420 print "</div>\n"; # class="patchset"
5421 }
5422
5423 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5424
5425 sub git_project_search_form {
5426 my ($searchtext, $search_use_regexp) = @_;
5427
5428 my $limit = '';
5429 if ($project_filter) {
5430 $limit = " in '$project_filter/'";
5431 }
5432
5433 print "<div class=\"projsearch\">\n";
5434 print $cgi->startform(-method => 'get', -action => $my_uri) .
5435 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5436 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5437 if (defined $project_filter);
5438 print $cgi->textfield(-name => 's', -value => $searchtext,
5439 -title => "Search project by name and description$limit",
5440 -size => 60) . "\n" .
5441 "<span title=\"Extended regular expression\">" .
5442 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5443 -checked => $search_use_regexp) .
5444 "</span>\n" .
5445 $cgi->submit(-name => 'btnS', -value => 'Search') .
5446 $cgi->end_form() . "\n" .
5447 $cgi->a({-href => href(project => undef, searchtext => undef,
5448 project_filter => $project_filter)},
5449 esc_html("List all projects$limit")) . "<br />\n";
5450 print "</div>\n";
5451 }
5452
5453 # entry for given @keys needs filling if at least one of keys in list
5454 # is not present in %$project_info
5455 sub project_info_needs_filling {
5456 my ($project_info, @keys) = @_;
5457
5458 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5459 foreach my $key (@keys) {
5460 if (!exists $project_info->{$key}) {
5461 return 1;
5462 }
5463 }
5464 return;
5465 }
5466
5467 # fills project list info (age, description, owner, category, forks, etc.)
5468 # for each project in the list, removing invalid projects from
5469 # returned list, or fill only specified info.
5470 #
5471 # Invalid projects are removed from the returned list if and only if you
5472 # ask 'age' or 'age_string' to be filled, because they are the only fields
5473 # that run unconditionally git command that requires repository, and
5474 # therefore do always check if project repository is invalid.
5475 #
5476 # USAGE:
5477 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5478 # ensures that 'descr_long' and 'ctags' fields are filled
5479 # * @project_list = fill_project_list_info(\@project_list)
5480 # ensures that all fields are filled (and invalid projects removed)
5481 #
5482 # NOTE: modifies $projlist, but does not remove entries from it
5483 sub fill_project_list_info {
5484 my ($projlist, @wanted_keys) = @_;
5485 my @projects;
5486 my $filter_set = sub { return @_; };
5487 if (@wanted_keys) {
5488 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5489 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5490 }
5491
5492 my $show_ctags = gitweb_check_feature('ctags');
5493 PROJECT:
5494 foreach my $pr (@$projlist) {
5495 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5496 my (@activity) = git_get_last_activity($pr->{'path'});
5497 unless (@activity) {
5498 next PROJECT;
5499 }
5500 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5501 }
5502 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5503 my $descr = git_get_project_description($pr->{'path'}) || "";
5504 $descr = to_utf8($descr);
5505 $pr->{'descr_long'} = $descr;
5506 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5507 }
5508 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5509 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5510 }
5511 if ($show_ctags &&
5512 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5513 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5514 }
5515 if ($projects_list_group_categories &&
5516 project_info_needs_filling($pr, $filter_set->('category'))) {
5517 my $cat = git_get_project_category($pr->{'path'}) ||
5518 $project_list_default_category;
5519 $pr->{'category'} = to_utf8($cat);
5520 }
5521
5522 push @projects, $pr;
5523 }
5524
5525 return @projects;
5526 }
5527
5528 sub sort_projects_list {
5529 my ($projlist, $order) = @_;
5530 my @projects;
5531
5532 my %order_info = (
5533 project => { key => 'path', type => 'str' },
5534 descr => { key => 'descr_long', type => 'str' },
5535 owner => { key => 'owner', type => 'str' },
5536 age => { key => 'age', type => 'num' }
5537 );
5538 my $oi = $order_info{$order};
5539 return @$projlist unless defined $oi;
5540 if ($oi->{'type'} eq 'str') {
5541 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @$projlist;
5542 } else {
5543 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @$projlist;
5544 }
5545
5546 return @projects;
5547 }
5548
5549 # returns a hash of categories, containing the list of project
5550 # belonging to each category
5551 sub build_projlist_by_category {
5552 my ($projlist, $from, $to) = @_;
5553 my %categories;
5554
5555 $from = 0 unless defined $from;
5556 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5557
5558 for (my $i = $from; $i <= $to; $i++) {
5559 my $pr = $projlist->[$i];
5560 push @{$categories{ $pr->{'category'} }}, $pr;
5561 }
5562
5563 return wantarray ? %categories : \%categories;
5564 }
5565
5566 # print 'sort by' <th> element, generating 'sort by $name' replay link
5567 # if that order is not selected
5568 sub print_sort_th {
5569 print format_sort_th(@_);
5570 }
5571
5572 sub format_sort_th {
5573 my ($name, $order, $header) = @_;
5574 my $sort_th = "";
5575 $header ||= ucfirst($name);
5576
5577 if ($order eq $name) {
5578 $sort_th .= "<th>$header</th>\n";
5579 } else {
5580 $sort_th .= "<th>" .
5581 $cgi->a({-href => href(-replay=>1, order=>$name),
5582 -class => "header"}, $header) .
5583 "</th>\n";
5584 }
5585
5586 return $sort_th;
5587 }
5588
5589 sub git_project_list_rows {
5590 my ($projlist, $from, $to, $check_forks) = @_;
5591
5592 $from = 0 unless defined $from;
5593 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5594
5595 my $alternate = 1;
5596 for (my $i = $from; $i <= $to; $i++) {
5597 my $pr = $projlist->[$i];
5598
5599 if ($alternate) {
5600 print "<tr class=\"dark\">\n";
5601 } else {
5602 print "<tr class=\"light\">\n";
5603 }
5604 $alternate ^= 1;
5605
5606 if ($check_forks) {
5607 print "<td>";
5608 if ($pr->{'forks'}) {
5609 my $nforks = scalar @{$pr->{'forks'}};
5610 if ($nforks > 0) {
5611 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5612 -title => "$nforks forks"}, "+");
5613 } else {
5614 print $cgi->span({-title => "$nforks forks"}, "+");
5615 }
5616 }
5617 print "</td>\n";
5618 }
5619 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5620 -class => "list"},
5621 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5622 "</td>\n" .
5623 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5624 -class => "list",
5625 -title => $pr->{'descr_long'}},
5626 $search_regexp
5627 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5628 $pr->{'descr'}, $search_regexp)
5629 : esc_html($pr->{'descr'})) .
5630 "</td>\n";
5631 unless ($omit_owner) {
5632 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5633 }
5634 unless ($omit_age_column) {
5635 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5636 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5637 }
5638 print"<td class=\"link\">" .
5639 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5640 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5641 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5642 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5643 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5644 "</td>\n" .
5645 "</tr>\n";
5646 }
5647 }
5648
5649 sub git_project_list_body {
5650 # actually uses global variable $project
5651 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5652 my @projects = @$projlist;
5653
5654 my $check_forks = gitweb_check_feature('forks');
5655 my $show_ctags = gitweb_check_feature('ctags');
5656 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5657 $check_forks = undef
5658 if ($tagfilter || $search_regexp);
5659
5660 # filtering out forks before filling info allows to do less work
5661 @projects = filter_forks_from_projects_list(\@projects)
5662 if ($check_forks);
5663 # search_projects_list pre-fills required info
5664 @projects = search_projects_list(\@projects,
5665 'search_regexp' => $search_regexp,
5666 'tagfilter' => $tagfilter)
5667 if ($tagfilter || $search_regexp);
5668 # fill the rest
5669 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5670 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5671 push @all_fields, 'owner' unless($omit_owner);
5672 @projects = fill_project_list_info(\@projects, @all_fields);
5673
5674 $order ||= $default_projects_order;
5675 $from = 0 unless defined $from;
5676 $to = $#projects if (!defined $to || $#projects < $to);
5677
5678 # short circuit
5679 if ($from > $to) {
5680 print "<center>\n".
5681 "<b>No such projects found</b><br />\n".
5682 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5683 "</center>\n<br />\n";
5684 return;
5685 }
5686
5687 @projects = sort_projects_list(\@projects, $order);
5688
5689 if ($show_ctags) {
5690 my $ctags = git_gather_all_ctags(\@projects);
5691 my $cloud = git_populate_project_tagcloud($ctags);
5692 print git_show_project_tagcloud($cloud, 64);
5693 }
5694
5695 print "<table class=\"project_list\">\n";
5696 unless ($no_header) {
5697 print "<tr>\n";
5698 if ($check_forks) {
5699 print "<th></th>\n";
5700 }
5701 print_sort_th('project', $order, 'Project');
5702 print_sort_th('descr', $order, 'Description');
5703 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5704 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5705 print "<th></th>\n" . # for links
5706 "</tr>\n";
5707 }
5708
5709 if ($projects_list_group_categories) {
5710 # only display categories with projects in the $from-$to window
5711 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5712 my %categories = build_projlist_by_category(\@projects, $from, $to);
5713 foreach my $cat (sort keys %categories) {
5714 unless ($cat eq "") {
5715 print "<tr>\n";
5716 if ($check_forks) {
5717 print "<td></td>\n";
5718 }
5719 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5720 print "</tr>\n";
5721 }
5722
5723 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5724 }
5725 } else {
5726 git_project_list_rows(\@projects, $from, $to, $check_forks);
5727 }
5728
5729 if (defined $extra) {
5730 print "<tr>\n";
5731 if ($check_forks) {
5732 print "<td></td>\n";
5733 }
5734 print "<td colspan=\"5\">$extra</td>\n" .
5735 "</tr>\n";
5736 }
5737 print "</table>\n";
5738 }
5739
5740 sub git_log_body {
5741 # uses global variable $project
5742 my ($commitlist, $from, $to, $refs, $extra) = @_;
5743
5744 $from = 0 unless defined $from;
5745 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5746
5747 for (my $i = 0; $i <= $to; $i++) {
5748 my %co = %{$commitlist->[$i]};
5749 next if !%co;
5750 my $commit = $co{'id'};
5751 my $ref = format_ref_marker($refs, $commit);
5752 git_print_header_div('commit',
5753 "<span class=\"age\">$co{'age_string'}</span>" .
5754 esc_html($co{'title'}) . $ref,
5755 $commit);
5756 print "<div class=\"title_text\">\n" .
5757 "<div class=\"log_link\">\n" .
5758 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5759 " | " .
5760 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5761 " | " .
5762 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5763 "<br/>\n" .
5764 "</div>\n";
5765 git_print_authorship(\%co, -tag => 'span');
5766 print "<br/>\n</div>\n";
5767
5768 print "<div class=\"log_body\">\n";
5769 git_print_log($co{'comment'}, -final_empty_line=> 1);
5770 print "</div>\n";
5771 }
5772 if ($extra) {
5773 print "<div class=\"page_nav\">\n";
5774 print "$extra\n";
5775 print "</div>\n";
5776 }
5777 }
5778
5779 sub git_shortlog_body {
5780 # uses global variable $project
5781 my ($commitlist, $from, $to, $refs, $extra) = @_;
5782
5783 $from = 0 unless defined $from;
5784 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5785
5786 print "<table class=\"shortlog\">\n";
5787 my $alternate = 1;
5788 for (my $i = $from; $i <= $to; $i++) {
5789 my %co = %{$commitlist->[$i]};
5790 my $commit = $co{'id'};
5791 my $ref = format_ref_marker($refs, $commit);
5792 if ($alternate) {
5793 print "<tr class=\"dark\">\n";
5794 } else {
5795 print "<tr class=\"light\">\n";
5796 }
5797 $alternate ^= 1;
5798 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5799 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5800 format_author_html('td', \%co, 10) . "<td>";
5801 print format_subject_html($co{'title'}, $co{'title_short'},
5802 href(action=>"commit", hash=>$commit), $ref);
5803 print "</td>\n" .
5804 "<td class=\"link\">" .
5805 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5806 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5807 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5808 my $snapshot_links = format_snapshot_links($commit);
5809 if (defined $snapshot_links) {
5810 print " | " . $snapshot_links;
5811 }
5812 print "</td>\n" .
5813 "</tr>\n";
5814 }
5815 if (defined $extra) {
5816 print "<tr>\n" .
5817 "<td colspan=\"4\">$extra</td>\n" .
5818 "</tr>\n";
5819 }
5820 print "</table>\n";
5821 }
5822
5823 sub git_history_body {
5824 # Warning: assumes constant type (blob or tree) during history
5825 my ($commitlist, $from, $to, $refs, $extra,
5826 $file_name, $file_hash, $ftype) = @_;
5827
5828 $from = 0 unless defined $from;
5829 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5830
5831 print "<table class=\"history\">\n";
5832 my $alternate = 1;
5833 for (my $i = $from; $i <= $to; $i++) {
5834 my %co = %{$commitlist->[$i]};
5835 if (!%co) {
5836 next;
5837 }
5838 my $commit = $co{'id'};
5839
5840 my $ref = format_ref_marker($refs, $commit);
5841
5842 if ($alternate) {
5843 print "<tr class=\"dark\">\n";
5844 } else {
5845 print "<tr class=\"light\">\n";
5846 }
5847 $alternate ^= 1;
5848 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5849 # shortlog: format_author_html('td', \%co, 10)
5850 format_author_html('td', \%co, 15, 3) . "<td>";
5851 # originally git_history used chop_str($co{'title'}, 50)
5852 print format_subject_html($co{'title'}, $co{'title_short'},
5853 href(action=>"commit", hash=>$commit), $ref);
5854 print "</td>\n" .
5855 "<td class=\"link\">" .
5856 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5857 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5858
5859 if ($ftype eq 'blob') {
5860 my $blob_current = $file_hash;
5861 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5862 if (defined $blob_current && defined $blob_parent &&
5863 $blob_current ne $blob_parent) {
5864 print " | " .
5865 $cgi->a({-href => href(action=>"blobdiff",
5866 hash=>$blob_current, hash_parent=>$blob_parent,
5867 hash_base=>$hash_base, hash_parent_base=>$commit,
5868 file_name=>$file_name)},
5869 "diff to current");
5870 }
5871 }
5872 print "</td>\n" .
5873 "</tr>\n";
5874 }
5875 if (defined $extra) {
5876 print "<tr>\n" .
5877 "<td colspan=\"4\">$extra</td>\n" .
5878 "</tr>\n";
5879 }
5880 print "</table>\n";
5881 }
5882
5883 sub git_tags_body {
5884 # uses global variable $project
5885 my ($taglist, $from, $to, $extra) = @_;
5886 $from = 0 unless defined $from;
5887 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5888
5889 print "<table class=\"tags\">\n";
5890 my $alternate = 1;
5891 for (my $i = $from; $i <= $to; $i++) {
5892 my $entry = $taglist->[$i];
5893 my %tag = %$entry;
5894 my $comment = $tag{'subject'};
5895 my $comment_short;
5896 if (defined $comment) {
5897 $comment_short = chop_str($comment, 30, 5);
5898 }
5899 if ($alternate) {
5900 print "<tr class=\"dark\">\n";
5901 } else {
5902 print "<tr class=\"light\">\n";
5903 }
5904 $alternate ^= 1;
5905 if (defined $tag{'age'}) {
5906 print "<td><i>$tag{'age'}</i></td>\n";
5907 } else {
5908 print "<td></td>\n";
5909 }
5910 print "<td>" .
5911 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5912 -class => "list name"}, esc_html($tag{'name'})) .
5913 "</td>\n" .
5914 "<td>";
5915 if (defined $comment) {
5916 print format_subject_html($comment, $comment_short,
5917 href(action=>"tag", hash=>$tag{'id'}));
5918 }
5919 print "</td>\n" .
5920 "<td class=\"selflink\">";
5921 if ($tag{'type'} eq "tag") {
5922 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5923 } else {
5924 print "&nbsp;";
5925 }
5926 print "</td>\n" .
5927 "<td class=\"link\">" . " | " .
5928 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5929 if ($tag{'reftype'} eq "commit") {
5930 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5931 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5932 } elsif ($tag{'reftype'} eq "blob") {
5933 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5934 }
5935 print "</td>\n" .
5936 "</tr>";
5937 }
5938 if (defined $extra) {
5939 print "<tr>\n" .
5940 "<td colspan=\"5\">$extra</td>\n" .
5941 "</tr>\n";
5942 }
5943 print "</table>\n";
5944 }
5945
5946 sub git_heads_body {
5947 # uses global variable $project
5948 my ($headlist, $head_at, $from, $to, $extra) = @_;
5949 $from = 0 unless defined $from;
5950 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5951
5952 print "<table class=\"heads\">\n";
5953 my $alternate = 1;
5954 for (my $i = $from; $i <= $to; $i++) {
5955 my $entry = $headlist->[$i];
5956 my %ref = %$entry;
5957 my $curr = defined $head_at && $ref{'id'} eq $head_at;
5958 if ($alternate) {
5959 print "<tr class=\"dark\">\n";
5960 } else {
5961 print "<tr class=\"light\">\n";
5962 }
5963 $alternate ^= 1;
5964 print "<td><i>$ref{'age'}</i></td>\n" .
5965 ($curr ? "<td class=\"current_head\">" : "<td>") .
5966 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5967 -class => "list name"},esc_html($ref{'name'})) .
5968 "</td>\n" .
5969 "<td class=\"link\">" .
5970 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5971 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5972 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
5973 "</td>\n" .
5974 "</tr>";
5975 }
5976 if (defined $extra) {
5977 print "<tr>\n" .
5978 "<td colspan=\"3\">$extra</td>\n" .
5979 "</tr>\n";
5980 }
5981 print "</table>\n";
5982 }
5983
5984 # Display a single remote block
5985 sub git_remote_block {
5986 my ($remote, $rdata, $limit, $head) = @_;
5987
5988 my $heads = $rdata->{'heads'};
5989 my $fetch = $rdata->{'fetch'};
5990 my $push = $rdata->{'push'};
5991
5992 my $urls_table = "<table class=\"projects_list\">\n" ;
5993
5994 if (defined $fetch) {
5995 if ($fetch eq $push) {
5996 $urls_table .= format_repo_url("URL", $fetch);
5997 } else {
5998 $urls_table .= format_repo_url("Fetch URL", $fetch);
5999 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6000 }
6001 } elsif (defined $push) {
6002 $urls_table .= format_repo_url("Push URL", $push);
6003 } else {
6004 $urls_table .= format_repo_url("", "No remote URL");
6005 }
6006
6007 $urls_table .= "</table>\n";
6008
6009 my $dots;
6010 if (defined $limit && $limit < @$heads) {
6011 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6012 }
6013
6014 print $urls_table;
6015 git_heads_body($heads, $head, 0, $limit, $dots);
6016 }
6017
6018 # Display a list of remote names with the respective fetch and push URLs
6019 sub git_remotes_list {
6020 my ($remotedata, $limit) = @_;
6021 print "<table class=\"heads\">\n";
6022 my $alternate = 1;
6023 my @remotes = sort keys %$remotedata;
6024
6025 my $limited = $limit && $limit < @remotes;
6026
6027 $#remotes = $limit - 1 if $limited;
6028
6029 while (my $remote = shift @remotes) {
6030 my $rdata = $remotedata->{$remote};
6031 my $fetch = $rdata->{'fetch'};
6032 my $push = $rdata->{'push'};
6033 if ($alternate) {
6034 print "<tr class=\"dark\">\n";
6035 } else {
6036 print "<tr class=\"light\">\n";
6037 }
6038 $alternate ^= 1;
6039 print "<td>" .
6040 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6041 -class=> "list name"},esc_html($remote)) .
6042 "</td>";
6043 print "<td class=\"link\">" .
6044 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6045 " | " .
6046 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6047 "</td>";
6048
6049 print "</tr>\n";
6050 }
6051
6052 if ($limited) {
6053 print "<tr>\n" .
6054 "<td colspan=\"3\">" .
6055 $cgi->a({-href => href(action=>"remotes")}, "...") .
6056 "</td>\n" . "</tr>\n";
6057 }
6058
6059 print "</table>";
6060 }
6061
6062 # Display remote heads grouped by remote, unless there are too many
6063 # remotes, in which case we only display the remote names
6064 sub git_remotes_body {
6065 my ($remotedata, $limit, $head) = @_;
6066 if ($limit and $limit < keys %$remotedata) {
6067 git_remotes_list($remotedata, $limit);
6068 } else {
6069 fill_remote_heads($remotedata);
6070 while (my ($remote, $rdata) = each %$remotedata) {
6071 git_print_section({-class=>"remote", -id=>$remote},
6072 ["remotes", $remote, $remote], sub {
6073 git_remote_block($remote, $rdata, $limit, $head);
6074 });
6075 }
6076 }
6077 }
6078
6079 sub git_search_message {
6080 my %co = @_;
6081
6082 my $greptype;
6083 if ($searchtype eq 'commit') {
6084 $greptype = "--grep=";
6085 } elsif ($searchtype eq 'author') {
6086 $greptype = "--author=";
6087 } elsif ($searchtype eq 'committer') {
6088 $greptype = "--committer=";
6089 }
6090 $greptype .= $searchtext;
6091 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6092 $greptype, '--regexp-ignore-case',
6093 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6094
6095 my $paging_nav = '';
6096 if ($page > 0) {
6097 $paging_nav .=
6098 $cgi->a({-href => href(-replay=>1, page=>undef)},
6099 "first") .
6100 " &sdot; " .
6101 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6102 -accesskey => "p", -title => "Alt-p"}, "prev");
6103 } else {
6104 $paging_nav .= "first &sdot; prev";
6105 }
6106 my $next_link = '';
6107 if ($#commitlist >= 100) {
6108 $next_link =
6109 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6110 -accesskey => "n", -title => "Alt-n"}, "next");
6111 $paging_nav .= " &sdot; $next_link";
6112 } else {
6113 $paging_nav .= " &sdot; next";
6114 }
6115
6116 git_header_html();
6117
6118 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6119 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6120 if ($page == 0 && !@commitlist) {
6121 print "<p>No match.</p>\n";
6122 } else {
6123 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6124 }
6125
6126 git_footer_html();
6127 }
6128
6129 sub git_search_changes {
6130 my %co = @_;
6131
6132 local $/ = "\n";
6133 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6134 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6135 ($search_use_regexp ? '--pickaxe-regex' : ())
6136 or die_error(500, "Open git-log failed");
6137
6138 git_header_html();
6139
6140 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6141 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6142
6143 print "<table class=\"pickaxe search\">\n";
6144 my $alternate = 1;
6145 undef %co;
6146 my @files;
6147 while (my $line = <$fd>) {
6148 chomp $line;
6149 next unless $line;
6150
6151 my %set = parse_difftree_raw_line($line);
6152 if (defined $set{'commit'}) {
6153 # finish previous commit
6154 if (%co) {
6155 print "</td>\n" .
6156 "<td class=\"link\">" .
6157 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6158 "commit") .
6159 " | " .
6160 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6161 hash_base=>$co{'id'})},
6162 "tree") .
6163 "</td>\n" .
6164 "</tr>\n";
6165 }
6166
6167 if ($alternate) {
6168 print "<tr class=\"dark\">\n";
6169 } else {
6170 print "<tr class=\"light\">\n";
6171 }
6172 $alternate ^= 1;
6173 %co = parse_commit($set{'commit'});
6174 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6175 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6176 "<td><i>$author</i></td>\n" .
6177 "<td>" .
6178 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6179 -class => "list subject"},
6180 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6181 } elsif (defined $set{'to_id'}) {
6182 next if ($set{'to_id'} =~ m/^0{40}$/);
6183
6184 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6185 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6186 -class => "list"},
6187 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6188 "<br/>\n";
6189 }
6190 }
6191 close $fd;
6192
6193 # finish last commit (warning: repetition!)
6194 if (%co) {
6195 print "</td>\n" .
6196 "<td class=\"link\">" .
6197 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6198 "commit") .
6199 " | " .
6200 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6201 hash_base=>$co{'id'})},
6202 "tree") .
6203 "</td>\n" .
6204 "</tr>\n";
6205 }
6206
6207 print "</table>\n";
6208
6209 git_footer_html();
6210 }
6211
6212 sub git_search_files {
6213 my %co = @_;
6214
6215 local $/ = "\n";
6216 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6217 $search_use_regexp ? ('-E', '-i') : '-F',
6218 $searchtext, $co{'tree'}
6219 or die_error(500, "Open git-grep failed");
6220
6221 git_header_html();
6222
6223 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6224 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6225
6226 print "<table class=\"grep_search\">\n";
6227 my $alternate = 1;
6228 my $matches = 0;
6229 my $lastfile = '';
6230 my $file_href;
6231 while (my $line = <$fd>) {
6232 chomp $line;
6233 my ($file, $lno, $ltext, $binary);
6234 last if ($matches++ > 1000);
6235 if ($line =~ /^Binary file (.+) matches$/) {
6236 $file = $1;
6237 $binary = 1;
6238 } else {
6239 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6240 $file =~ s/^$co{'tree'}://;
6241 }
6242 if ($file ne $lastfile) {
6243 $lastfile and print "</td></tr>\n";
6244 if ($alternate++) {
6245 print "<tr class=\"dark\">\n";
6246 } else {
6247 print "<tr class=\"light\">\n";
6248 }
6249 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6250 file_name=>$file);
6251 print "<td class=\"list\">".
6252 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6253 print "</td><td>\n";
6254 $lastfile = $file;
6255 }
6256 if ($binary) {
6257 print "<div class=\"binary\">Binary file</div>\n";
6258 } else {
6259 $ltext = untabify($ltext);
6260 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6261 $ltext = esc_html($1, -nbsp=>1);
6262 $ltext .= '<span class="match">';
6263 $ltext .= esc_html($2, -nbsp=>1);
6264 $ltext .= '</span>';
6265 $ltext .= esc_html($3, -nbsp=>1);
6266 } else {
6267 $ltext = esc_html($ltext, -nbsp=>1);
6268 }
6269 print "<div class=\"pre\">" .
6270 $cgi->a({-href => $file_href.'#l'.$lno,
6271 -class => "linenr"}, sprintf('%4i', $lno)) .
6272 ' ' . $ltext . "</div>\n";
6273 }
6274 }
6275 if ($lastfile) {
6276 print "</td></tr>\n";
6277 if ($matches > 1000) {
6278 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6279 }
6280 } else {
6281 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6282 }
6283 close $fd;
6284
6285 print "</table>\n";
6286
6287 git_footer_html();
6288 }
6289
6290 sub git_search_grep_body {
6291 my ($commitlist, $from, $to, $extra) = @_;
6292 $from = 0 unless defined $from;
6293 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6294
6295 print "<table class=\"commit_search\">\n";
6296 my $alternate = 1;
6297 for (my $i = $from; $i <= $to; $i++) {
6298 my %co = %{$commitlist->[$i]};
6299 if (!%co) {
6300 next;
6301 }
6302 my $commit = $co{'id'};
6303 if ($alternate) {
6304 print "<tr class=\"dark\">\n";
6305 } else {
6306 print "<tr class=\"light\">\n";
6307 }
6308 $alternate ^= 1;
6309 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6310 format_author_html('td', \%co, 15, 5) .
6311 "<td>" .
6312 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6313 -class => "list subject"},
6314 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6315 my $comment = $co{'comment'};
6316 foreach my $line (@$comment) {
6317 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6318 my ($lead, $match, $trail) = ($1, $2, $3);
6319 $match = chop_str($match, 70, 5, 'center');
6320 my $contextlen = int((80 - length($match))/2);
6321 $contextlen = 30 if ($contextlen > 30);
6322 $lead = chop_str($lead, $contextlen, 10, 'left');
6323 $trail = chop_str($trail, $contextlen, 10, 'right');
6324
6325 $lead = esc_html($lead);
6326 $match = esc_html($match);
6327 $trail = esc_html($trail);
6328
6329 print "$lead<span class=\"match\">$match</span>$trail<br />";
6330 }
6331 }
6332 print "</td>\n" .
6333 "<td class=\"link\">" .
6334 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6335 " | " .
6336 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6337 " | " .
6338 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6339 print "</td>\n" .
6340 "</tr>\n";
6341 }
6342 if (defined $extra) {
6343 print "<tr>\n" .
6344 "<td colspan=\"3\">$extra</td>\n" .
6345 "</tr>\n";
6346 }
6347 print "</table>\n";
6348 }
6349
6350 ## ======================================================================
6351 ## ======================================================================
6352 ## actions
6353
6354 sub git_project_list {
6355 my $order = $input_params{'order'};
6356 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6357 die_error(400, "Unknown order parameter");
6358 }
6359
6360 my @list = git_get_projects_list($project_filter, $strict_export);
6361 if (!@list) {
6362 die_error(404, "No projects found");
6363 }
6364
6365 git_header_html();
6366 if (defined $home_text && -f $home_text) {
6367 print "<div class=\"index_include\">\n";
6368 insert_file($home_text);
6369 print "</div>\n";
6370 }
6371
6372 git_project_search_form($searchtext, $search_use_regexp);
6373 git_project_list_body(\@list, $order);
6374 git_footer_html();
6375 }
6376
6377 sub git_forks {
6378 my $order = $input_params{'order'};
6379 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6380 die_error(400, "Unknown order parameter");
6381 }
6382
6383 my $filter = $project;
6384 $filter =~ s/\.git$//;
6385 my @list = git_get_projects_list($filter);
6386 if (!@list) {
6387 die_error(404, "No forks found");
6388 }
6389
6390 git_header_html();
6391 git_print_page_nav('','');
6392 git_print_header_div('summary', "$project forks");
6393 git_project_list_body(\@list, $order);
6394 git_footer_html();
6395 }
6396
6397 sub git_project_index {
6398 my @projects = git_get_projects_list($project_filter, $strict_export);
6399 if (!@projects) {
6400 die_error(404, "No projects found");
6401 }
6402
6403 print $cgi->header(
6404 -type => 'text/plain',
6405 -charset => 'utf-8',
6406 -content_disposition => 'inline; filename="index.aux"');
6407
6408 foreach my $pr (@projects) {
6409 if (!exists $pr->{'owner'}) {
6410 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6411 }
6412
6413 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6414 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6415 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6416 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6417 $path =~ s/ /\+/g;
6418 $owner =~ s/ /\+/g;
6419
6420 print "$path $owner\n";
6421 }
6422 }
6423
6424 sub git_summary {
6425 my $descr = git_get_project_description($project) || "none";
6426 my %co = parse_commit("HEAD");
6427 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6428 my $head = $co{'id'};
6429 my $remote_heads = gitweb_check_feature('remote_heads');
6430
6431 my $owner = git_get_project_owner($project);
6432
6433 my $refs = git_get_references();
6434 # These get_*_list functions return one more to allow us to see if
6435 # there are more ...
6436 my @taglist = git_get_tags_list(16);
6437 my @headlist = git_get_heads_list(16);
6438 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6439 my @forklist;
6440 my $check_forks = gitweb_check_feature('forks');
6441
6442 if ($check_forks) {
6443 # find forks of a project
6444 my $filter = $project;
6445 $filter =~ s/\.git$//;
6446 @forklist = git_get_projects_list($filter);
6447 # filter out forks of forks
6448 @forklist = filter_forks_from_projects_list(\@forklist)
6449 if (@forklist);
6450 }
6451
6452 git_header_html();
6453 git_print_page_nav('summary','', $head);
6454
6455 print "<div class=\"title\">&nbsp;</div>\n";
6456 print "<table class=\"projects_list\">\n" .
6457 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6458 unless ($omit_owner) {
6459 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6460 }
6461 if (defined $cd{'rfc2822'}) {
6462 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6463 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6464 }
6465
6466 # use per project git URL list in $projectroot/$project/cloneurl
6467 # or make project git URL from git base URL and project name
6468 my $url_tag = "URL";
6469 my @url_list = git_get_project_url_list($project);
6470 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6471 foreach my $git_url (@url_list) {
6472 next unless $git_url;
6473 print format_repo_url($url_tag, $git_url);
6474 $url_tag = "";
6475 }
6476
6477 # Tag cloud
6478 my $show_ctags = gitweb_check_feature('ctags');
6479 if ($show_ctags) {
6480 my $ctags = git_get_project_ctags($project);
6481 if (%$ctags) {
6482 # without ability to add tags, don't show if there are none
6483 my $cloud = git_populate_project_tagcloud($ctags);
6484 print "<tr id=\"metadata_ctags\">" .
6485 "<td>content tags</td>" .
6486 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6487 "</tr>\n";
6488 }
6489 }
6490
6491 print "</table>\n";
6492
6493 # If XSS prevention is on, we don't include README.html.
6494 # TODO: Allow a readme in some safe format.
6495 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6496 print "<div class=\"title\">readme</div>\n" .
6497 "<div class=\"readme\">\n";
6498 insert_file("$projectroot/$project/README.html");
6499 print "\n</div>\n"; # class="readme"
6500 }
6501
6502 # we need to request one more than 16 (0..15) to check if
6503 # those 16 are all
6504 my @commitlist = $head ? parse_commits($head, 17) : ();
6505 if (@commitlist) {
6506 git_print_header_div('shortlog');
6507 git_shortlog_body(\@commitlist, 0, 15, $refs,
6508 $#commitlist <= 15 ? undef :
6509 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6510 }
6511
6512 if (@taglist) {
6513 git_print_header_div('tags');
6514 git_tags_body(\@taglist, 0, 15,
6515 $#taglist <= 15 ? undef :
6516 $cgi->a({-href => href(action=>"tags")}, "..."));
6517 }
6518
6519 if (@headlist) {
6520 git_print_header_div('heads');
6521 git_heads_body(\@headlist, $head, 0, 15,
6522 $#headlist <= 15 ? undef :
6523 $cgi->a({-href => href(action=>"heads")}, "..."));
6524 }
6525
6526 if (%remotedata) {
6527 git_print_header_div('remotes');
6528 git_remotes_body(\%remotedata, 15, $head);
6529 }
6530
6531 if (@forklist) {
6532 git_print_header_div('forks');
6533 git_project_list_body(\@forklist, 'age', 0, 15,
6534 $#forklist <= 15 ? undef :
6535 $cgi->a({-href => href(action=>"forks")}, "..."),
6536 'no_header');
6537 }
6538
6539 git_footer_html();
6540 }
6541
6542 sub git_tag {
6543 my %tag = parse_tag($hash);
6544
6545 if (! %tag) {
6546 die_error(404, "Unknown tag object");
6547 }
6548
6549 my $head = git_get_head_hash($project);
6550 git_header_html();
6551 git_print_page_nav('','', $head,undef,$head);
6552 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6553 print "<div class=\"title_text\">\n" .
6554 "<table class=\"object_header\">\n" .
6555 "<tr>\n" .
6556 "<td>object</td>\n" .
6557 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6558 $tag{'object'}) . "</td>\n" .
6559 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6560 $tag{'type'}) . "</td>\n" .
6561 "</tr>\n";
6562 if (defined($tag{'author'})) {
6563 git_print_authorship_rows(\%tag, 'author');
6564 }
6565 print "</table>\n\n" .
6566 "</div>\n";
6567 print "<div class=\"page_body\">";
6568 my $comment = $tag{'comment'};
6569 foreach my $line (@$comment) {
6570 chomp $line;
6571 print esc_html($line, -nbsp=>1) . "<br/>\n";
6572 }
6573 print "</div>\n";
6574 git_footer_html();
6575 }
6576
6577 sub git_blame_common {
6578 my $format = shift || 'porcelain';
6579 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6580 $format = 'incremental';
6581 $action = 'blame_incremental'; # for page title etc
6582 }
6583
6584 # permissions
6585 gitweb_check_feature('blame')
6586 or die_error(403, "Blame view not allowed");
6587
6588 # error checking
6589 die_error(400, "No file name given") unless $file_name;
6590 $hash_base ||= git_get_head_hash($project);
6591 die_error(404, "Couldn't find base commit") unless $hash_base;
6592 my %co = parse_commit($hash_base)
6593 or die_error(404, "Commit not found");
6594 my $ftype = "blob";
6595 if (!defined $hash) {
6596 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6597 or die_error(404, "Error looking up file");
6598 } else {
6599 $ftype = git_get_type($hash);
6600 if ($ftype !~ "blob") {
6601 die_error(400, "Object is not a blob");
6602 }
6603 }
6604
6605 my $fd;
6606 if ($format eq 'incremental') {
6607 # get file contents (as base)
6608 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6609 or die_error(500, "Open git-cat-file failed");
6610 } elsif ($format eq 'data') {
6611 # run git-blame --incremental
6612 open $fd, "-|", git_cmd(), "blame", "--incremental",
6613 $hash_base, "--", $file_name
6614 or die_error(500, "Open git-blame --incremental failed");
6615 } else {
6616 # run git-blame --porcelain
6617 open $fd, "-|", git_cmd(), "blame", '-p',
6618 $hash_base, '--', $file_name
6619 or die_error(500, "Open git-blame --porcelain failed");
6620 }
6621
6622 # incremental blame data returns early
6623 if ($format eq 'data') {
6624 print $cgi->header(
6625 -type=>"text/plain", -charset => "utf-8",
6626 -status=> "200 OK");
6627 local $| = 1; # output autoflush
6628 while (my $line = <$fd>) {
6629 print to_utf8($line);
6630 }
6631 close $fd
6632 or print "ERROR $!\n";
6633
6634 print 'END';
6635 if (defined $t0 && gitweb_check_feature('timed')) {
6636 print ' '.
6637 tv_interval($t0, [ gettimeofday() ]).
6638 ' '.$number_of_git_cmds;
6639 }
6640 print "\n";
6641
6642 return;
6643 }
6644
6645 # page header
6646 git_header_html();
6647 my $formats_nav =
6648 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6649 "blob") .
6650 " | ";
6651 if ($format eq 'incremental') {
6652 $formats_nav .=
6653 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6654 "blame") . " (non-incremental)";
6655 } else {
6656 $formats_nav .=
6657 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6658 "blame") . " (incremental)";
6659 }
6660 $formats_nav .=
6661 " | " .
6662 $cgi->a({-href => href(action=>"history", -replay=>1)},
6663 "history") .
6664 " | " .
6665 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6666 "HEAD");
6667 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6668 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6669 git_print_page_path($file_name, $ftype, $hash_base);
6670
6671 # page body
6672 if ($format eq 'incremental') {
6673 print "<noscript>\n<div class=\"error\"><center><b>\n".
6674 "This page requires JavaScript to run.\n Use ".
6675 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6676 'this page').
6677 " instead.\n".
6678 "</b></center></div>\n</noscript>\n";
6679
6680 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6681 }
6682
6683 print qq!<div class="page_body">\n!;
6684 print qq!<div id="progress_info">... / ...</div>\n!
6685 if ($format eq 'incremental');
6686 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6687 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6688 qq!<thead>\n!.
6689 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6690 qq!</thead>\n!.
6691 qq!<tbody>\n!;
6692
6693 my @rev_color = qw(light dark);
6694 my $num_colors = scalar(@rev_color);
6695 my $current_color = 0;
6696
6697 if ($format eq 'incremental') {
6698 my $color_class = $rev_color[$current_color];
6699
6700 #contents of a file
6701 my $linenr = 0;
6702 LINE:
6703 while (my $line = <$fd>) {
6704 chomp $line;
6705 $linenr++;
6706
6707 print qq!<tr id="l$linenr" class="$color_class">!.
6708 qq!<td class="sha1"><a href=""> </a></td>!.
6709 qq!<td class="linenr">!.
6710 qq!<a class="linenr" href="">$linenr</a></td>!;
6711 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6712 print qq!</tr>\n!;
6713 }
6714
6715 } else { # porcelain, i.e. ordinary blame
6716 my %metainfo = (); # saves information about commits
6717
6718 # blame data
6719 LINE:
6720 while (my $line = <$fd>) {
6721 chomp $line;
6722 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6723 # no <lines in group> for subsequent lines in group of lines
6724 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6725 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6726 if (!exists $metainfo{$full_rev}) {
6727 $metainfo{$full_rev} = { 'nprevious' => 0 };
6728 }
6729 my $meta = $metainfo{$full_rev};
6730 my $data;
6731 while ($data = <$fd>) {
6732 chomp $data;
6733 last if ($data =~ s/^\t//); # contents of line
6734 if ($data =~ /^(\S+)(?: (.*))?$/) {
6735 $meta->{$1} = $2 unless exists $meta->{$1};
6736 }
6737 if ($data =~ /^previous /) {
6738 $meta->{'nprevious'}++;
6739 }
6740 }
6741 my $short_rev = substr($full_rev, 0, 8);
6742 my $author = $meta->{'author'};
6743 my %date =
6744 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6745 my $date = $date{'iso-tz'};
6746 if ($group_size) {
6747 $current_color = ($current_color + 1) % $num_colors;
6748 }
6749 my $tr_class = $rev_color[$current_color];
6750 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6751 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6752 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6753 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6754 if ($group_size) {
6755 print "<td class=\"sha1\"";
6756 print " title=\"". esc_html($author) . ", $date\"";
6757 print " rowspan=\"$group_size\"" if ($group_size > 1);
6758 print ">";
6759 print $cgi->a({-href => href(action=>"commit",
6760 hash=>$full_rev,
6761 file_name=>$file_name)},
6762 esc_html($short_rev));
6763 if ($group_size >= 2) {
6764 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6765 if (@author_initials) {
6766 print "<br />" .
6767 esc_html(join('', @author_initials));
6768 # or join('.', ...)
6769 }
6770 }
6771 print "</td>\n";
6772 }
6773 # 'previous' <sha1 of parent commit> <filename at commit>
6774 if (exists $meta->{'previous'} &&
6775 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6776 $meta->{'parent'} = $1;
6777 $meta->{'file_parent'} = unquote($2);
6778 }
6779 my $linenr_commit =
6780 exists($meta->{'parent'}) ?
6781 $meta->{'parent'} : $full_rev;
6782 my $linenr_filename =
6783 exists($meta->{'file_parent'}) ?
6784 $meta->{'file_parent'} : unquote($meta->{'filename'});
6785 my $blamed = href(action => 'blame',
6786 file_name => $linenr_filename,
6787 hash_base => $linenr_commit);
6788 print "<td class=\"linenr\">";
6789 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6790 -class => "linenr" },
6791 esc_html($lineno));
6792 print "</td>";
6793 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6794 print "</tr>\n";
6795 } # end while
6796
6797 }
6798
6799 # footer
6800 print "</tbody>\n".
6801 "</table>\n"; # class="blame"
6802 print "</div>\n"; # class="blame_body"
6803 close $fd
6804 or print "Reading blob failed\n";
6805
6806 git_footer_html();
6807 }
6808
6809 sub git_blame {
6810 git_blame_common();
6811 }
6812
6813 sub git_blame_incremental {
6814 git_blame_common('incremental');
6815 }
6816
6817 sub git_blame_data {
6818 git_blame_common('data');
6819 }
6820
6821 sub git_tags {
6822 my $head = git_get_head_hash($project);
6823 git_header_html();
6824 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6825 git_print_header_div('summary', $project);
6826
6827 my @tagslist = git_get_tags_list();
6828 if (@tagslist) {
6829 git_tags_body(\@tagslist);
6830 }
6831 git_footer_html();
6832 }
6833
6834 sub git_heads {
6835 my $head = git_get_head_hash($project);
6836 git_header_html();
6837 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6838 git_print_header_div('summary', $project);
6839
6840 my @headslist = git_get_heads_list();
6841 if (@headslist) {
6842 git_heads_body(\@headslist, $head);
6843 }
6844 git_footer_html();
6845 }
6846
6847 # used both for single remote view and for list of all the remotes
6848 sub git_remotes {
6849 gitweb_check_feature('remote_heads')
6850 or die_error(403, "Remote heads view is disabled");
6851
6852 my $head = git_get_head_hash($project);
6853 my $remote = $input_params{'hash'};
6854
6855 my $remotedata = git_get_remotes_list($remote);
6856 die_error(500, "Unable to get remote information") unless defined $remotedata;
6857
6858 unless (%$remotedata) {
6859 die_error(404, defined $remote ?
6860 "Remote $remote not found" :
6861 "No remotes found");
6862 }
6863
6864 git_header_html(undef, undef, -action_extra => $remote);
6865 git_print_page_nav('', '', $head, undef, $head,
6866 format_ref_views($remote ? '' : 'remotes'));
6867
6868 fill_remote_heads($remotedata);
6869 if (defined $remote) {
6870 git_print_header_div('remotes', "$remote remote for $project");
6871 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6872 } else {
6873 git_print_header_div('summary', "$project remotes");
6874 git_remotes_body($remotedata, undef, $head);
6875 }
6876
6877 git_footer_html();
6878 }
6879
6880 sub git_blob_plain {
6881 my $type = shift;
6882 my $expires;
6883
6884 if (!defined $hash) {
6885 if (defined $file_name) {
6886 my $base = $hash_base || git_get_head_hash($project);
6887 $hash = git_get_hash_by_path($base, $file_name, "blob")
6888 or die_error(404, "Cannot find file");
6889 } else {
6890 die_error(400, "No file name defined");
6891 }
6892 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6893 # blobs defined by non-textual hash id's can be cached
6894 $expires = "+1d";
6895 }
6896
6897 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6898 or die_error(500, "Open git-cat-file blob '$hash' failed");
6899
6900 # content-type (can include charset)
6901 $type = blob_contenttype($fd, $file_name, $type);
6902
6903 # "save as" filename, even when no $file_name is given
6904 my $save_as = "$hash";
6905 if (defined $file_name) {
6906 $save_as = $file_name;
6907 } elsif ($type =~ m/^text\//) {
6908 $save_as .= '.txt';
6909 }
6910
6911 # With XSS prevention on, blobs of all types except a few known safe
6912 # ones are served with "Content-Disposition: attachment" to make sure
6913 # they don't run in our security domain. For certain image types,
6914 # blob view writes an <img> tag referring to blob_plain view, and we
6915 # want to be sure not to break that by serving the image as an
6916 # attachment (though Firefox 3 doesn't seem to care).
6917 my $sandbox = $prevent_xss &&
6918 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
6919
6920 # serve text/* as text/plain
6921 if ($prevent_xss &&
6922 ($type =~ m!^text/[a-z]+\b(.*)$! ||
6923 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
6924 my $rest = $1;
6925 $rest = defined $rest ? $rest : '';
6926 $type = "text/plain$rest";
6927 }
6928
6929 print $cgi->header(
6930 -type => $type,
6931 -expires => $expires,
6932 -content_disposition =>
6933 ($sandbox ? 'attachment' : 'inline')
6934 . '; filename="' . $save_as . '"');
6935 local $/ = undef;
6936 binmode STDOUT, ':raw';
6937 print <$fd>;
6938 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6939 close $fd;
6940 }
6941
6942 sub git_blob {
6943 my $expires;
6944
6945 if (!defined $hash) {
6946 if (defined $file_name) {
6947 my $base = $hash_base || git_get_head_hash($project);
6948 $hash = git_get_hash_by_path($base, $file_name, "blob")
6949 or die_error(404, "Cannot find file");
6950 } else {
6951 die_error(400, "No file name defined");
6952 }
6953 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6954 # blobs defined by non-textual hash id's can be cached
6955 $expires = "+1d";
6956 }
6957
6958 my $have_blame = gitweb_check_feature('blame');
6959 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6960 or die_error(500, "Couldn't cat $file_name, $hash");
6961 my $mimetype = blob_mimetype($fd, $file_name);
6962 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
6963 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
6964 close $fd;
6965 return git_blob_plain($mimetype);
6966 }
6967 # we can have blame only for text/* mimetype
6968 $have_blame &&= ($mimetype =~ m!^text/!);
6969
6970 my $highlight = gitweb_check_feature('highlight');
6971 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
6972 $fd = run_highlighter($fd, $highlight, $syntax)
6973 if $syntax;
6974
6975 git_header_html(undef, $expires);
6976 my $formats_nav = '';
6977 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6978 if (defined $file_name) {
6979 if ($have_blame) {
6980 $formats_nav .=
6981 $cgi->a({-href => href(action=>"blame", -replay=>1)},
6982 "blame") .
6983 " | ";
6984 }
6985 $formats_nav .=
6986 $cgi->a({-href => href(action=>"history", -replay=>1)},
6987 "history") .
6988 " | " .
6989 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6990 "raw") .
6991 " | " .
6992 $cgi->a({-href => href(action=>"blob",
6993 hash_base=>"HEAD", file_name=>$file_name)},
6994 "HEAD");
6995 } else {
6996 $formats_nav .=
6997 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6998 "raw");
6999 }
7000 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7001 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7002 } else {
7003 print "<div class=\"page_nav\">\n" .
7004 "<br/><br/></div>\n" .
7005 "<div class=\"title\">".esc_html($hash)."</div>\n";
7006 }
7007 git_print_page_path($file_name, "blob", $hash_base);
7008 print "<div class=\"page_body\">\n";
7009 if ($mimetype =~ m!^image/!) {
7010 print qq!<img type="!.esc_attr($mimetype).qq!"!;
7011 if ($file_name) {
7012 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7013 }
7014 print qq! src="! .
7015 href(action=>"blob_plain", hash=>$hash,
7016 hash_base=>$hash_base, file_name=>$file_name) .
7017 qq!" />\n!;
7018 } else {
7019 my $nr;
7020 while (my $line = <$fd>) {
7021 chomp $line;
7022 $nr++;
7023 $line = untabify($line);
7024 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7025 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7026 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7027 }
7028 }
7029 close $fd
7030 or print "Reading blob failed.\n";
7031 print "</div>";
7032 git_footer_html();
7033 }
7034
7035 sub git_tree {
7036 if (!defined $hash_base) {
7037 $hash_base = "HEAD";
7038 }
7039 if (!defined $hash) {
7040 if (defined $file_name) {
7041 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7042 } else {
7043 $hash = $hash_base;
7044 }
7045 }
7046 die_error(404, "No such tree") unless defined($hash);
7047
7048 my $show_sizes = gitweb_check_feature('show-sizes');
7049 my $have_blame = gitweb_check_feature('blame');
7050
7051 my @entries = ();
7052 {
7053 local $/ = "\0";
7054 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7055 ($show_sizes ? '-l' : ()), @extra_options, $hash
7056 or die_error(500, "Open git-ls-tree failed");
7057 @entries = map { chomp; $_ } <$fd>;
7058 close $fd
7059 or die_error(404, "Reading tree failed");
7060 }
7061
7062 my $refs = git_get_references();
7063 my $ref = format_ref_marker($refs, $hash_base);
7064 git_header_html();
7065 my $basedir = '';
7066 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7067 my @views_nav = ();
7068 if (defined $file_name) {
7069 push @views_nav,
7070 $cgi->a({-href => href(action=>"history", -replay=>1)},
7071 "history"),
7072 $cgi->a({-href => href(action=>"tree",
7073 hash_base=>"HEAD", file_name=>$file_name)},
7074 "HEAD"),
7075 }
7076 my $snapshot_links = format_snapshot_links($hash);
7077 if (defined $snapshot_links) {
7078 # FIXME: Should be available when we have no hash base as well.
7079 push @views_nav, $snapshot_links;
7080 }
7081 git_print_page_nav('tree','', $hash_base, undef, undef,
7082 join(' | ', @views_nav));
7083 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7084 } else {
7085 undef $hash_base;
7086 print "<div class=\"page_nav\">\n";
7087 print "<br/><br/></div>\n";
7088 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7089 }
7090 if (defined $file_name) {
7091 $basedir = $file_name;
7092 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7093 $basedir .= '/';
7094 }
7095 git_print_page_path($file_name, 'tree', $hash_base);
7096 }
7097 print "<div class=\"page_body\">\n";
7098 print "<table class=\"tree\">\n";
7099 my $alternate = 1;
7100 # '..' (top directory) link if possible
7101 if (defined $hash_base &&
7102 defined $file_name && $file_name =~ m![^/]+$!) {
7103 if ($alternate) {
7104 print "<tr class=\"dark\">\n";
7105 } else {
7106 print "<tr class=\"light\">\n";
7107 }
7108 $alternate ^= 1;
7109
7110 my $up = $file_name;
7111 $up =~ s!/?[^/]+$!!;
7112 undef $up unless $up;
7113 # based on git_print_tree_entry
7114 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7115 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7116 print '<td class="list">';
7117 print $cgi->a({-href => href(action=>"tree",
7118 hash_base=>$hash_base,
7119 file_name=>$up)},
7120 "..");
7121 print "</td>\n";
7122 print "<td class=\"link\"></td>\n";
7123
7124 print "</tr>\n";
7125 }
7126 foreach my $line (@entries) {
7127 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7128
7129 if ($alternate) {
7130 print "<tr class=\"dark\">\n";
7131 } else {
7132 print "<tr class=\"light\">\n";
7133 }
7134 $alternate ^= 1;
7135
7136 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7137
7138 print "</tr>\n";
7139 }
7140 print "</table>\n" .
7141 "</div>";
7142 git_footer_html();
7143 }
7144
7145 sub snapshot_name {
7146 my ($project, $hash) = @_;
7147
7148 # path/to/project.git -> project
7149 # path/to/project/.git -> project
7150 my $name = to_utf8($project);
7151 $name =~ s,([^/])/*\.git$,$1,;
7152 $name = basename($name);
7153 # sanitize name
7154 $name =~ s/[[:cntrl:]]/?/g;
7155
7156 my $ver = $hash;
7157 if ($hash =~ /^[0-9a-fA-F]+$/) {
7158 # shorten SHA-1 hash
7159 my $full_hash = git_get_full_hash($project, $hash);
7160 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7161 $ver = git_get_short_hash($project, $hash);
7162 }
7163 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7164 # tags don't need shortened SHA-1 hash
7165 $ver = $1;
7166 } else {
7167 # branches and other need shortened SHA-1 hash
7168 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
7169 $ver = $1;
7170 }
7171 $ver .= '-' . git_get_short_hash($project, $hash);
7172 }
7173 # in case of hierarchical branch names
7174 $ver =~ s!/!.!g;
7175
7176 # name = project-version_string
7177 $name = "$name-$ver";
7178
7179 return wantarray ? ($name, $name) : $name;
7180 }
7181
7182 sub exit_if_unmodified_since {
7183 my ($latest_epoch) = @_;
7184 our $cgi;
7185
7186 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7187 if (defined $if_modified) {
7188 my $since;
7189 if (eval { require HTTP::Date; 1; }) {
7190 $since = HTTP::Date::str2time($if_modified);
7191 } elsif (eval { require Time::ParseDate; 1; }) {
7192 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7193 }
7194 if (defined $since && $latest_epoch <= $since) {
7195 my %latest_date = parse_date($latest_epoch);
7196 print $cgi->header(
7197 -last_modified => $latest_date{'rfc2822'},
7198 -status => '304 Not Modified');
7199 goto DONE_GITWEB;
7200 }
7201 }
7202 }
7203
7204 sub git_snapshot {
7205 my $format = $input_params{'snapshot_format'};
7206 if (!@snapshot_fmts) {
7207 die_error(403, "Snapshots not allowed");
7208 }
7209 # default to first supported snapshot format
7210 $format ||= $snapshot_fmts[0];
7211 if ($format !~ m/^[a-z0-9]+$/) {
7212 die_error(400, "Invalid snapshot format parameter");
7213 } elsif (!exists($known_snapshot_formats{$format})) {
7214 die_error(400, "Unknown snapshot format");
7215 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7216 die_error(403, "Snapshot format not allowed");
7217 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7218 die_error(403, "Unsupported snapshot format");
7219 }
7220
7221 my $type = git_get_type("$hash^{}");
7222 if (!$type) {
7223 die_error(404, 'Object does not exist');
7224 } elsif ($type eq 'blob') {
7225 die_error(400, 'Object is not a tree-ish');
7226 }
7227
7228 my ($name, $prefix) = snapshot_name($project, $hash);
7229 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7230
7231 my %co = parse_commit($hash);
7232 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7233
7234 my $cmd = quote_command(
7235 git_cmd(), 'archive',
7236 "--format=$known_snapshot_formats{$format}{'format'}",
7237 "--prefix=$prefix/", $hash);
7238 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7239 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7240 }
7241
7242 $filename =~ s/(["\\])/\\$1/g;
7243 my %latest_date;
7244 if (%co) {
7245 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7246 }
7247
7248 print $cgi->header(
7249 -type => $known_snapshot_formats{$format}{'type'},
7250 -content_disposition => 'inline; filename="' . $filename . '"',
7251 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7252 -status => '200 OK');
7253
7254 open my $fd, "-|", $cmd
7255 or die_error(500, "Execute git-archive failed");
7256 binmode STDOUT, ':raw';
7257 print <$fd>;
7258 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7259 close $fd;
7260 }
7261
7262 sub git_log_generic {
7263 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7264
7265 my $head = git_get_head_hash($project);
7266 if (!defined $base) {
7267 $base = $head;
7268 }
7269 if (!defined $page) {
7270 $page = 0;
7271 }
7272 my $refs = git_get_references();
7273
7274 my $commit_hash = $base;
7275 if (defined $parent) {
7276 $commit_hash = "$parent..$base";
7277 }
7278 my @commitlist =
7279 parse_commits($commit_hash, 101, (100 * $page),
7280 defined $file_name ? ($file_name, "--full-history") : ());
7281
7282 my $ftype;
7283 if (!defined $file_hash && defined $file_name) {
7284 # some commits could have deleted file in question,
7285 # and not have it in tree, but one of them has to have it
7286 for (my $i = 0; $i < @commitlist; $i++) {
7287 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7288 last if defined $file_hash;
7289 }
7290 }
7291 if (defined $file_hash) {
7292 $ftype = git_get_type($file_hash);
7293 }
7294 if (defined $file_name && !defined $ftype) {
7295 die_error(500, "Unknown type of object");
7296 }
7297 my %co;
7298 if (defined $file_name) {
7299 %co = parse_commit($base)
7300 or die_error(404, "Unknown commit object");
7301 }
7302
7303
7304 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7305 my $next_link = '';
7306 if ($#commitlist >= 100) {
7307 $next_link =
7308 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7309 -accesskey => "n", -title => "Alt-n"}, "next");
7310 }
7311 my $patch_max = gitweb_get_feature('patches');
7312 if ($patch_max && !defined $file_name) {
7313 if ($patch_max < 0 || @commitlist <= $patch_max) {
7314 $paging_nav .= " &sdot; " .
7315 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7316 "patches");
7317 }
7318 }
7319
7320 git_header_html();
7321 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7322 if (defined $file_name) {
7323 git_print_header_div('commit', esc_html($co{'title'}), $base);
7324 } else {
7325 git_print_header_div('summary', $project)
7326 }
7327 git_print_page_path($file_name, $ftype, $hash_base)
7328 if (defined $file_name);
7329
7330 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7331 $file_name, $file_hash, $ftype);
7332
7333 git_footer_html();
7334 }
7335
7336 sub git_log {
7337 git_log_generic('log', \&git_log_body,
7338 $hash, $hash_parent);
7339 }
7340
7341 sub git_commit {
7342 $hash ||= $hash_base || "HEAD";
7343 my %co = parse_commit($hash)
7344 or die_error(404, "Unknown commit object");
7345
7346 my $parent = $co{'parent'};
7347 my $parents = $co{'parents'}; # listref
7348
7349 # we need to prepare $formats_nav before any parameter munging
7350 my $formats_nav;
7351 if (!defined $parent) {
7352 # --root commitdiff
7353 $formats_nav .= '(initial)';
7354 } elsif (@$parents == 1) {
7355 # single parent commit
7356 $formats_nav .=
7357 '(parent: ' .
7358 $cgi->a({-href => href(action=>"commit",
7359 hash=>$parent)},
7360 esc_html(substr($parent, 0, 7))) .
7361 ')';
7362 } else {
7363 # merge commit
7364 $formats_nav .=
7365 '(merge: ' .
7366 join(' ', map {
7367 $cgi->a({-href => href(action=>"commit",
7368 hash=>$_)},
7369 esc_html(substr($_, 0, 7)));
7370 } @$parents ) .
7371 ')';
7372 }
7373 if (gitweb_check_feature('patches') && @$parents <= 1) {
7374 $formats_nav .= " | " .
7375 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7376 "patch");
7377 }
7378
7379 if (!defined $parent) {
7380 $parent = "--root";
7381 }
7382 my @difftree;
7383 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7384 @diff_opts,
7385 (@$parents <= 1 ? $parent : '-c'),
7386 $hash, "--"
7387 or die_error(500, "Open git-diff-tree failed");
7388 @difftree = map { chomp; $_ } <$fd>;
7389 close $fd or die_error(404, "Reading git-diff-tree failed");
7390
7391 # non-textual hash id's can be cached
7392 my $expires;
7393 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7394 $expires = "+1d";
7395 }
7396 my $refs = git_get_references();
7397 my $ref = format_ref_marker($refs, $co{'id'});
7398
7399 git_header_html(undef, $expires);
7400 git_print_page_nav('commit', '',
7401 $hash, $co{'tree'}, $hash,
7402 $formats_nav);
7403
7404 if (defined $co{'parent'}) {
7405 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7406 } else {
7407 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7408 }
7409 print "<div class=\"title_text\">\n" .
7410 "<table class=\"object_header\">\n";
7411 git_print_authorship_rows(\%co);
7412 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7413 print "<tr>" .
7414 "<td>tree</td>" .
7415 "<td class=\"sha1\">" .
7416 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7417 class => "list"}, $co{'tree'}) .
7418 "</td>" .
7419 "<td class=\"link\">" .
7420 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7421 "tree");
7422 my $snapshot_links = format_snapshot_links($hash);
7423 if (defined $snapshot_links) {
7424 print " | " . $snapshot_links;
7425 }
7426 print "</td>" .
7427 "</tr>\n";
7428
7429 foreach my $par (@$parents) {
7430 print "<tr>" .
7431 "<td>parent</td>" .
7432 "<td class=\"sha1\">" .
7433 $cgi->a({-href => href(action=>"commit", hash=>$par),
7434 class => "list"}, $par) .
7435 "</td>" .
7436 "<td class=\"link\">" .
7437 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7438 " | " .
7439 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7440 "</td>" .
7441 "</tr>\n";
7442 }
7443 print "</table>".
7444 "</div>\n";
7445
7446 print "<div class=\"page_body\">\n";
7447 git_print_log($co{'comment'});
7448 print "</div>\n";
7449
7450 git_difftree_body(\@difftree, $hash, @$parents);
7451
7452 git_footer_html();
7453 }
7454
7455 sub git_object {
7456 # object is defined by:
7457 # - hash or hash_base alone
7458 # - hash_base and file_name
7459 my $type;
7460
7461 # - hash or hash_base alone
7462 if ($hash || ($hash_base && !defined $file_name)) {
7463 my $object_id = $hash || $hash_base;
7464
7465 open my $fd, "-|", quote_command(
7466 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7467 or die_error(404, "Object does not exist");
7468 $type = <$fd>;
7469 chomp $type;
7470 close $fd
7471 or die_error(404, "Object does not exist");
7472
7473 # - hash_base and file_name
7474 } elsif ($hash_base && defined $file_name) {
7475 $file_name =~ s,/+$,,;
7476
7477 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7478 or die_error(404, "Base object does not exist");
7479
7480 # here errors should not hapen
7481 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7482 or die_error(500, "Open git-ls-tree failed");
7483 my $line = <$fd>;
7484 close $fd;
7485
7486 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7487 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7488 die_error(404, "File or directory for given base does not exist");
7489 }
7490 $type = $2;
7491 $hash = $3;
7492 } else {
7493 die_error(400, "Not enough information to find object");
7494 }
7495
7496 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7497 hash=>$hash, hash_base=>$hash_base,
7498 file_name=>$file_name),
7499 -status => '302 Found');
7500 }
7501
7502 sub git_blobdiff {
7503 my $format = shift || 'html';
7504 my $diff_style = $input_params{'diff_style'} || 'inline';
7505
7506 my $fd;
7507 my @difftree;
7508 my %diffinfo;
7509 my $expires;
7510
7511 # preparing $fd and %diffinfo for git_patchset_body
7512 # new style URI
7513 if (defined $hash_base && defined $hash_parent_base) {
7514 if (defined $file_name) {
7515 # read raw output
7516 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7517 $hash_parent_base, $hash_base,
7518 "--", (defined $file_parent ? $file_parent : ()), $file_name
7519 or die_error(500, "Open git-diff-tree failed");
7520 @difftree = map { chomp; $_ } <$fd>;
7521 close $fd
7522 or die_error(404, "Reading git-diff-tree failed");
7523 @difftree
7524 or die_error(404, "Blob diff not found");
7525
7526 } elsif (defined $hash &&
7527 $hash =~ /[0-9a-fA-F]{40}/) {
7528 # try to find filename from $hash
7529
7530 # read filtered raw output
7531 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7532 $hash_parent_base, $hash_base, "--"
7533 or die_error(500, "Open git-diff-tree failed");
7534 @difftree =
7535 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7536 # $hash == to_id
7537 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7538 map { chomp; $_ } <$fd>;
7539 close $fd
7540 or die_error(404, "Reading git-diff-tree failed");
7541 @difftree
7542 or die_error(404, "Blob diff not found");
7543
7544 } else {
7545 die_error(400, "Missing one of the blob diff parameters");
7546 }
7547
7548 if (@difftree > 1) {
7549 die_error(400, "Ambiguous blob diff specification");
7550 }
7551
7552 %diffinfo = parse_difftree_raw_line($difftree[0]);
7553 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7554 $file_name ||= $diffinfo{'to_file'};
7555
7556 $hash_parent ||= $diffinfo{'from_id'};
7557 $hash ||= $diffinfo{'to_id'};
7558
7559 # non-textual hash id's can be cached
7560 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7561 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7562 $expires = '+1d';
7563 }
7564
7565 # open patch output
7566 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7567 '-p', ($format eq 'html' ? "--full-index" : ()),
7568 $hash_parent_base, $hash_base,
7569 "--", (defined $file_parent ? $file_parent : ()), $file_name
7570 or die_error(500, "Open git-diff-tree failed");
7571 }
7572
7573 # old/legacy style URI -- not generated anymore since 1.4.3.
7574 if (!%diffinfo) {
7575 die_error('404 Not Found', "Missing one of the blob diff parameters")
7576 }
7577
7578 # header
7579 if ($format eq 'html') {
7580 my $formats_nav =
7581 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7582 "raw");
7583 $formats_nav .= diff_style_nav($diff_style);
7584 git_header_html(undef, $expires);
7585 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7586 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7587 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7588 } else {
7589 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7590 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7591 }
7592 if (defined $file_name) {
7593 git_print_page_path($file_name, "blob", $hash_base);
7594 } else {
7595 print "<div class=\"page_path\"></div>\n";
7596 }
7597
7598 } elsif ($format eq 'plain') {
7599 print $cgi->header(
7600 -type => 'text/plain',
7601 -charset => 'utf-8',
7602 -expires => $expires,
7603 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7604
7605 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7606
7607 } else {
7608 die_error(400, "Unknown blobdiff format");
7609 }
7610
7611 # patch
7612 if ($format eq 'html') {
7613 print "<div class=\"page_body\">\n";
7614
7615 git_patchset_body($fd, $diff_style,
7616 [ \%diffinfo ], $hash_base, $hash_parent_base);
7617 close $fd;
7618
7619 print "</div>\n"; # class="page_body"
7620 git_footer_html();
7621
7622 } else {
7623 while (my $line = <$fd>) {
7624 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7625 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7626
7627 print $line;
7628
7629 last if $line =~ m!^\+\+\+!;
7630 }
7631 local $/ = undef;
7632 print <$fd>;
7633 close $fd;
7634 }
7635 }
7636
7637 sub git_blobdiff_plain {
7638 git_blobdiff('plain');
7639 }
7640
7641 # assumes that it is added as later part of already existing navigation,
7642 # so it returns "| foo | bar" rather than just "foo | bar"
7643 sub diff_style_nav {
7644 my ($diff_style, $is_combined) = @_;
7645 $diff_style ||= 'inline';
7646
7647 return "" if ($is_combined);
7648
7649 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7650 my %styles = @styles;
7651 @styles =
7652 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7653
7654 return join '',
7655 map { " | ".$_ }
7656 map {
7657 $_ eq $diff_style ? $styles{$_} :
7658 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7659 } @styles;
7660 }
7661
7662 sub git_commitdiff {
7663 my %params = @_;
7664 my $format = $params{-format} || 'html';
7665 my $diff_style = $input_params{'diff_style'} || 'inline';
7666
7667 my ($patch_max) = gitweb_get_feature('patches');
7668 if ($format eq 'patch') {
7669 die_error(403, "Patch view not allowed") unless $patch_max;
7670 }
7671
7672 $hash ||= $hash_base || "HEAD";
7673 my %co = parse_commit($hash)
7674 or die_error(404, "Unknown commit object");
7675
7676 # choose format for commitdiff for merge
7677 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7678 $hash_parent = '--cc';
7679 }
7680 # we need to prepare $formats_nav before almost any parameter munging
7681 my $formats_nav;
7682 if ($format eq 'html') {
7683 $formats_nav =
7684 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7685 "raw");
7686 if ($patch_max && @{$co{'parents'}} <= 1) {
7687 $formats_nav .= " | " .
7688 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7689 "patch");
7690 }
7691 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7692
7693 if (defined $hash_parent &&
7694 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7695 # commitdiff with two commits given
7696 my $hash_parent_short = $hash_parent;
7697 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7698 $hash_parent_short = substr($hash_parent, 0, 7);
7699 }
7700 $formats_nav .=
7701 ' (from';
7702 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7703 if ($co{'parents'}[$i] eq $hash_parent) {
7704 $formats_nav .= ' parent ' . ($i+1);
7705 last;
7706 }
7707 }
7708 $formats_nav .= ': ' .
7709 $cgi->a({-href => href(-replay=>1,
7710 hash=>$hash_parent, hash_base=>undef)},
7711 esc_html($hash_parent_short)) .
7712 ')';
7713 } elsif (!$co{'parent'}) {
7714 # --root commitdiff
7715 $formats_nav .= ' (initial)';
7716 } elsif (scalar @{$co{'parents'}} == 1) {
7717 # single parent commit
7718 $formats_nav .=
7719 ' (parent: ' .
7720 $cgi->a({-href => href(-replay=>1,
7721 hash=>$co{'parent'}, hash_base=>undef)},
7722 esc_html(substr($co{'parent'}, 0, 7))) .
7723 ')';
7724 } else {
7725 # merge commit
7726 if ($hash_parent eq '--cc') {
7727 $formats_nav .= ' | ' .
7728 $cgi->a({-href => href(-replay=>1,
7729 hash=>$hash, hash_parent=>'-c')},
7730 'combined');
7731 } else { # $hash_parent eq '-c'
7732 $formats_nav .= ' | ' .
7733 $cgi->a({-href => href(-replay=>1,
7734 hash=>$hash, hash_parent=>'--cc')},
7735 'compact');
7736 }
7737 $formats_nav .=
7738 ' (merge: ' .
7739 join(' ', map {
7740 $cgi->a({-href => href(-replay=>1,
7741 hash=>$_, hash_base=>undef)},
7742 esc_html(substr($_, 0, 7)));
7743 } @{$co{'parents'}} ) .
7744 ')';
7745 }
7746 }
7747
7748 my $hash_parent_param = $hash_parent;
7749 if (!defined $hash_parent_param) {
7750 # --cc for multiple parents, --root for parentless
7751 $hash_parent_param =
7752 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7753 }
7754
7755 # read commitdiff
7756 my $fd;
7757 my @difftree;
7758 if ($format eq 'html') {
7759 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7760 "--no-commit-id", "--patch-with-raw", "--full-index",
7761 $hash_parent_param, $hash, "--"
7762 or die_error(500, "Open git-diff-tree failed");
7763
7764 while (my $line = <$fd>) {
7765 chomp $line;
7766 # empty line ends raw part of diff-tree output
7767 last unless $line;
7768 push @difftree, scalar parse_difftree_raw_line($line);
7769 }
7770
7771 } elsif ($format eq 'plain') {
7772 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7773 '-p', $hash_parent_param, $hash, "--"
7774 or die_error(500, "Open git-diff-tree failed");
7775 } elsif ($format eq 'patch') {
7776 # For commit ranges, we limit the output to the number of
7777 # patches specified in the 'patches' feature.
7778 # For single commits, we limit the output to a single patch,
7779 # diverging from the git-format-patch default.
7780 my @commit_spec = ();
7781 if ($hash_parent) {
7782 if ($patch_max > 0) {
7783 push @commit_spec, "-$patch_max";
7784 }
7785 push @commit_spec, '-n', "$hash_parent..$hash";
7786 } else {
7787 if ($params{-single}) {
7788 push @commit_spec, '-1';
7789 } else {
7790 if ($patch_max > 0) {
7791 push @commit_spec, "-$patch_max";
7792 }
7793 push @commit_spec, "-n";
7794 }
7795 push @commit_spec, '--root', $hash;
7796 }
7797 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7798 '--encoding=utf8', '--stdout', @commit_spec
7799 or die_error(500, "Open git-format-patch failed");
7800 } else {
7801 die_error(400, "Unknown commitdiff format");
7802 }
7803
7804 # non-textual hash id's can be cached
7805 my $expires;
7806 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7807 $expires = "+1d";
7808 }
7809
7810 # write commit message
7811 if ($format eq 'html') {
7812 my $refs = git_get_references();
7813 my $ref = format_ref_marker($refs, $co{'id'});
7814
7815 git_header_html(undef, $expires);
7816 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7817 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7818 print "<div class=\"title_text\">\n" .
7819 "<table class=\"object_header\">\n";
7820 git_print_authorship_rows(\%co);
7821 print "</table>".
7822 "</div>\n";
7823 print "<div class=\"page_body\">\n";
7824 if (@{$co{'comment'}} > 1) {
7825 print "<div class=\"log\">\n";
7826 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7827 print "</div>\n"; # class="log"
7828 }
7829
7830 } elsif ($format eq 'plain') {
7831 my $refs = git_get_references("tags");
7832 my $tagname = git_get_rev_name_tags($hash);
7833 my $filename = basename($project) . "-$hash.patch";
7834
7835 print $cgi->header(
7836 -type => 'text/plain',
7837 -charset => 'utf-8',
7838 -expires => $expires,
7839 -content_disposition => 'inline; filename="' . "$filename" . '"');
7840 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7841 print "From: " . to_utf8($co{'author'}) . "\n";
7842 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7843 print "Subject: " . to_utf8($co{'title'}) . "\n";
7844
7845 print "X-Git-Tag: $tagname\n" if $tagname;
7846 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7847
7848 foreach my $line (@{$co{'comment'}}) {
7849 print to_utf8($line) . "\n";
7850 }
7851 print "---\n\n";
7852 } elsif ($format eq 'patch') {
7853 my $filename = basename($project) . "-$hash.patch";
7854
7855 print $cgi->header(
7856 -type => 'text/plain',
7857 -charset => 'utf-8',
7858 -expires => $expires,
7859 -content_disposition => 'inline; filename="' . "$filename" . '"');
7860 }
7861
7862 # write patch
7863 if ($format eq 'html') {
7864 my $use_parents = !defined $hash_parent ||
7865 $hash_parent eq '-c' || $hash_parent eq '--cc';
7866 git_difftree_body(\@difftree, $hash,
7867 $use_parents ? @{$co{'parents'}} : $hash_parent);
7868 print "<br/>\n";
7869
7870 git_patchset_body($fd, $diff_style,
7871 \@difftree, $hash,
7872 $use_parents ? @{$co{'parents'}} : $hash_parent);
7873 close $fd;
7874 print "</div>\n"; # class="page_body"
7875 git_footer_html();
7876
7877 } elsif ($format eq 'plain') {
7878 local $/ = undef;
7879 print <$fd>;
7880 close $fd
7881 or print "Reading git-diff-tree failed\n";
7882 } elsif ($format eq 'patch') {
7883 local $/ = undef;
7884 print <$fd>;
7885 close $fd
7886 or print "Reading git-format-patch failed\n";
7887 }
7888 }
7889
7890 sub git_commitdiff_plain {
7891 git_commitdiff(-format => 'plain');
7892 }
7893
7894 # format-patch-style patches
7895 sub git_patch {
7896 git_commitdiff(-format => 'patch', -single => 1);
7897 }
7898
7899 sub git_patches {
7900 git_commitdiff(-format => 'patch');
7901 }
7902
7903 sub git_history {
7904 git_log_generic('history', \&git_history_body,
7905 $hash_base, $hash_parent_base,
7906 $file_name, $hash);
7907 }
7908
7909 sub git_search {
7910 $searchtype ||= 'commit';
7911
7912 # check if appropriate features are enabled
7913 gitweb_check_feature('search')
7914 or die_error(403, "Search is disabled");
7915 if ($searchtype eq 'pickaxe') {
7916 # pickaxe may take all resources of your box and run for several minutes
7917 # with every query - so decide by yourself how public you make this feature
7918 gitweb_check_feature('pickaxe')
7919 or die_error(403, "Pickaxe search is disabled");
7920 }
7921 if ($searchtype eq 'grep') {
7922 # grep search might be potentially CPU-intensive, too
7923 gitweb_check_feature('grep')
7924 or die_error(403, "Grep search is disabled");
7925 }
7926
7927 if (!defined $searchtext) {
7928 die_error(400, "Text field is empty");
7929 }
7930 if (!defined $hash) {
7931 $hash = git_get_head_hash($project);
7932 }
7933 my %co = parse_commit($hash);
7934 if (!%co) {
7935 die_error(404, "Unknown commit object");
7936 }
7937 if (!defined $page) {
7938 $page = 0;
7939 }
7940
7941 if ($searchtype eq 'commit' ||
7942 $searchtype eq 'author' ||
7943 $searchtype eq 'committer') {
7944 git_search_message(%co);
7945 } elsif ($searchtype eq 'pickaxe') {
7946 git_search_changes(%co);
7947 } elsif ($searchtype eq 'grep') {
7948 git_search_files(%co);
7949 } else {
7950 die_error(400, "Unknown search type");
7951 }
7952 }
7953
7954 sub git_search_help {
7955 git_header_html();
7956 git_print_page_nav('','', $hash,$hash,$hash);
7957 print <<EOT;
7958 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7959 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7960 the pattern entered is recognized as the POSIX extended
7961 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7962 insensitive).</p>
7963 <dl>
7964 <dt><b>commit</b></dt>
7965 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7966 EOT
7967 my $have_grep = gitweb_check_feature('grep');
7968 if ($have_grep) {
7969 print <<EOT;
7970 <dt><b>grep</b></dt>
7971 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7972 a different one) are searched for the given pattern. On large trees, this search can take
7973 a while and put some strain on the server, so please use it with some consideration. Note that
7974 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7975 case-sensitive.</dd>
7976 EOT
7977 }
7978 print <<EOT;
7979 <dt><b>author</b></dt>
7980 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7981 <dt><b>committer</b></dt>
7982 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7983 EOT
7984 my $have_pickaxe = gitweb_check_feature('pickaxe');
7985 if ($have_pickaxe) {
7986 print <<EOT;
7987 <dt><b>pickaxe</b></dt>
7988 <dd>All commits that caused the string to appear or disappear from any file (changes that
7989 added, removed or "modified" the string) will be listed. This search can take a while and
7990 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7991 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7992 EOT
7993 }
7994 print "</dl>\n";
7995 git_footer_html();
7996 }
7997
7998 sub git_shortlog {
7999 git_log_generic('shortlog', \&git_shortlog_body,
8000 $hash, $hash_parent);
8001 }
8002
8003 ## ......................................................................
8004 ## feeds (RSS, Atom; OPML)
8005
8006 sub git_feed {
8007 my $format = shift || 'atom';
8008 my $have_blame = gitweb_check_feature('blame');
8009
8010 # Atom: http://www.atomenabled.org/developers/syndication/
8011 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8012 if ($format ne 'rss' && $format ne 'atom') {
8013 die_error(400, "Unknown web feed format");
8014 }
8015
8016 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8017 my $head = $hash || 'HEAD';
8018 my @commitlist = parse_commits($head, 150, 0, $file_name);
8019
8020 my %latest_commit;
8021 my %latest_date;
8022 my $content_type = "application/$format+xml";
8023 if (defined $cgi->http('HTTP_ACCEPT') &&
8024 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8025 # browser (feed reader) prefers text/xml
8026 $content_type = 'text/xml';
8027 }
8028 if (defined($commitlist[0])) {
8029 %latest_commit = %{$commitlist[0]};
8030 my $latest_epoch = $latest_commit{'committer_epoch'};
8031 exit_if_unmodified_since($latest_epoch);
8032 %latest_date = parse_date($latest_epoch, $latest_commit{'comitter_tz'});
8033 }
8034 print $cgi->header(
8035 -type => $content_type,
8036 -charset => 'utf-8',
8037 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8038 -status => '200 OK');
8039
8040 # Optimization: skip generating the body if client asks only
8041 # for Last-Modified date.
8042 return if ($cgi->request_method() eq 'HEAD');
8043
8044 # header variables
8045 my $title = "$site_name - $project/$action";
8046 my $feed_type = 'log';
8047 if (defined $hash) {
8048 $title .= " - '$hash'";
8049 $feed_type = 'branch log';
8050 if (defined $file_name) {
8051 $title .= " :: $file_name";
8052 $feed_type = 'history';
8053 }
8054 } elsif (defined $file_name) {
8055 $title .= " - $file_name";
8056 $feed_type = 'history';
8057 }
8058 $title .= " $feed_type";
8059 my $descr = git_get_project_description($project);
8060 if (defined $descr) {
8061 $descr = esc_html($descr);
8062 } else {
8063 $descr = "$project " .
8064 ($format eq 'rss' ? 'RSS' : 'Atom') .
8065 " feed";
8066 }
8067 my $owner = git_get_project_owner($project);
8068 $owner = esc_html($owner);
8069
8070 #header
8071 my $alt_url;
8072 if (defined $file_name) {
8073 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8074 } elsif (defined $hash) {
8075 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8076 } else {
8077 $alt_url = href(-full=>1, action=>"summary");
8078 }
8079 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8080 if ($format eq 'rss') {
8081 print <<XML;
8082 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8083 <channel>
8084 XML
8085 print "<title>$title</title>\n" .
8086 "<link>$alt_url</link>\n" .
8087 "<description>$descr</description>\n" .
8088 "<language>en</language>\n" .
8089 # project owner is responsible for 'editorial' content
8090 "<managingEditor>$owner</managingEditor>\n";
8091 if (defined $logo || defined $favicon) {
8092 # prefer the logo to the favicon, since RSS
8093 # doesn't allow both
8094 my $img = esc_url($logo || $favicon);
8095 print "<image>\n" .
8096 "<url>$img</url>\n" .
8097 "<title>$title</title>\n" .
8098 "<link>$alt_url</link>\n" .
8099 "</image>\n";
8100 }
8101 if (%latest_date) {
8102 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8103 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8104 }
8105 print "<generator>gitweb v.$version/$git_version</generator>\n";
8106 } elsif ($format eq 'atom') {
8107 print <<XML;
8108 <feed xmlns="http://www.w3.org/2005/Atom">
8109 XML
8110 print "<title>$title</title>\n" .
8111 "<subtitle>$descr</subtitle>\n" .
8112 '<link rel="alternate" type="text/html" href="' .
8113 $alt_url . '" />' . "\n" .
8114 '<link rel="self" type="' . $content_type . '" href="' .
8115 $cgi->self_url() . '" />' . "\n" .
8116 "<id>" . href(-full=>1) . "</id>\n" .
8117 # use project owner for feed author
8118 "<author><name>$owner</name></author>\n";
8119 if (defined $favicon) {
8120 print "<icon>" . esc_url($favicon) . "</icon>\n";
8121 }
8122 if (defined $logo) {
8123 # not twice as wide as tall: 72 x 27 pixels
8124 print "<logo>" . esc_url($logo) . "</logo>\n";
8125 }
8126 if (! %latest_date) {
8127 # dummy date to keep the feed valid until commits trickle in:
8128 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8129 } else {
8130 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8131 }
8132 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8133 }
8134
8135 # contents
8136 for (my $i = 0; $i <= $#commitlist; $i++) {
8137 my %co = %{$commitlist[$i]};
8138 my $commit = $co{'id'};
8139 # we read 150, we always show 30 and the ones more recent than 48 hours
8140 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8141 last;
8142 }
8143 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8144
8145 # get list of changed files
8146 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8147 $co{'parent'} || "--root",
8148 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8149 or next;
8150 my @difftree = map { chomp; $_ } <$fd>;
8151 close $fd
8152 or next;
8153
8154 # print element (entry, item)
8155 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8156 if ($format eq 'rss') {
8157 print "<item>\n" .
8158 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8159 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8160 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8161 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8162 "<link>$co_url</link>\n" .
8163 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8164 "<content:encoded>" .
8165 "<![CDATA[\n";
8166 } elsif ($format eq 'atom') {
8167 print "<entry>\n" .
8168 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8169 "<updated>$cd{'iso-8601'}</updated>\n" .
8170 "<author>\n" .
8171 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8172 if ($co{'author_email'}) {
8173 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8174 }
8175 print "</author>\n" .
8176 # use committer for contributor
8177 "<contributor>\n" .
8178 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8179 if ($co{'committer_email'}) {
8180 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8181 }
8182 print "</contributor>\n" .
8183 "<published>$cd{'iso-8601'}</published>\n" .
8184 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8185 "<id>$co_url</id>\n" .
8186 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8187 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8188 }
8189 my $comment = $co{'comment'};
8190 print "<pre>\n";
8191 foreach my $line (@$comment) {
8192 $line = esc_html($line);
8193 print "$line\n";
8194 }
8195 print "</pre><ul>\n";
8196 foreach my $difftree_line (@difftree) {
8197 my %difftree = parse_difftree_raw_line($difftree_line);
8198 next if !$difftree{'from_id'};
8199
8200 my $file = $difftree{'file'} || $difftree{'to_file'};
8201
8202 print "<li>" .
8203 "[" .
8204 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8205 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8206 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8207 file_name=>$file, file_parent=>$difftree{'from_file'}),
8208 -title => "diff"}, 'D');
8209 if ($have_blame) {
8210 print $cgi->a({-href => href(-full=>1, action=>"blame",
8211 file_name=>$file, hash_base=>$commit),
8212 -title => "blame"}, 'B');
8213 }
8214 # if this is not a feed of a file history
8215 if (!defined $file_name || $file_name ne $file) {
8216 print $cgi->a({-href => href(-full=>1, action=>"history",
8217 file_name=>$file, hash=>$commit),
8218 -title => "history"}, 'H');
8219 }
8220 $file = esc_path($file);
8221 print "] ".
8222 "$file</li>\n";
8223 }
8224 if ($format eq 'rss') {
8225 print "</ul>]]>\n" .
8226 "</content:encoded>\n" .
8227 "</item>\n";
8228 } elsif ($format eq 'atom') {
8229 print "</ul>\n</div>\n" .
8230 "</content>\n" .
8231 "</entry>\n";
8232 }
8233 }
8234
8235 # end of feed
8236 if ($format eq 'rss') {
8237 print "</channel>\n</rss>\n";
8238 } elsif ($format eq 'atom') {
8239 print "</feed>\n";
8240 }
8241 }
8242
8243 sub git_rss {
8244 git_feed('rss');
8245 }
8246
8247 sub git_atom {
8248 git_feed('atom');
8249 }
8250
8251 sub git_opml {
8252 my @list = git_get_projects_list($project_filter, $strict_export);
8253 if (!@list) {
8254 die_error(404, "No projects found");
8255 }
8256
8257 print $cgi->header(
8258 -type => 'text/xml',
8259 -charset => 'utf-8',
8260 -content_disposition => 'inline; filename="opml.xml"');
8261
8262 my $title = esc_html($site_name);
8263 my $filter = " within subdirectory ";
8264 if (defined $project_filter) {
8265 $filter .= esc_html($project_filter);
8266 } else {
8267 $filter = "";
8268 }
8269 print <<XML;
8270 <?xml version="1.0" encoding="utf-8"?>
8271 <opml version="1.0">
8272 <head>
8273 <title>$title OPML Export$filter</title>
8274 </head>
8275 <body>
8276 <outline text="git RSS feeds">
8277 XML
8278
8279 foreach my $pr (@list) {
8280 my %proj = %$pr;
8281 my $head = git_get_head_hash($proj{'path'});
8282 if (!defined $head) {
8283 next;
8284 }
8285 $git_dir = "$projectroot/$proj{'path'}";
8286 my %co = parse_commit($head);
8287 if (!%co) {
8288 next;
8289 }
8290
8291 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8292 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8293 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8294 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8295 }
8296 print <<XML;
8297 </outline>
8298 </body>
8299 </opml>
8300 XML
8301 }
This page took 4.861882 seconds and 3 git commands to generate.