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