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