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