]> Lady’s Gitweb - Gitweb/blob - gitweb.perl
gitweb: Describe CSSMIN and JSMIN in gitweb/INSTALL
[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(/\t+/);
3565 if (defined $exts) {
3566 my @exts = split(/\s+/, $exts);
3567 foreach my $ext (@exts) {
3568 $mimemap{$ext} = $mimetype;
3569 }
3570 }
3571 }
3572 close($mh);
3573
3574 $filename =~ /\.([^.]*)$/;
3575 return $mimemap{$1};
3576 }
3577
3578 sub mimetype_guess {
3579 my $filename = shift;
3580 my $mime;
3581 $filename =~ /\./ or return undef;
3582
3583 if ($mimetypes_file) {
3584 my $file = $mimetypes_file;
3585 if ($file !~ m!^/!) { # if it is relative path
3586 # it is relative to project
3587 $file = "$projectroot/$project/$file";
3588 }
3589 $mime = mimetype_guess_file($filename, $file);
3590 }
3591 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3592 return $mime;
3593 }
3594
3595 sub blob_mimetype {
3596 my $fd = shift;
3597 my $filename = shift;
3598
3599 if ($filename) {
3600 my $mime = mimetype_guess($filename);
3601 $mime and return $mime;
3602 }
3603
3604 # just in case
3605 return $default_blob_plain_mimetype unless $fd;
3606
3607 if (-T $fd) {
3608 return 'text/plain';
3609 } elsif (! $filename) {
3610 return 'application/octet-stream';
3611 } elsif ($filename =~ m/\.png$/i) {
3612 return 'image/png';
3613 } elsif ($filename =~ m/\.gif$/i) {
3614 return 'image/gif';
3615 } elsif ($filename =~ m/\.jpe?g$/i) {
3616 return 'image/jpeg';
3617 } else {
3618 return 'application/octet-stream';
3619 }
3620 }
3621
3622 sub blob_contenttype {
3623 my ($fd, $file_name, $type) = @_;
3624
3625 $type ||= blob_mimetype($fd, $file_name);
3626 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3627 $type .= "; charset=$default_text_plain_charset";
3628 }
3629
3630 return $type;
3631 }
3632
3633 # guess file syntax for syntax highlighting; return undef if no highlighting
3634 # the name of syntax can (in the future) depend on syntax highlighter used
3635 sub guess_file_syntax {
3636 my ($highlight, $mimetype, $file_name) = @_;
3637 return undef unless ($highlight && defined $file_name);
3638 my $basename = basename($file_name, '.in');
3639 return $highlight_basename{$basename}
3640 if exists $highlight_basename{$basename};
3641
3642 $basename =~ /\.([^.]*)$/;
3643 my $ext = $1 or return undef;
3644 return $highlight_ext{$ext}
3645 if exists $highlight_ext{$ext};
3646
3647 return undef;
3648 }
3649
3650 # run highlighter and return FD of its output,
3651 # or return original FD if no highlighting
3652 sub run_highlighter {
3653 my ($fd, $highlight, $syntax) = @_;
3654 return $fd unless ($highlight && defined $syntax);
3655
3656 close $fd;
3657 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3658 quote_command($highlight_bin).
3659 " --replace-tabs=8 --fragment --syntax $syntax |"
3660 or die_error(500, "Couldn't open file or run syntax highlighter");
3661 return $fd;
3662 }
3663
3664 ## ======================================================================
3665 ## functions printing HTML: header, footer, error page
3666
3667 sub get_page_title {
3668 my $title = to_utf8($site_name);
3669
3670 return $title unless (defined $project);
3671 $title .= " - " . to_utf8($project);
3672
3673 return $title unless (defined $action);
3674 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3675
3676 return $title unless (defined $file_name);
3677 $title .= " - " . esc_path($file_name);
3678 if ($action eq "tree" && $file_name !~ m|/$|) {
3679 $title .= "/";
3680 }
3681
3682 return $title;
3683 }
3684
3685 sub print_feed_meta {
3686 if (defined $project) {
3687 my %href_params = get_feed_info();
3688 if (!exists $href_params{'-title'}) {
3689 $href_params{'-title'} = 'log';
3690 }
3691
3692 foreach my $format (qw(RSS Atom)) {
3693 my $type = lc($format);
3694 my %link_attr = (
3695 '-rel' => 'alternate',
3696 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3697 '-type' => "application/$type+xml"
3698 );
3699
3700 $href_params{'action'} = $type;
3701 $link_attr{'-href'} = href(%href_params);
3702 print "<link ".
3703 "rel=\"$link_attr{'-rel'}\" ".
3704 "title=\"$link_attr{'-title'}\" ".
3705 "href=\"$link_attr{'-href'}\" ".
3706 "type=\"$link_attr{'-type'}\" ".
3707 "/>\n";
3708
3709 $href_params{'extra_options'} = '--no-merges';
3710 $link_attr{'-href'} = href(%href_params);
3711 $link_attr{'-title'} .= ' (no merges)';
3712 print "<link ".
3713 "rel=\"$link_attr{'-rel'}\" ".
3714 "title=\"$link_attr{'-title'}\" ".
3715 "href=\"$link_attr{'-href'}\" ".
3716 "type=\"$link_attr{'-type'}\" ".
3717 "/>\n";
3718 }
3719
3720 } else {
3721 printf('<link rel="alternate" title="%s projects list" '.
3722 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3723 esc_attr($site_name), href(project=>undef, action=>"project_index"));
3724 printf('<link rel="alternate" title="%s projects feeds" '.
3725 'href="%s" type="text/x-opml" />'."\n",
3726 esc_attr($site_name), href(project=>undef, action=>"opml"));
3727 }
3728 }
3729
3730 sub git_header_html {
3731 my $status = shift || "200 OK";
3732 my $expires = shift;
3733 my %opts = @_;
3734
3735 my $title = get_page_title();
3736 my $content_type;
3737 # require explicit support from the UA if we are to send the page as
3738 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3739 # we have to do this because MSIE sometimes globs '*/*', pretending to
3740 # support xhtml+xml but choking when it gets what it asked for.
3741 if (defined $cgi->http('HTTP_ACCEPT') &&
3742 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3743 $cgi->Accept('application/xhtml+xml') != 0) {
3744 $content_type = 'application/xhtml+xml';
3745 } else {
3746 $content_type = 'text/html';
3747 }
3748 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3749 -status=> $status, -expires => $expires)
3750 unless ($opts{'-no_http_header'});
3751 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3752 print <<EOF;
3753 <?xml version="1.0" encoding="utf-8"?>
3754 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3755 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3756 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3757 <!-- git core binaries version $git_version -->
3758 <head>
3759 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3760 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3761 <meta name="robots" content="index, nofollow"/>
3762 <title>$title</title>
3763 EOF
3764 # the stylesheet, favicon etc urls won't work correctly with path_info
3765 # unless we set the appropriate base URL
3766 if ($ENV{'PATH_INFO'}) {
3767 print "<base href=\"".esc_url($base_url)."\" />\n";
3768 }
3769 # print out each stylesheet that exist, providing backwards capability
3770 # for those people who defined $stylesheet in a config file
3771 if (defined $stylesheet) {
3772 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3773 } else {
3774 foreach my $stylesheet (@stylesheets) {
3775 next unless $stylesheet;
3776 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3777 }
3778 }
3779 print_feed_meta()
3780 if ($status eq '200 OK');
3781 if (defined $favicon) {
3782 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
3783 }
3784
3785 print "</head>\n" .
3786 "<body>\n";
3787
3788 if (defined $site_header && -f $site_header) {
3789 insert_file($site_header);
3790 }
3791
3792 print "<div class=\"page_header\">\n";
3793 if (defined $logo) {
3794 print $cgi->a({-href => esc_url($logo_url),
3795 -title => $logo_label},
3796 $cgi->img({-src => esc_url($logo),
3797 -width => 72, -height => 27,
3798 -alt => "git",
3799 -class => "logo"}));
3800 }
3801 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3802 if (defined $project) {
3803 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3804 if (defined $action) {
3805 my $action_print = $action ;
3806 if (defined $opts{-action_extra}) {
3807 $action_print = $cgi->a({-href => href(action=>$action)},
3808 $action);
3809 }
3810 print " / $action_print";
3811 }
3812 if (defined $opts{-action_extra}) {
3813 print " / $opts{-action_extra}";
3814 }
3815 print "\n";
3816 }
3817 print "</div>\n";
3818
3819 my $have_search = gitweb_check_feature('search');
3820 if (defined $project && $have_search) {
3821 if (!defined $searchtext) {
3822 $searchtext = "";
3823 }
3824 my $search_hash;
3825 if (defined $hash_base) {
3826 $search_hash = $hash_base;
3827 } elsif (defined $hash) {
3828 $search_hash = $hash;
3829 } else {
3830 $search_hash = "HEAD";
3831 }
3832 my $action = $my_uri;
3833 my $use_pathinfo = gitweb_check_feature('pathinfo');
3834 if ($use_pathinfo) {
3835 $action .= "/".esc_url($project);
3836 }
3837 print $cgi->startform(-method => "get", -action => $action) .
3838 "<div class=\"search\">\n" .
3839 (!$use_pathinfo &&
3840 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3841 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3842 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3843 $cgi->popup_menu(-name => 'st', -default => 'commit',
3844 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3845 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3846 " search:\n",
3847 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3848 "<span title=\"Extended regular expression\">" .
3849 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3850 -checked => $search_use_regexp) .
3851 "</span>" .
3852 "</div>" .
3853 $cgi->end_form() . "\n";
3854 }
3855 }
3856
3857 sub git_footer_html {
3858 my $feed_class = 'rss_logo';
3859
3860 print "<div class=\"page_footer\">\n";
3861 if (defined $project) {
3862 my $descr = git_get_project_description($project);
3863 if (defined $descr) {
3864 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3865 }
3866
3867 my %href_params = get_feed_info();
3868 if (!%href_params) {
3869 $feed_class .= ' generic';
3870 }
3871 $href_params{'-title'} ||= 'log';
3872
3873 foreach my $format (qw(RSS Atom)) {
3874 $href_params{'action'} = lc($format);
3875 print $cgi->a({-href => href(%href_params),
3876 -title => "$href_params{'-title'} $format feed",
3877 -class => $feed_class}, $format)."\n";
3878 }
3879
3880 } else {
3881 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3882 -class => $feed_class}, "OPML") . " ";
3883 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3884 -class => $feed_class}, "TXT") . "\n";
3885 }
3886 print "</div>\n"; # class="page_footer"
3887
3888 if (defined $t0 && gitweb_check_feature('timed')) {
3889 print "<div id=\"generating_info\">\n";
3890 print 'This page took '.
3891 '<span id="generating_time" class="time_span">'.
3892 tv_interval($t0, [ gettimeofday() ]).
3893 ' seconds </span>'.
3894 ' and '.
3895 '<span id="generating_cmd">'.
3896 $number_of_git_cmds.
3897 '</span> git commands '.
3898 " to generate.\n";
3899 print "</div>\n"; # class="page_footer"
3900 }
3901
3902 if (defined $site_footer && -f $site_footer) {
3903 insert_file($site_footer);
3904 }
3905
3906 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
3907 if (defined $action &&
3908 $action eq 'blame_incremental') {
3909 print qq!<script type="text/javascript">\n!.
3910 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3911 qq! "!. href() .qq!");\n!.
3912 qq!</script>\n!;
3913 } else {
3914 my ($jstimezone, $tz_cookie, $datetime_class) =
3915 gitweb_get_feature('javascript-timezone');
3916
3917 print qq!<script type="text/javascript">\n!.
3918 qq!window.onload = function () {\n!;
3919 if (gitweb_check_feature('javascript-actions')) {
3920 print qq! fixLinks();\n!;
3921 }
3922 if ($jstimezone && $tz_cookie && $datetime_class) {
3923 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
3924 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
3925 }
3926 print qq!};\n!.
3927 qq!</script>\n!;
3928 }
3929
3930 print "</body>\n" .
3931 "</html>";
3932 }
3933
3934 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3935 # Example: die_error(404, 'Hash not found')
3936 # By convention, use the following status codes (as defined in RFC 2616):
3937 # 400: Invalid or missing CGI parameters, or
3938 # requested object exists but has wrong type.
3939 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3940 # this server or project.
3941 # 404: Requested object/revision/project doesn't exist.
3942 # 500: The server isn't configured properly, or
3943 # an internal error occurred (e.g. failed assertions caused by bugs), or
3944 # an unknown error occurred (e.g. the git binary died unexpectedly).
3945 # 503: The server is currently unavailable (because it is overloaded,
3946 # or down for maintenance). Generally, this is a temporary state.
3947 sub die_error {
3948 my $status = shift || 500;
3949 my $error = esc_html(shift) || "Internal Server Error";
3950 my $extra = shift;
3951 my %opts = @_;
3952
3953 my %http_responses = (
3954 400 => '400 Bad Request',
3955 403 => '403 Forbidden',
3956 404 => '404 Not Found',
3957 500 => '500 Internal Server Error',
3958 503 => '503 Service Unavailable',
3959 );
3960 git_header_html($http_responses{$status}, undef, %opts);
3961 print <<EOF;
3962 <div class="page_body">
3963 <br /><br />
3964 $status - $error
3965 <br />
3966 EOF
3967 if (defined $extra) {
3968 print "<hr />\n" .
3969 "$extra\n";
3970 }
3971 print "</div>\n";
3972
3973 git_footer_html();
3974 goto DONE_GITWEB
3975 unless ($opts{'-error_handler'});
3976 }
3977
3978 ## ----------------------------------------------------------------------
3979 ## functions printing or outputting HTML: navigation
3980
3981 sub git_print_page_nav {
3982 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3983 $extra = '' if !defined $extra; # pager or formats
3984
3985 my @navs = qw(summary shortlog log commit commitdiff tree);
3986 if ($suppress) {
3987 @navs = grep { $_ ne $suppress } @navs;
3988 }
3989
3990 my %arg = map { $_ => {action=>$_} } @navs;
3991 if (defined $head) {
3992 for (qw(commit commitdiff)) {
3993 $arg{$_}{'hash'} = $head;
3994 }
3995 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3996 for (qw(shortlog log)) {
3997 $arg{$_}{'hash'} = $head;
3998 }
3999 }
4000 }
4001
4002 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4003 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4004
4005 my @actions = gitweb_get_feature('actions');
4006 my %repl = (
4007 '%' => '%',
4008 'n' => $project, # project name
4009 'f' => $git_dir, # project path within filesystem
4010 'h' => $treehead || '', # current hash ('h' parameter)
4011 'b' => $treebase || '', # hash base ('hb' parameter)
4012 );
4013 while (@actions) {
4014 my ($label, $link, $pos) = splice(@actions,0,3);
4015 # insert
4016 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4017 # munch munch
4018 $link =~ s/%([%nfhb])/$repl{$1}/g;
4019 $arg{$label}{'_href'} = $link;
4020 }
4021
4022 print "<div class=\"page_nav\">\n" .
4023 (join " | ",
4024 map { $_ eq $current ?
4025 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4026 } @navs);
4027 print "<br/>\n$extra<br/>\n" .
4028 "</div>\n";
4029 }
4030
4031 # returns a submenu for the nagivation of the refs views (tags, heads,
4032 # remotes) with the current view disabled and the remotes view only
4033 # available if the feature is enabled
4034 sub format_ref_views {
4035 my ($current) = @_;
4036 my @ref_views = qw{tags heads};
4037 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4038 return join " | ", map {
4039 $_ eq $current ? $_ :
4040 $cgi->a({-href => href(action=>$_)}, $_)
4041 } @ref_views
4042 }
4043
4044 sub format_paging_nav {
4045 my ($action, $page, $has_next_link) = @_;
4046 my $paging_nav;
4047
4048
4049 if ($page > 0) {
4050 $paging_nav .=
4051 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4052 " &sdot; " .
4053 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4054 -accesskey => "p", -title => "Alt-p"}, "prev");
4055 } else {
4056 $paging_nav .= "first &sdot; prev";
4057 }
4058
4059 if ($has_next_link) {
4060 $paging_nav .= " &sdot; " .
4061 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4062 -accesskey => "n", -title => "Alt-n"}, "next");
4063 } else {
4064 $paging_nav .= " &sdot; next";
4065 }
4066
4067 return $paging_nav;
4068 }
4069
4070 ## ......................................................................
4071 ## functions printing or outputting HTML: div
4072
4073 sub git_print_header_div {
4074 my ($action, $title, $hash, $hash_base) = @_;
4075 my %args = ();
4076
4077 $args{'action'} = $action;
4078 $args{'hash'} = $hash if $hash;
4079 $args{'hash_base'} = $hash_base if $hash_base;
4080
4081 print "<div class=\"header\">\n" .
4082 $cgi->a({-href => href(%args), -class => "title"},
4083 $title ? $title : $action) .
4084 "\n</div>\n";
4085 }
4086
4087 sub format_repo_url {
4088 my ($name, $url) = @_;
4089 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4090 }
4091
4092 # Group output by placing it in a DIV element and adding a header.
4093 # Options for start_div() can be provided by passing a hash reference as the
4094 # first parameter to the function.
4095 # Options to git_print_header_div() can be provided by passing an array
4096 # reference. This must follow the options to start_div if they are present.
4097 # The content can be a scalar, which is output as-is, a scalar reference, which
4098 # is output after html escaping, an IO handle passed either as *handle or
4099 # *handle{IO}, or a function reference. In the latter case all following
4100 # parameters will be taken as argument to the content function call.
4101 sub git_print_section {
4102 my ($div_args, $header_args, $content);
4103 my $arg = shift;
4104 if (ref($arg) eq 'HASH') {
4105 $div_args = $arg;
4106 $arg = shift;
4107 }
4108 if (ref($arg) eq 'ARRAY') {
4109 $header_args = $arg;
4110 $arg = shift;
4111 }
4112 $content = $arg;
4113
4114 print $cgi->start_div($div_args);
4115 git_print_header_div(@$header_args);
4116
4117 if (ref($content) eq 'CODE') {
4118 $content->(@_);
4119 } elsif (ref($content) eq 'SCALAR') {
4120 print esc_html($$content);
4121 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4122 print <$content>;
4123 } elsif (!ref($content) && defined($content)) {
4124 print $content;
4125 }
4126
4127 print $cgi->end_div;
4128 }
4129
4130 sub format_timestamp_html {
4131 my $date = shift;
4132 my $strtime = $date->{'rfc2822'};
4133
4134 my (undef, undef, $datetime_class) =
4135 gitweb_get_feature('javascript-timezone');
4136 if ($datetime_class) {
4137 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4138 }
4139
4140 my $localtime_format = '(%02d:%02d %s)';
4141 if ($date->{'hour_local'} < 6) {
4142 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4143 }
4144 $strtime .= ' ' .
4145 sprintf($localtime_format,
4146 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4147
4148 return $strtime;
4149 }
4150
4151 # Outputs the author name and date in long form
4152 sub git_print_authorship {
4153 my $co = shift;
4154 my %opts = @_;
4155 my $tag = $opts{-tag} || 'div';
4156 my $author = $co->{'author_name'};
4157
4158 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4159 print "<$tag class=\"author_date\">" .
4160 format_search_author($author, "author", esc_html($author)) .
4161 " [".format_timestamp_html(\%ad)."]".
4162 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4163 "</$tag>\n";
4164 }
4165
4166 # Outputs table rows containing the full author or committer information,
4167 # in the format expected for 'commit' view (& similar).
4168 # Parameters are a commit hash reference, followed by the list of people
4169 # to output information for. If the list is empty it defaults to both
4170 # author and committer.
4171 sub git_print_authorship_rows {
4172 my $co = shift;
4173 # too bad we can't use @people = @_ || ('author', 'committer')
4174 my @people = @_;
4175 @people = ('author', 'committer') unless @people;
4176 foreach my $who (@people) {
4177 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4178 print "<tr><td>$who</td><td>" .
4179 format_search_author($co->{"${who}_name"}, $who,
4180 esc_html($co->{"${who}_name"})) . " " .
4181 format_search_author($co->{"${who}_email"}, $who,
4182 esc_html("<" . $co->{"${who}_email"} . ">")) .
4183 "</td><td rowspan=\"2\">" .
4184 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4185 "</td></tr>\n" .
4186 "<tr>" .
4187 "<td></td><td>" .
4188 format_timestamp_html(\%wd) .
4189 "</td>" .
4190 "</tr>\n";
4191 }
4192 }
4193
4194 sub git_print_page_path {
4195 my $name = shift;
4196 my $type = shift;
4197 my $hb = shift;
4198
4199
4200 print "<div class=\"page_path\">";
4201 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4202 -title => 'tree root'}, to_utf8("[$project]"));
4203 print " / ";
4204 if (defined $name) {
4205 my @dirname = split '/', $name;
4206 my $basename = pop @dirname;
4207 my $fullname = '';
4208
4209 foreach my $dir (@dirname) {
4210 $fullname .= ($fullname ? '/' : '') . $dir;
4211 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4212 hash_base=>$hb),
4213 -title => $fullname}, esc_path($dir));
4214 print " / ";
4215 }
4216 if (defined $type && $type eq 'blob') {
4217 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4218 hash_base=>$hb),
4219 -title => $name}, esc_path($basename));
4220 } elsif (defined $type && $type eq 'tree') {
4221 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4222 hash_base=>$hb),
4223 -title => $name}, esc_path($basename));
4224 print " / ";
4225 } else {
4226 print esc_path($basename);
4227 }
4228 }
4229 print "<br/></div>\n";
4230 }
4231
4232 sub git_print_log {
4233 my $log = shift;
4234 my %opts = @_;
4235
4236 if ($opts{'-remove_title'}) {
4237 # remove title, i.e. first line of log
4238 shift @$log;
4239 }
4240 # remove leading empty lines
4241 while (defined $log->[0] && $log->[0] eq "") {
4242 shift @$log;
4243 }
4244
4245 # print log
4246 my $signoff = 0;
4247 my $empty = 0;
4248 foreach my $line (@$log) {
4249 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4250 $signoff = 1;
4251 $empty = 0;
4252 if (! $opts{'-remove_signoff'}) {
4253 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4254 next;
4255 } else {
4256 # remove signoff lines
4257 next;
4258 }
4259 } else {
4260 $signoff = 0;
4261 }
4262
4263 # print only one empty line
4264 # do not print empty line after signoff
4265 if ($line eq "") {
4266 next if ($empty || $signoff);
4267 $empty = 1;
4268 } else {
4269 $empty = 0;
4270 }
4271
4272 print format_log_line_html($line) . "<br/>\n";
4273 }
4274
4275 if ($opts{'-final_empty_line'}) {
4276 # end with single empty line
4277 print "<br/>\n" unless $empty;
4278 }
4279 }
4280
4281 # return link target (what link points to)
4282 sub git_get_link_target {
4283 my $hash = shift;
4284 my $link_target;
4285
4286 # read link
4287 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4288 or return;
4289 {
4290 local $/ = undef;
4291 $link_target = <$fd>;
4292 }
4293 close $fd
4294 or return;
4295
4296 return $link_target;
4297 }
4298
4299 # given link target, and the directory (basedir) the link is in,
4300 # return target of link relative to top directory (top tree);
4301 # return undef if it is not possible (including absolute links).
4302 sub normalize_link_target {
4303 my ($link_target, $basedir) = @_;
4304
4305 # absolute symlinks (beginning with '/') cannot be normalized
4306 return if (substr($link_target, 0, 1) eq '/');
4307
4308 # normalize link target to path from top (root) tree (dir)
4309 my $path;
4310 if ($basedir) {
4311 $path = $basedir . '/' . $link_target;
4312 } else {
4313 # we are in top (root) tree (dir)
4314 $path = $link_target;
4315 }
4316
4317 # remove //, /./, and /../
4318 my @path_parts;
4319 foreach my $part (split('/', $path)) {
4320 # discard '.' and ''
4321 next if (!$part || $part eq '.');
4322 # handle '..'
4323 if ($part eq '..') {
4324 if (@path_parts) {
4325 pop @path_parts;
4326 } else {
4327 # link leads outside repository (outside top dir)
4328 return;
4329 }
4330 } else {
4331 push @path_parts, $part;
4332 }
4333 }
4334 $path = join('/', @path_parts);
4335
4336 return $path;
4337 }
4338
4339 # print tree entry (row of git_tree), but without encompassing <tr> element
4340 sub git_print_tree_entry {
4341 my ($t, $basedir, $hash_base, $have_blame) = @_;
4342
4343 my %base_key = ();
4344 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4345
4346 # The format of a table row is: mode list link. Where mode is
4347 # the mode of the entry, list is the name of the entry, an href,
4348 # and link is the action links of the entry.
4349
4350 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4351 if (exists $t->{'size'}) {
4352 print "<td class=\"size\">$t->{'size'}</td>\n";
4353 }
4354 if ($t->{'type'} eq "blob") {
4355 print "<td class=\"list\">" .
4356 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4357 file_name=>"$basedir$t->{'name'}", %base_key),
4358 -class => "list"}, esc_path($t->{'name'}));
4359 if (S_ISLNK(oct $t->{'mode'})) {
4360 my $link_target = git_get_link_target($t->{'hash'});
4361 if ($link_target) {
4362 my $norm_target = normalize_link_target($link_target, $basedir);
4363 if (defined $norm_target) {
4364 print " -> " .
4365 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4366 file_name=>$norm_target),
4367 -title => $norm_target}, esc_path($link_target));
4368 } else {
4369 print " -> " . esc_path($link_target);
4370 }
4371 }
4372 }
4373 print "</td>\n";
4374 print "<td class=\"link\">";
4375 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4376 file_name=>"$basedir$t->{'name'}", %base_key)},
4377 "blob");
4378 if ($have_blame) {
4379 print " | " .
4380 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4381 file_name=>"$basedir$t->{'name'}", %base_key)},
4382 "blame");
4383 }
4384 if (defined $hash_base) {
4385 print " | " .
4386 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4387 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4388 "history");
4389 }
4390 print " | " .
4391 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4392 file_name=>"$basedir$t->{'name'}")},
4393 "raw");
4394 print "</td>\n";
4395
4396 } elsif ($t->{'type'} eq "tree") {
4397 print "<td class=\"list\">";
4398 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4399 file_name=>"$basedir$t->{'name'}",
4400 %base_key)},
4401 esc_path($t->{'name'}));
4402 print "</td>\n";
4403 print "<td class=\"link\">";
4404 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4405 file_name=>"$basedir$t->{'name'}",
4406 %base_key)},
4407 "tree");
4408 if (defined $hash_base) {
4409 print " | " .
4410 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4411 file_name=>"$basedir$t->{'name'}")},
4412 "history");
4413 }
4414 print "</td>\n";
4415 } else {
4416 # unknown object: we can only present history for it
4417 # (this includes 'commit' object, i.e. submodule support)
4418 print "<td class=\"list\">" .
4419 esc_path($t->{'name'}) .
4420 "</td>\n";
4421 print "<td class=\"link\">";
4422 if (defined $hash_base) {
4423 print $cgi->a({-href => href(action=>"history",
4424 hash_base=>$hash_base,
4425 file_name=>"$basedir$t->{'name'}")},
4426 "history");
4427 }
4428 print "</td>\n";
4429 }
4430 }
4431
4432 ## ......................................................................
4433 ## functions printing large fragments of HTML
4434
4435 # get pre-image filenames for merge (combined) diff
4436 sub fill_from_file_info {
4437 my ($diff, @parents) = @_;
4438
4439 $diff->{'from_file'} = [ ];
4440 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4441 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4442 if ($diff->{'status'}[$i] eq 'R' ||
4443 $diff->{'status'}[$i] eq 'C') {
4444 $diff->{'from_file'}[$i] =
4445 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4446 }
4447 }
4448
4449 return $diff;
4450 }
4451
4452 # is current raw difftree line of file deletion
4453 sub is_deleted {
4454 my $diffinfo = shift;
4455
4456 return $diffinfo->{'to_id'} eq ('0' x 40);
4457 }
4458
4459 # does patch correspond to [previous] difftree raw line
4460 # $diffinfo - hashref of parsed raw diff format
4461 # $patchinfo - hashref of parsed patch diff format
4462 # (the same keys as in $diffinfo)
4463 sub is_patch_split {
4464 my ($diffinfo, $patchinfo) = @_;
4465
4466 return defined $diffinfo && defined $patchinfo
4467 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4468 }
4469
4470
4471 sub git_difftree_body {
4472 my ($difftree, $hash, @parents) = @_;
4473 my ($parent) = $parents[0];
4474 my $have_blame = gitweb_check_feature('blame');
4475 print "<div class=\"list_head\">\n";
4476 if ($#{$difftree} > 10) {
4477 print(($#{$difftree} + 1) . " files changed:\n");
4478 }
4479 print "</div>\n";
4480
4481 print "<table class=\"" .
4482 (@parents > 1 ? "combined " : "") .
4483 "diff_tree\">\n";
4484
4485 # header only for combined diff in 'commitdiff' view
4486 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4487 if ($has_header) {
4488 # table header
4489 print "<thead><tr>\n" .
4490 "<th></th><th></th>\n"; # filename, patchN link
4491 for (my $i = 0; $i < @parents; $i++) {
4492 my $par = $parents[$i];
4493 print "<th>" .
4494 $cgi->a({-href => href(action=>"commitdiff",
4495 hash=>$hash, hash_parent=>$par),
4496 -title => 'commitdiff to parent number ' .
4497 ($i+1) . ': ' . substr($par,0,7)},
4498 $i+1) .
4499 "&nbsp;</th>\n";
4500 }
4501 print "</tr></thead>\n<tbody>\n";
4502 }
4503
4504 my $alternate = 1;
4505 my $patchno = 0;
4506 foreach my $line (@{$difftree}) {
4507 my $diff = parsed_difftree_line($line);
4508
4509 if ($alternate) {
4510 print "<tr class=\"dark\">\n";
4511 } else {
4512 print "<tr class=\"light\">\n";
4513 }
4514 $alternate ^= 1;
4515
4516 if (exists $diff->{'nparents'}) { # combined diff
4517
4518 fill_from_file_info($diff, @parents)
4519 unless exists $diff->{'from_file'};
4520
4521 if (!is_deleted($diff)) {
4522 # file exists in the result (child) commit
4523 print "<td>" .
4524 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4525 file_name=>$diff->{'to_file'},
4526 hash_base=>$hash),
4527 -class => "list"}, esc_path($diff->{'to_file'})) .
4528 "</td>\n";
4529 } else {
4530 print "<td>" .
4531 esc_path($diff->{'to_file'}) .
4532 "</td>\n";
4533 }
4534
4535 if ($action eq 'commitdiff') {
4536 # link to patch
4537 $patchno++;
4538 print "<td class=\"link\">" .
4539 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4540 "patch") .
4541 " | " .
4542 "</td>\n";
4543 }
4544
4545 my $has_history = 0;
4546 my $not_deleted = 0;
4547 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4548 my $hash_parent = $parents[$i];
4549 my $from_hash = $diff->{'from_id'}[$i];
4550 my $from_path = $diff->{'from_file'}[$i];
4551 my $status = $diff->{'status'}[$i];
4552
4553 $has_history ||= ($status ne 'A');
4554 $not_deleted ||= ($status ne 'D');
4555
4556 if ($status eq 'A') {
4557 print "<td class=\"link\" align=\"right\"> | </td>\n";
4558 } elsif ($status eq 'D') {
4559 print "<td class=\"link\">" .
4560 $cgi->a({-href => href(action=>"blob",
4561 hash_base=>$hash,
4562 hash=>$from_hash,
4563 file_name=>$from_path)},
4564 "blob" . ($i+1)) .
4565 " | </td>\n";
4566 } else {
4567 if ($diff->{'to_id'} eq $from_hash) {
4568 print "<td class=\"link nochange\">";
4569 } else {
4570 print "<td class=\"link\">";
4571 }
4572 print $cgi->a({-href => href(action=>"blobdiff",
4573 hash=>$diff->{'to_id'},
4574 hash_parent=>$from_hash,
4575 hash_base=>$hash,
4576 hash_parent_base=>$hash_parent,
4577 file_name=>$diff->{'to_file'},
4578 file_parent=>$from_path)},
4579 "diff" . ($i+1)) .
4580 " | </td>\n";
4581 }
4582 }
4583
4584 print "<td class=\"link\">";
4585 if ($not_deleted) {
4586 print $cgi->a({-href => href(action=>"blob",
4587 hash=>$diff->{'to_id'},
4588 file_name=>$diff->{'to_file'},
4589 hash_base=>$hash)},
4590 "blob");
4591 print " | " if ($has_history);
4592 }
4593 if ($has_history) {
4594 print $cgi->a({-href => href(action=>"history",
4595 file_name=>$diff->{'to_file'},
4596 hash_base=>$hash)},
4597 "history");
4598 }
4599 print "</td>\n";
4600
4601 print "</tr>\n";
4602 next; # instead of 'else' clause, to avoid extra indent
4603 }
4604 # else ordinary diff
4605
4606 my ($to_mode_oct, $to_mode_str, $to_file_type);
4607 my ($from_mode_oct, $from_mode_str, $from_file_type);
4608 if ($diff->{'to_mode'} ne ('0' x 6)) {
4609 $to_mode_oct = oct $diff->{'to_mode'};
4610 if (S_ISREG($to_mode_oct)) { # only for regular file
4611 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4612 }
4613 $to_file_type = file_type($diff->{'to_mode'});
4614 }
4615 if ($diff->{'from_mode'} ne ('0' x 6)) {
4616 $from_mode_oct = oct $diff->{'from_mode'};
4617 if (S_ISREG($from_mode_oct)) { # only for regular file
4618 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4619 }
4620 $from_file_type = file_type($diff->{'from_mode'});
4621 }
4622
4623 if ($diff->{'status'} eq "A") { # created
4624 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4625 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4626 $mode_chng .= "]</span>";
4627 print "<td>";
4628 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4629 hash_base=>$hash, file_name=>$diff->{'file'}),
4630 -class => "list"}, esc_path($diff->{'file'}));
4631 print "</td>\n";
4632 print "<td>$mode_chng</td>\n";
4633 print "<td class=\"link\">";
4634 if ($action eq 'commitdiff') {
4635 # link to patch
4636 $patchno++;
4637 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4638 "patch") .
4639 " | ";
4640 }
4641 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4642 hash_base=>$hash, file_name=>$diff->{'file'})},
4643 "blob");
4644 print "</td>\n";
4645
4646 } elsif ($diff->{'status'} eq "D") { # deleted
4647 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4648 print "<td>";
4649 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4650 hash_base=>$parent, file_name=>$diff->{'file'}),
4651 -class => "list"}, esc_path($diff->{'file'}));
4652 print "</td>\n";
4653 print "<td>$mode_chng</td>\n";
4654 print "<td class=\"link\">";
4655 if ($action eq 'commitdiff') {
4656 # link to patch
4657 $patchno++;
4658 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4659 "patch") .
4660 " | ";
4661 }
4662 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4663 hash_base=>$parent, file_name=>$diff->{'file'})},
4664 "blob") . " | ";
4665 if ($have_blame) {
4666 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4667 file_name=>$diff->{'file'})},
4668 "blame") . " | ";
4669 }
4670 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4671 file_name=>$diff->{'file'})},
4672 "history");
4673 print "</td>\n";
4674
4675 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4676 my $mode_chnge = "";
4677 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4678 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4679 if ($from_file_type ne $to_file_type) {
4680 $mode_chnge .= " from $from_file_type to $to_file_type";
4681 }
4682 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4683 if ($from_mode_str && $to_mode_str) {
4684 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4685 } elsif ($to_mode_str) {
4686 $mode_chnge .= " mode: $to_mode_str";
4687 }
4688 }
4689 $mode_chnge .= "]</span>\n";
4690 }
4691 print "<td>";
4692 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4693 hash_base=>$hash, file_name=>$diff->{'file'}),
4694 -class => "list"}, esc_path($diff->{'file'}));
4695 print "</td>\n";
4696 print "<td>$mode_chnge</td>\n";
4697 print "<td class=\"link\">";
4698 if ($action eq 'commitdiff') {
4699 # link to patch
4700 $patchno++;
4701 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4702 "patch") .
4703 " | ";
4704 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4705 # "commit" view and modified file (not onlu mode changed)
4706 print $cgi->a({-href => href(action=>"blobdiff",
4707 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4708 hash_base=>$hash, hash_parent_base=>$parent,
4709 file_name=>$diff->{'file'})},
4710 "diff") .
4711 " | ";
4712 }
4713 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4714 hash_base=>$hash, file_name=>$diff->{'file'})},
4715 "blob") . " | ";
4716 if ($have_blame) {
4717 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4718 file_name=>$diff->{'file'})},
4719 "blame") . " | ";
4720 }
4721 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4722 file_name=>$diff->{'file'})},
4723 "history");
4724 print "</td>\n";
4725
4726 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4727 my %status_name = ('R' => 'moved', 'C' => 'copied');
4728 my $nstatus = $status_name{$diff->{'status'}};
4729 my $mode_chng = "";
4730 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4731 # mode also for directories, so we cannot use $to_mode_str
4732 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4733 }
4734 print "<td>" .
4735 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4736 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4737 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4738 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4739 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4740 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4741 -class => "list"}, esc_path($diff->{'from_file'})) .
4742 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4743 "<td class=\"link\">";
4744 if ($action eq 'commitdiff') {
4745 # link to patch
4746 $patchno++;
4747 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4748 "patch") .
4749 " | ";
4750 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4751 # "commit" view and modified file (not only pure rename or copy)
4752 print $cgi->a({-href => href(action=>"blobdiff",
4753 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4754 hash_base=>$hash, hash_parent_base=>$parent,
4755 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4756 "diff") .
4757 " | ";
4758 }
4759 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4760 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4761 "blob") . " | ";
4762 if ($have_blame) {
4763 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4764 file_name=>$diff->{'to_file'})},
4765 "blame") . " | ";
4766 }
4767 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4768 file_name=>$diff->{'to_file'})},
4769 "history");
4770 print "</td>\n";
4771
4772 } # we should not encounter Unmerged (U) or Unknown (X) status
4773 print "</tr>\n";
4774 }
4775 print "</tbody>" if $has_header;
4776 print "</table>\n";
4777 }
4778
4779 sub git_patchset_body {
4780 my ($fd, $difftree, $hash, @hash_parents) = @_;
4781 my ($hash_parent) = $hash_parents[0];
4782
4783 my $is_combined = (@hash_parents > 1);
4784 my $patch_idx = 0;
4785 my $patch_number = 0;
4786 my $patch_line;
4787 my $diffinfo;
4788 my $to_name;
4789 my (%from, %to);
4790
4791 print "<div class=\"patchset\">\n";
4792
4793 # skip to first patch
4794 while ($patch_line = <$fd>) {
4795 chomp $patch_line;
4796
4797 last if ($patch_line =~ m/^diff /);
4798 }
4799
4800 PATCH:
4801 while ($patch_line) {
4802
4803 # parse "git diff" header line
4804 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4805 # $1 is from_name, which we do not use
4806 $to_name = unquote($2);
4807 $to_name =~ s!^b/!!;
4808 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4809 # $1 is 'cc' or 'combined', which we do not use
4810 $to_name = unquote($2);
4811 } else {
4812 $to_name = undef;
4813 }
4814
4815 # check if current patch belong to current raw line
4816 # and parse raw git-diff line if needed
4817 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4818 # this is continuation of a split patch
4819 print "<div class=\"patch cont\">\n";
4820 } else {
4821 # advance raw git-diff output if needed
4822 $patch_idx++ if defined $diffinfo;
4823
4824 # read and prepare patch information
4825 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4826
4827 # compact combined diff output can have some patches skipped
4828 # find which patch (using pathname of result) we are at now;
4829 if ($is_combined) {
4830 while ($to_name ne $diffinfo->{'to_file'}) {
4831 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4832 format_diff_cc_simplified($diffinfo, @hash_parents) .
4833 "</div>\n"; # class="patch"
4834
4835 $patch_idx++;
4836 $patch_number++;
4837
4838 last if $patch_idx > $#$difftree;
4839 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4840 }
4841 }
4842
4843 # modifies %from, %to hashes
4844 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4845
4846 # this is first patch for raw difftree line with $patch_idx index
4847 # we index @$difftree array from 0, but number patches from 1
4848 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4849 }
4850
4851 # git diff header
4852 #assert($patch_line =~ m/^diff /) if DEBUG;
4853 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4854 $patch_number++;
4855 # print "git diff" header
4856 print format_git_diff_header_line($patch_line, $diffinfo,
4857 \%from, \%to);
4858
4859 # print extended diff header
4860 print "<div class=\"diff extended_header\">\n";
4861 EXTENDED_HEADER:
4862 while ($patch_line = <$fd>) {
4863 chomp $patch_line;
4864
4865 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4866
4867 print format_extended_diff_header_line($patch_line, $diffinfo,
4868 \%from, \%to);
4869 }
4870 print "</div>\n"; # class="diff extended_header"
4871
4872 # from-file/to-file diff header
4873 if (! $patch_line) {
4874 print "</div>\n"; # class="patch"
4875 last PATCH;
4876 }
4877 next PATCH if ($patch_line =~ m/^diff /);
4878 #assert($patch_line =~ m/^---/) if DEBUG;
4879
4880 my $last_patch_line = $patch_line;
4881 $patch_line = <$fd>;
4882 chomp $patch_line;
4883 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4884
4885 print format_diff_from_to_header($last_patch_line, $patch_line,
4886 $diffinfo, \%from, \%to,
4887 @hash_parents);
4888
4889 # the patch itself
4890 LINE:
4891 while ($patch_line = <$fd>) {
4892 chomp $patch_line;
4893
4894 next PATCH if ($patch_line =~ m/^diff /);
4895
4896 print format_diff_line($patch_line, \%from, \%to);
4897 }
4898
4899 } continue {
4900 print "</div>\n"; # class="patch"
4901 }
4902
4903 # for compact combined (--cc) format, with chunk and patch simplification
4904 # the patchset might be empty, but there might be unprocessed raw lines
4905 for (++$patch_idx if $patch_number > 0;
4906 $patch_idx < @$difftree;
4907 ++$patch_idx) {
4908 # read and prepare patch information
4909 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4910
4911 # generate anchor for "patch" links in difftree / whatchanged part
4912 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4913 format_diff_cc_simplified($diffinfo, @hash_parents) .
4914 "</div>\n"; # class="patch"
4915
4916 $patch_number++;
4917 }
4918
4919 if ($patch_number == 0) {
4920 if (@hash_parents > 1) {
4921 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4922 } else {
4923 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4924 }
4925 }
4926
4927 print "</div>\n"; # class="patchset"
4928 }
4929
4930 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4931
4932 # fills project list info (age, description, owner, category, forks)
4933 # for each project in the list, removing invalid projects from
4934 # returned list
4935 # NOTE: modifies $projlist, but does not remove entries from it
4936 sub fill_project_list_info {
4937 my $projlist = shift;
4938 my @projects;
4939
4940 my $show_ctags = gitweb_check_feature('ctags');
4941 PROJECT:
4942 foreach my $pr (@$projlist) {
4943 my (@activity) = git_get_last_activity($pr->{'path'});
4944 unless (@activity) {
4945 next PROJECT;
4946 }
4947 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4948 if (!defined $pr->{'descr'}) {
4949 my $descr = git_get_project_description($pr->{'path'}) || "";
4950 $descr = to_utf8($descr);
4951 $pr->{'descr_long'} = $descr;
4952 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4953 }
4954 if (!defined $pr->{'owner'}) {
4955 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4956 }
4957 if ($show_ctags) {
4958 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4959 }
4960 if ($projects_list_group_categories && !defined $pr->{'category'}) {
4961 my $cat = git_get_project_category($pr->{'path'}) ||
4962 $project_list_default_category;
4963 $pr->{'category'} = to_utf8($cat);
4964 }
4965
4966 push @projects, $pr;
4967 }
4968
4969 return @projects;
4970 }
4971
4972 sub sort_projects_list {
4973 my ($projlist, $order) = @_;
4974 my @projects;
4975
4976 my %order_info = (
4977 project => { key => 'path', type => 'str' },
4978 descr => { key => 'descr_long', type => 'str' },
4979 owner => { key => 'owner', type => 'str' },
4980 age => { key => 'age', type => 'num' }
4981 );
4982 my $oi = $order_info{$order};
4983 return @$projlist unless defined $oi;
4984 if ($oi->{'type'} eq 'str') {
4985 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @$projlist;
4986 } else {
4987 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @$projlist;
4988 }
4989
4990 return @projects;
4991 }
4992
4993 # returns a hash of categories, containing the list of project
4994 # belonging to each category
4995 sub build_projlist_by_category {
4996 my ($projlist, $from, $to) = @_;
4997 my %categories;
4998
4999 $from = 0 unless defined $from;
5000 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5001
5002 for (my $i = $from; $i <= $to; $i++) {
5003 my $pr = $projlist->[$i];
5004 push @{$categories{ $pr->{'category'} }}, $pr;
5005 }
5006
5007 return wantarray ? %categories : \%categories;
5008 }
5009
5010 # print 'sort by' <th> element, generating 'sort by $name' replay link
5011 # if that order is not selected
5012 sub print_sort_th {
5013 print format_sort_th(@_);
5014 }
5015
5016 sub format_sort_th {
5017 my ($name, $order, $header) = @_;
5018 my $sort_th = "";
5019 $header ||= ucfirst($name);
5020
5021 if ($order eq $name) {
5022 $sort_th .= "<th>$header</th>\n";
5023 } else {
5024 $sort_th .= "<th>" .
5025 $cgi->a({-href => href(-replay=>1, order=>$name),
5026 -class => "header"}, $header) .
5027 "</th>\n";
5028 }
5029
5030 return $sort_th;
5031 }
5032
5033 sub git_project_list_rows {
5034 my ($projlist, $from, $to, $check_forks) = @_;
5035
5036 $from = 0 unless defined $from;
5037 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5038
5039 my $alternate = 1;
5040 for (my $i = $from; $i <= $to; $i++) {
5041 my $pr = $projlist->[$i];
5042
5043 if ($alternate) {
5044 print "<tr class=\"dark\">\n";
5045 } else {
5046 print "<tr class=\"light\">\n";
5047 }
5048 $alternate ^= 1;
5049
5050 if ($check_forks) {
5051 print "<td>";
5052 if ($pr->{'forks'}) {
5053 my $nforks = scalar @{$pr->{'forks'}};
5054 if ($nforks > 0) {
5055 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5056 -title => "$nforks forks"}, "+");
5057 } else {
5058 print $cgi->span({-title => "$nforks forks"}, "+");
5059 }
5060 }
5061 print "</td>\n";
5062 }
5063 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5064 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
5065 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5066 -class => "list", -title => $pr->{'descr_long'}},
5067 esc_html($pr->{'descr'})) . "</td>\n" .
5068 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5069 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5070 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
5071 "<td class=\"link\">" .
5072 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5073 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5074 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5075 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5076 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5077 "</td>\n" .
5078 "</tr>\n";
5079 }
5080 }
5081
5082 sub git_project_list_body {
5083 # actually uses global variable $project
5084 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5085 my @projects = @$projlist;
5086
5087 my $check_forks = gitweb_check_feature('forks');
5088 my $show_ctags = gitweb_check_feature('ctags');
5089 my $tagfilter = $show_ctags ? $cgi->param('by_tag') : undef;
5090 $check_forks = undef
5091 if ($tagfilter || $searchtext);
5092
5093 # filtering out forks before filling info allows to do less work
5094 @projects = filter_forks_from_projects_list(\@projects)
5095 if ($check_forks);
5096 @projects = fill_project_list_info(\@projects);
5097 # searching projects require filling to be run before it
5098 @projects = search_projects_list(\@projects,
5099 'searchtext' => $searchtext,
5100 'tagfilter' => $tagfilter)
5101 if ($tagfilter || $searchtext);
5102
5103 $order ||= $default_projects_order;
5104 $from = 0 unless defined $from;
5105 $to = $#projects if (!defined $to || $#projects < $to);
5106
5107 # short circuit
5108 if ($from > $to) {
5109 print "<center>\n".
5110 "<b>No such projects found</b><br />\n".
5111 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5112 "</center>\n<br />\n";
5113 return;
5114 }
5115
5116 @projects = sort_projects_list(\@projects, $order);
5117
5118 if ($show_ctags) {
5119 my $ctags = git_gather_all_ctags(\@projects);
5120 my $cloud = git_populate_project_tagcloud($ctags);
5121 print git_show_project_tagcloud($cloud, 64);
5122 }
5123
5124 print "<table class=\"project_list\">\n";
5125 unless ($no_header) {
5126 print "<tr>\n";
5127 if ($check_forks) {
5128 print "<th></th>\n";
5129 }
5130 print_sort_th('project', $order, 'Project');
5131 print_sort_th('descr', $order, 'Description');
5132 print_sort_th('owner', $order, 'Owner');
5133 print_sort_th('age', $order, 'Last Change');
5134 print "<th></th>\n" . # for links
5135 "</tr>\n";
5136 }
5137
5138 if ($projects_list_group_categories) {
5139 # only display categories with projects in the $from-$to window
5140 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5141 my %categories = build_projlist_by_category(\@projects, $from, $to);
5142 foreach my $cat (sort keys %categories) {
5143 unless ($cat eq "") {
5144 print "<tr>\n";
5145 if ($check_forks) {
5146 print "<td></td>\n";
5147 }
5148 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5149 print "</tr>\n";
5150 }
5151
5152 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5153 }
5154 } else {
5155 git_project_list_rows(\@projects, $from, $to, $check_forks);
5156 }
5157
5158 if (defined $extra) {
5159 print "<tr>\n";
5160 if ($check_forks) {
5161 print "<td></td>\n";
5162 }
5163 print "<td colspan=\"5\">$extra</td>\n" .
5164 "</tr>\n";
5165 }
5166 print "</table>\n";
5167 }
5168
5169 sub git_log_body {
5170 # uses global variable $project
5171 my ($commitlist, $from, $to, $refs, $extra) = @_;
5172
5173 $from = 0 unless defined $from;
5174 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5175
5176 for (my $i = 0; $i <= $to; $i++) {
5177 my %co = %{$commitlist->[$i]};
5178 next if !%co;
5179 my $commit = $co{'id'};
5180 my $ref = format_ref_marker($refs, $commit);
5181 git_print_header_div('commit',
5182 "<span class=\"age\">$co{'age_string'}</span>" .
5183 esc_html($co{'title'}) . $ref,
5184 $commit);
5185 print "<div class=\"title_text\">\n" .
5186 "<div class=\"log_link\">\n" .
5187 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5188 " | " .
5189 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5190 " | " .
5191 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5192 "<br/>\n" .
5193 "</div>\n";
5194 git_print_authorship(\%co, -tag => 'span');
5195 print "<br/>\n</div>\n";
5196
5197 print "<div class=\"log_body\">\n";
5198 git_print_log($co{'comment'}, -final_empty_line=> 1);
5199 print "</div>\n";
5200 }
5201 if ($extra) {
5202 print "<div class=\"page_nav\">\n";
5203 print "$extra\n";
5204 print "</div>\n";
5205 }
5206 }
5207
5208 sub git_shortlog_body {
5209 # uses global variable $project
5210 my ($commitlist, $from, $to, $refs, $extra) = @_;
5211
5212 $from = 0 unless defined $from;
5213 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5214
5215 print "<table class=\"shortlog\">\n";
5216 my $alternate = 1;
5217 for (my $i = $from; $i <= $to; $i++) {
5218 my %co = %{$commitlist->[$i]};
5219 my $commit = $co{'id'};
5220 my $ref = format_ref_marker($refs, $commit);
5221 if ($alternate) {
5222 print "<tr class=\"dark\">\n";
5223 } else {
5224 print "<tr class=\"light\">\n";
5225 }
5226 $alternate ^= 1;
5227 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5228 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5229 format_author_html('td', \%co, 10) . "<td>";
5230 print format_subject_html($co{'title'}, $co{'title_short'},
5231 href(action=>"commit", hash=>$commit), $ref);
5232 print "</td>\n" .
5233 "<td class=\"link\">" .
5234 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5235 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5236 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5237 my $snapshot_links = format_snapshot_links($commit);
5238 if (defined $snapshot_links) {
5239 print " | " . $snapshot_links;
5240 }
5241 print "</td>\n" .
5242 "</tr>\n";
5243 }
5244 if (defined $extra) {
5245 print "<tr>\n" .
5246 "<td colspan=\"4\">$extra</td>\n" .
5247 "</tr>\n";
5248 }
5249 print "</table>\n";
5250 }
5251
5252 sub git_history_body {
5253 # Warning: assumes constant type (blob or tree) during history
5254 my ($commitlist, $from, $to, $refs, $extra,
5255 $file_name, $file_hash, $ftype) = @_;
5256
5257 $from = 0 unless defined $from;
5258 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5259
5260 print "<table class=\"history\">\n";
5261 my $alternate = 1;
5262 for (my $i = $from; $i <= $to; $i++) {
5263 my %co = %{$commitlist->[$i]};
5264 if (!%co) {
5265 next;
5266 }
5267 my $commit = $co{'id'};
5268
5269 my $ref = format_ref_marker($refs, $commit);
5270
5271 if ($alternate) {
5272 print "<tr class=\"dark\">\n";
5273 } else {
5274 print "<tr class=\"light\">\n";
5275 }
5276 $alternate ^= 1;
5277 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5278 # shortlog: format_author_html('td', \%co, 10)
5279 format_author_html('td', \%co, 15, 3) . "<td>";
5280 # originally git_history used chop_str($co{'title'}, 50)
5281 print format_subject_html($co{'title'}, $co{'title_short'},
5282 href(action=>"commit", hash=>$commit), $ref);
5283 print "</td>\n" .
5284 "<td class=\"link\">" .
5285 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5286 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5287
5288 if ($ftype eq 'blob') {
5289 my $blob_current = $file_hash;
5290 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5291 if (defined $blob_current && defined $blob_parent &&
5292 $blob_current ne $blob_parent) {
5293 print " | " .
5294 $cgi->a({-href => href(action=>"blobdiff",
5295 hash=>$blob_current, hash_parent=>$blob_parent,
5296 hash_base=>$hash_base, hash_parent_base=>$commit,
5297 file_name=>$file_name)},
5298 "diff to current");
5299 }
5300 }
5301 print "</td>\n" .
5302 "</tr>\n";
5303 }
5304 if (defined $extra) {
5305 print "<tr>\n" .
5306 "<td colspan=\"4\">$extra</td>\n" .
5307 "</tr>\n";
5308 }
5309 print "</table>\n";
5310 }
5311
5312 sub git_tags_body {
5313 # uses global variable $project
5314 my ($taglist, $from, $to, $extra) = @_;
5315 $from = 0 unless defined $from;
5316 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5317
5318 print "<table class=\"tags\">\n";
5319 my $alternate = 1;
5320 for (my $i = $from; $i <= $to; $i++) {
5321 my $entry = $taglist->[$i];
5322 my %tag = %$entry;
5323 my $comment = $tag{'subject'};
5324 my $comment_short;
5325 if (defined $comment) {
5326 $comment_short = chop_str($comment, 30, 5);
5327 }
5328 if ($alternate) {
5329 print "<tr class=\"dark\">\n";
5330 } else {
5331 print "<tr class=\"light\">\n";
5332 }
5333 $alternate ^= 1;
5334 if (defined $tag{'age'}) {
5335 print "<td><i>$tag{'age'}</i></td>\n";
5336 } else {
5337 print "<td></td>\n";
5338 }
5339 print "<td>" .
5340 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5341 -class => "list name"}, esc_html($tag{'name'})) .
5342 "</td>\n" .
5343 "<td>";
5344 if (defined $comment) {
5345 print format_subject_html($comment, $comment_short,
5346 href(action=>"tag", hash=>$tag{'id'}));
5347 }
5348 print "</td>\n" .
5349 "<td class=\"selflink\">";
5350 if ($tag{'type'} eq "tag") {
5351 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5352 } else {
5353 print "&nbsp;";
5354 }
5355 print "</td>\n" .
5356 "<td class=\"link\">" . " | " .
5357 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5358 if ($tag{'reftype'} eq "commit") {
5359 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5360 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5361 } elsif ($tag{'reftype'} eq "blob") {
5362 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5363 }
5364 print "</td>\n" .
5365 "</tr>";
5366 }
5367 if (defined $extra) {
5368 print "<tr>\n" .
5369 "<td colspan=\"5\">$extra</td>\n" .
5370 "</tr>\n";
5371 }
5372 print "</table>\n";
5373 }
5374
5375 sub git_heads_body {
5376 # uses global variable $project
5377 my ($headlist, $head, $from, $to, $extra) = @_;
5378 $from = 0 unless defined $from;
5379 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5380
5381 print "<table class=\"heads\">\n";
5382 my $alternate = 1;
5383 for (my $i = $from; $i <= $to; $i++) {
5384 my $entry = $headlist->[$i];
5385 my %ref = %$entry;
5386 my $curr = $ref{'id'} eq $head;
5387 if ($alternate) {
5388 print "<tr class=\"dark\">\n";
5389 } else {
5390 print "<tr class=\"light\">\n";
5391 }
5392 $alternate ^= 1;
5393 print "<td><i>$ref{'age'}</i></td>\n" .
5394 ($curr ? "<td class=\"current_head\">" : "<td>") .
5395 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5396 -class => "list name"},esc_html($ref{'name'})) .
5397 "</td>\n" .
5398 "<td class=\"link\">" .
5399 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5400 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5401 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
5402 "</td>\n" .
5403 "</tr>";
5404 }
5405 if (defined $extra) {
5406 print "<tr>\n" .
5407 "<td colspan=\"3\">$extra</td>\n" .
5408 "</tr>\n";
5409 }
5410 print "</table>\n";
5411 }
5412
5413 # Display a single remote block
5414 sub git_remote_block {
5415 my ($remote, $rdata, $limit, $head) = @_;
5416
5417 my $heads = $rdata->{'heads'};
5418 my $fetch = $rdata->{'fetch'};
5419 my $push = $rdata->{'push'};
5420
5421 my $urls_table = "<table class=\"projects_list\">\n" ;
5422
5423 if (defined $fetch) {
5424 if ($fetch eq $push) {
5425 $urls_table .= format_repo_url("URL", $fetch);
5426 } else {
5427 $urls_table .= format_repo_url("Fetch URL", $fetch);
5428 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
5429 }
5430 } elsif (defined $push) {
5431 $urls_table .= format_repo_url("Push URL", $push);
5432 } else {
5433 $urls_table .= format_repo_url("", "No remote URL");
5434 }
5435
5436 $urls_table .= "</table>\n";
5437
5438 my $dots;
5439 if (defined $limit && $limit < @$heads) {
5440 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
5441 }
5442
5443 print $urls_table;
5444 git_heads_body($heads, $head, 0, $limit, $dots);
5445 }
5446
5447 # Display a list of remote names with the respective fetch and push URLs
5448 sub git_remotes_list {
5449 my ($remotedata, $limit) = @_;
5450 print "<table class=\"heads\">\n";
5451 my $alternate = 1;
5452 my @remotes = sort keys %$remotedata;
5453
5454 my $limited = $limit && $limit < @remotes;
5455
5456 $#remotes = $limit - 1 if $limited;
5457
5458 while (my $remote = shift @remotes) {
5459 my $rdata = $remotedata->{$remote};
5460 my $fetch = $rdata->{'fetch'};
5461 my $push = $rdata->{'push'};
5462 if ($alternate) {
5463 print "<tr class=\"dark\">\n";
5464 } else {
5465 print "<tr class=\"light\">\n";
5466 }
5467 $alternate ^= 1;
5468 print "<td>" .
5469 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
5470 -class=> "list name"},esc_html($remote)) .
5471 "</td>";
5472 print "<td class=\"link\">" .
5473 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
5474 " | " .
5475 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
5476 "</td>";
5477
5478 print "</tr>\n";
5479 }
5480
5481 if ($limited) {
5482 print "<tr>\n" .
5483 "<td colspan=\"3\">" .
5484 $cgi->a({-href => href(action=>"remotes")}, "...") .
5485 "</td>\n" . "</tr>\n";
5486 }
5487
5488 print "</table>";
5489 }
5490
5491 # Display remote heads grouped by remote, unless there are too many
5492 # remotes, in which case we only display the remote names
5493 sub git_remotes_body {
5494 my ($remotedata, $limit, $head) = @_;
5495 if ($limit and $limit < keys %$remotedata) {
5496 git_remotes_list($remotedata, $limit);
5497 } else {
5498 fill_remote_heads($remotedata);
5499 while (my ($remote, $rdata) = each %$remotedata) {
5500 git_print_section({-class=>"remote", -id=>$remote},
5501 ["remotes", $remote, $remote], sub {
5502 git_remote_block($remote, $rdata, $limit, $head);
5503 });
5504 }
5505 }
5506 }
5507
5508 sub git_search_grep_body {
5509 my ($commitlist, $from, $to, $extra) = @_;
5510 $from = 0 unless defined $from;
5511 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5512
5513 print "<table class=\"commit_search\">\n";
5514 my $alternate = 1;
5515 for (my $i = $from; $i <= $to; $i++) {
5516 my %co = %{$commitlist->[$i]};
5517 if (!%co) {
5518 next;
5519 }
5520 my $commit = $co{'id'};
5521 if ($alternate) {
5522 print "<tr class=\"dark\">\n";
5523 } else {
5524 print "<tr class=\"light\">\n";
5525 }
5526 $alternate ^= 1;
5527 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5528 format_author_html('td', \%co, 15, 5) .
5529 "<td>" .
5530 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5531 -class => "list subject"},
5532 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5533 my $comment = $co{'comment'};
5534 foreach my $line (@$comment) {
5535 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5536 my ($lead, $match, $trail) = ($1, $2, $3);
5537 $match = chop_str($match, 70, 5, 'center');
5538 my $contextlen = int((80 - length($match))/2);
5539 $contextlen = 30 if ($contextlen > 30);
5540 $lead = chop_str($lead, $contextlen, 10, 'left');
5541 $trail = chop_str($trail, $contextlen, 10, 'right');
5542
5543 $lead = esc_html($lead);
5544 $match = esc_html($match);
5545 $trail = esc_html($trail);
5546
5547 print "$lead<span class=\"match\">$match</span>$trail<br />";
5548 }
5549 }
5550 print "</td>\n" .
5551 "<td class=\"link\">" .
5552 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5553 " | " .
5554 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5555 " | " .
5556 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5557 print "</td>\n" .
5558 "</tr>\n";
5559 }
5560 if (defined $extra) {
5561 print "<tr>\n" .
5562 "<td colspan=\"3\">$extra</td>\n" .
5563 "</tr>\n";
5564 }
5565 print "</table>\n";
5566 }
5567
5568 ## ======================================================================
5569 ## ======================================================================
5570 ## actions
5571
5572 sub git_project_list {
5573 my $order = $input_params{'order'};
5574 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5575 die_error(400, "Unknown order parameter");
5576 }
5577
5578 my @list = git_get_projects_list();
5579 if (!@list) {
5580 die_error(404, "No projects found");
5581 }
5582
5583 git_header_html();
5584 if (defined $home_text && -f $home_text) {
5585 print "<div class=\"index_include\">\n";
5586 insert_file($home_text);
5587 print "</div>\n";
5588 }
5589 print $cgi->startform(-method => "get") .
5590 "<p class=\"projsearch\">Search:\n" .
5591 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5592 "</p>" .
5593 $cgi->end_form() . "\n";
5594 git_project_list_body(\@list, $order);
5595 git_footer_html();
5596 }
5597
5598 sub git_forks {
5599 my $order = $input_params{'order'};
5600 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5601 die_error(400, "Unknown order parameter");
5602 }
5603
5604 my @list = git_get_projects_list($project);
5605 if (!@list) {
5606 die_error(404, "No forks found");
5607 }
5608
5609 git_header_html();
5610 git_print_page_nav('','');
5611 git_print_header_div('summary', "$project forks");
5612 git_project_list_body(\@list, $order);
5613 git_footer_html();
5614 }
5615
5616 sub git_project_index {
5617 my @projects = git_get_projects_list();
5618 if (!@projects) {
5619 die_error(404, "No projects found");
5620 }
5621
5622 print $cgi->header(
5623 -type => 'text/plain',
5624 -charset => 'utf-8',
5625 -content_disposition => 'inline; filename="index.aux"');
5626
5627 foreach my $pr (@projects) {
5628 if (!exists $pr->{'owner'}) {
5629 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5630 }
5631
5632 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5633 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5634 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5635 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5636 $path =~ s/ /\+/g;
5637 $owner =~ s/ /\+/g;
5638
5639 print "$path $owner\n";
5640 }
5641 }
5642
5643 sub git_summary {
5644 my $descr = git_get_project_description($project) || "none";
5645 my %co = parse_commit("HEAD");
5646 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5647 my $head = $co{'id'};
5648 my $remote_heads = gitweb_check_feature('remote_heads');
5649
5650 my $owner = git_get_project_owner($project);
5651
5652 my $refs = git_get_references();
5653 # These get_*_list functions return one more to allow us to see if
5654 # there are more ...
5655 my @taglist = git_get_tags_list(16);
5656 my @headlist = git_get_heads_list(16);
5657 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
5658 my @forklist;
5659 my $check_forks = gitweb_check_feature('forks');
5660
5661 if ($check_forks) {
5662 # find forks of a project
5663 @forklist = git_get_projects_list($project);
5664 # filter out forks of forks
5665 @forklist = filter_forks_from_projects_list(\@forklist)
5666 if (@forklist);
5667 }
5668
5669 git_header_html();
5670 git_print_page_nav('summary','', $head);
5671
5672 print "<div class=\"title\">&nbsp;</div>\n";
5673 print "<table class=\"projects_list\">\n" .
5674 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5675 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5676 if (defined $cd{'rfc2822'}) {
5677 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
5678 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
5679 }
5680
5681 # use per project git URL list in $projectroot/$project/cloneurl
5682 # or make project git URL from git base URL and project name
5683 my $url_tag = "URL";
5684 my @url_list = git_get_project_url_list($project);
5685 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5686 foreach my $git_url (@url_list) {
5687 next unless $git_url;
5688 print format_repo_url($url_tag, $git_url);
5689 $url_tag = "";
5690 }
5691
5692 # Tag cloud
5693 my $show_ctags = gitweb_check_feature('ctags');
5694 if ($show_ctags) {
5695 my $ctags = git_get_project_ctags($project);
5696 if (%$ctags) {
5697 # without ability to add tags, don't show if there are none
5698 my $cloud = git_populate_project_tagcloud($ctags);
5699 print "<tr id=\"metadata_ctags\">" .
5700 "<td>content tags</td>" .
5701 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
5702 "</tr>\n";
5703 }
5704 }
5705
5706 print "</table>\n";
5707
5708 # If XSS prevention is on, we don't include README.html.
5709 # TODO: Allow a readme in some safe format.
5710 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5711 print "<div class=\"title\">readme</div>\n" .
5712 "<div class=\"readme\">\n";
5713 insert_file("$projectroot/$project/README.html");
5714 print "\n</div>\n"; # class="readme"
5715 }
5716
5717 # we need to request one more than 16 (0..15) to check if
5718 # those 16 are all
5719 my @commitlist = $head ? parse_commits($head, 17) : ();
5720 if (@commitlist) {
5721 git_print_header_div('shortlog');
5722 git_shortlog_body(\@commitlist, 0, 15, $refs,
5723 $#commitlist <= 15 ? undef :
5724 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5725 }
5726
5727 if (@taglist) {
5728 git_print_header_div('tags');
5729 git_tags_body(\@taglist, 0, 15,
5730 $#taglist <= 15 ? undef :
5731 $cgi->a({-href => href(action=>"tags")}, "..."));
5732 }
5733
5734 if (@headlist) {
5735 git_print_header_div('heads');
5736 git_heads_body(\@headlist, $head, 0, 15,
5737 $#headlist <= 15 ? undef :
5738 $cgi->a({-href => href(action=>"heads")}, "..."));
5739 }
5740
5741 if (%remotedata) {
5742 git_print_header_div('remotes');
5743 git_remotes_body(\%remotedata, 15, $head);
5744 }
5745
5746 if (@forklist) {
5747 git_print_header_div('forks');
5748 git_project_list_body(\@forklist, 'age', 0, 15,
5749 $#forklist <= 15 ? undef :
5750 $cgi->a({-href => href(action=>"forks")}, "..."),
5751 'no_header');
5752 }
5753
5754 git_footer_html();
5755 }
5756
5757 sub git_tag {
5758 my %tag = parse_tag($hash);
5759
5760 if (! %tag) {
5761 die_error(404, "Unknown tag object");
5762 }
5763
5764 my $head = git_get_head_hash($project);
5765 git_header_html();
5766 git_print_page_nav('','', $head,undef,$head);
5767 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5768 print "<div class=\"title_text\">\n" .
5769 "<table class=\"object_header\">\n" .
5770 "<tr>\n" .
5771 "<td>object</td>\n" .
5772 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5773 $tag{'object'}) . "</td>\n" .
5774 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5775 $tag{'type'}) . "</td>\n" .
5776 "</tr>\n";
5777 if (defined($tag{'author'})) {
5778 git_print_authorship_rows(\%tag, 'author');
5779 }
5780 print "</table>\n\n" .
5781 "</div>\n";
5782 print "<div class=\"page_body\">";
5783 my $comment = $tag{'comment'};
5784 foreach my $line (@$comment) {
5785 chomp $line;
5786 print esc_html($line, -nbsp=>1) . "<br/>\n";
5787 }
5788 print "</div>\n";
5789 git_footer_html();
5790 }
5791
5792 sub git_blame_common {
5793 my $format = shift || 'porcelain';
5794 if ($format eq 'porcelain' && $cgi->param('js')) {
5795 $format = 'incremental';
5796 $action = 'blame_incremental'; # for page title etc
5797 }
5798
5799 # permissions
5800 gitweb_check_feature('blame')
5801 or die_error(403, "Blame view not allowed");
5802
5803 # error checking
5804 die_error(400, "No file name given") unless $file_name;
5805 $hash_base ||= git_get_head_hash($project);
5806 die_error(404, "Couldn't find base commit") unless $hash_base;
5807 my %co = parse_commit($hash_base)
5808 or die_error(404, "Commit not found");
5809 my $ftype = "blob";
5810 if (!defined $hash) {
5811 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5812 or die_error(404, "Error looking up file");
5813 } else {
5814 $ftype = git_get_type($hash);
5815 if ($ftype !~ "blob") {
5816 die_error(400, "Object is not a blob");
5817 }
5818 }
5819
5820 my $fd;
5821 if ($format eq 'incremental') {
5822 # get file contents (as base)
5823 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5824 or die_error(500, "Open git-cat-file failed");
5825 } elsif ($format eq 'data') {
5826 # run git-blame --incremental
5827 open $fd, "-|", git_cmd(), "blame", "--incremental",
5828 $hash_base, "--", $file_name
5829 or die_error(500, "Open git-blame --incremental failed");
5830 } else {
5831 # run git-blame --porcelain
5832 open $fd, "-|", git_cmd(), "blame", '-p',
5833 $hash_base, '--', $file_name
5834 or die_error(500, "Open git-blame --porcelain failed");
5835 }
5836
5837 # incremental blame data returns early
5838 if ($format eq 'data') {
5839 print $cgi->header(
5840 -type=>"text/plain", -charset => "utf-8",
5841 -status=> "200 OK");
5842 local $| = 1; # output autoflush
5843 print while <$fd>;
5844 close $fd
5845 or print "ERROR $!\n";
5846
5847 print 'END';
5848 if (defined $t0 && gitweb_check_feature('timed')) {
5849 print ' '.
5850 tv_interval($t0, [ gettimeofday() ]).
5851 ' '.$number_of_git_cmds;
5852 }
5853 print "\n";
5854
5855 return;
5856 }
5857
5858 # page header
5859 git_header_html();
5860 my $formats_nav =
5861 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5862 "blob") .
5863 " | ";
5864 if ($format eq 'incremental') {
5865 $formats_nav .=
5866 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5867 "blame") . " (non-incremental)";
5868 } else {
5869 $formats_nav .=
5870 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5871 "blame") . " (incremental)";
5872 }
5873 $formats_nav .=
5874 " | " .
5875 $cgi->a({-href => href(action=>"history", -replay=>1)},
5876 "history") .
5877 " | " .
5878 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5879 "HEAD");
5880 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5881 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5882 git_print_page_path($file_name, $ftype, $hash_base);
5883
5884 # page body
5885 if ($format eq 'incremental') {
5886 print "<noscript>\n<div class=\"error\"><center><b>\n".
5887 "This page requires JavaScript to run.\n Use ".
5888 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5889 'this page').
5890 " instead.\n".
5891 "</b></center></div>\n</noscript>\n";
5892
5893 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5894 }
5895
5896 print qq!<div class="page_body">\n!;
5897 print qq!<div id="progress_info">... / ...</div>\n!
5898 if ($format eq 'incremental');
5899 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5900 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5901 qq!<thead>\n!.
5902 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5903 qq!</thead>\n!.
5904 qq!<tbody>\n!;
5905
5906 my @rev_color = qw(light dark);
5907 my $num_colors = scalar(@rev_color);
5908 my $current_color = 0;
5909
5910 if ($format eq 'incremental') {
5911 my $color_class = $rev_color[$current_color];
5912
5913 #contents of a file
5914 my $linenr = 0;
5915 LINE:
5916 while (my $line = <$fd>) {
5917 chomp $line;
5918 $linenr++;
5919
5920 print qq!<tr id="l$linenr" class="$color_class">!.
5921 qq!<td class="sha1"><a href=""> </a></td>!.
5922 qq!<td class="linenr">!.
5923 qq!<a class="linenr" href="">$linenr</a></td>!;
5924 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5925 print qq!</tr>\n!;
5926 }
5927
5928 } else { # porcelain, i.e. ordinary blame
5929 my %metainfo = (); # saves information about commits
5930
5931 # blame data
5932 LINE:
5933 while (my $line = <$fd>) {
5934 chomp $line;
5935 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5936 # no <lines in group> for subsequent lines in group of lines
5937 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5938 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5939 if (!exists $metainfo{$full_rev}) {
5940 $metainfo{$full_rev} = { 'nprevious' => 0 };
5941 }
5942 my $meta = $metainfo{$full_rev};
5943 my $data;
5944 while ($data = <$fd>) {
5945 chomp $data;
5946 last if ($data =~ s/^\t//); # contents of line
5947 if ($data =~ /^(\S+)(?: (.*))?$/) {
5948 $meta->{$1} = $2 unless exists $meta->{$1};
5949 }
5950 if ($data =~ /^previous /) {
5951 $meta->{'nprevious'}++;
5952 }
5953 }
5954 my $short_rev = substr($full_rev, 0, 8);
5955 my $author = $meta->{'author'};
5956 my %date =
5957 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5958 my $date = $date{'iso-tz'};
5959 if ($group_size) {
5960 $current_color = ($current_color + 1) % $num_colors;
5961 }
5962 my $tr_class = $rev_color[$current_color];
5963 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5964 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5965 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5966 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5967 if ($group_size) {
5968 print "<td class=\"sha1\"";
5969 print " title=\"". esc_html($author) . ", $date\"";
5970 print " rowspan=\"$group_size\"" if ($group_size > 1);
5971 print ">";
5972 print $cgi->a({-href => href(action=>"commit",
5973 hash=>$full_rev,
5974 file_name=>$file_name)},
5975 esc_html($short_rev));
5976 if ($group_size >= 2) {
5977 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5978 if (@author_initials) {
5979 print "<br />" .
5980 esc_html(join('', @author_initials));
5981 # or join('.', ...)
5982 }
5983 }
5984 print "</td>\n";
5985 }
5986 # 'previous' <sha1 of parent commit> <filename at commit>
5987 if (exists $meta->{'previous'} &&
5988 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5989 $meta->{'parent'} = $1;
5990 $meta->{'file_parent'} = unquote($2);
5991 }
5992 my $linenr_commit =
5993 exists($meta->{'parent'}) ?
5994 $meta->{'parent'} : $full_rev;
5995 my $linenr_filename =
5996 exists($meta->{'file_parent'}) ?
5997 $meta->{'file_parent'} : unquote($meta->{'filename'});
5998 my $blamed = href(action => 'blame',
5999 file_name => $linenr_filename,
6000 hash_base => $linenr_commit);
6001 print "<td class=\"linenr\">";
6002 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6003 -class => "linenr" },
6004 esc_html($lineno));
6005 print "</td>";
6006 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6007 print "</tr>\n";
6008 } # end while
6009
6010 }
6011
6012 # footer
6013 print "</tbody>\n".
6014 "</table>\n"; # class="blame"
6015 print "</div>\n"; # class="blame_body"
6016 close $fd
6017 or print "Reading blob failed\n";
6018
6019 git_footer_html();
6020 }
6021
6022 sub git_blame {
6023 git_blame_common();
6024 }
6025
6026 sub git_blame_incremental {
6027 git_blame_common('incremental');
6028 }
6029
6030 sub git_blame_data {
6031 git_blame_common('data');
6032 }
6033
6034 sub git_tags {
6035 my $head = git_get_head_hash($project);
6036 git_header_html();
6037 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6038 git_print_header_div('summary', $project);
6039
6040 my @tagslist = git_get_tags_list();
6041 if (@tagslist) {
6042 git_tags_body(\@tagslist);
6043 }
6044 git_footer_html();
6045 }
6046
6047 sub git_heads {
6048 my $head = git_get_head_hash($project);
6049 git_header_html();
6050 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6051 git_print_header_div('summary', $project);
6052
6053 my @headslist = git_get_heads_list();
6054 if (@headslist) {
6055 git_heads_body(\@headslist, $head);
6056 }
6057 git_footer_html();
6058 }
6059
6060 # used both for single remote view and for list of all the remotes
6061 sub git_remotes {
6062 gitweb_check_feature('remote_heads')
6063 or die_error(403, "Remote heads view is disabled");
6064
6065 my $head = git_get_head_hash($project);
6066 my $remote = $input_params{'hash'};
6067
6068 my $remotedata = git_get_remotes_list($remote);
6069 die_error(500, "Unable to get remote information") unless defined $remotedata;
6070
6071 unless (%$remotedata) {
6072 die_error(404, defined $remote ?
6073 "Remote $remote not found" :
6074 "No remotes found");
6075 }
6076
6077 git_header_html(undef, undef, -action_extra => $remote);
6078 git_print_page_nav('', '', $head, undef, $head,
6079 format_ref_views($remote ? '' : 'remotes'));
6080
6081 fill_remote_heads($remotedata);
6082 if (defined $remote) {
6083 git_print_header_div('remotes', "$remote remote for $project");
6084 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6085 } else {
6086 git_print_header_div('summary', "$project remotes");
6087 git_remotes_body($remotedata, undef, $head);
6088 }
6089
6090 git_footer_html();
6091 }
6092
6093 sub git_blob_plain {
6094 my $type = shift;
6095 my $expires;
6096
6097 if (!defined $hash) {
6098 if (defined $file_name) {
6099 my $base = $hash_base || git_get_head_hash($project);
6100 $hash = git_get_hash_by_path($base, $file_name, "blob")
6101 or die_error(404, "Cannot find file");
6102 } else {
6103 die_error(400, "No file name defined");
6104 }
6105 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6106 # blobs defined by non-textual hash id's can be cached
6107 $expires = "+1d";
6108 }
6109
6110 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6111 or die_error(500, "Open git-cat-file blob '$hash' failed");
6112
6113 # content-type (can include charset)
6114 $type = blob_contenttype($fd, $file_name, $type);
6115
6116 # "save as" filename, even when no $file_name is given
6117 my $save_as = "$hash";
6118 if (defined $file_name) {
6119 $save_as = $file_name;
6120 } elsif ($type =~ m/^text\//) {
6121 $save_as .= '.txt';
6122 }
6123
6124 # With XSS prevention on, blobs of all types except a few known safe
6125 # ones are served with "Content-Disposition: attachment" to make sure
6126 # they don't run in our security domain. For certain image types,
6127 # blob view writes an <img> tag referring to blob_plain view, and we
6128 # want to be sure not to break that by serving the image as an
6129 # attachment (though Firefox 3 doesn't seem to care).
6130 my $sandbox = $prevent_xss &&
6131 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
6132
6133 print $cgi->header(
6134 -type => $type,
6135 -expires => $expires,
6136 -content_disposition =>
6137 ($sandbox ? 'attachment' : 'inline')
6138 . '; filename="' . $save_as . '"');
6139 local $/ = undef;
6140 binmode STDOUT, ':raw';
6141 print <$fd>;
6142 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6143 close $fd;
6144 }
6145
6146 sub git_blob {
6147 my $expires;
6148
6149 if (!defined $hash) {
6150 if (defined $file_name) {
6151 my $base = $hash_base || git_get_head_hash($project);
6152 $hash = git_get_hash_by_path($base, $file_name, "blob")
6153 or die_error(404, "Cannot find file");
6154 } else {
6155 die_error(400, "No file name defined");
6156 }
6157 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6158 # blobs defined by non-textual hash id's can be cached
6159 $expires = "+1d";
6160 }
6161
6162 my $have_blame = gitweb_check_feature('blame');
6163 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6164 or die_error(500, "Couldn't cat $file_name, $hash");
6165 my $mimetype = blob_mimetype($fd, $file_name);
6166 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
6167 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
6168 close $fd;
6169 return git_blob_plain($mimetype);
6170 }
6171 # we can have blame only for text/* mimetype
6172 $have_blame &&= ($mimetype =~ m!^text/!);
6173
6174 my $highlight = gitweb_check_feature('highlight');
6175 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
6176 $fd = run_highlighter($fd, $highlight, $syntax)
6177 if $syntax;
6178
6179 git_header_html(undef, $expires);
6180 my $formats_nav = '';
6181 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6182 if (defined $file_name) {
6183 if ($have_blame) {
6184 $formats_nav .=
6185 $cgi->a({-href => href(action=>"blame", -replay=>1)},
6186 "blame") .
6187 " | ";
6188 }
6189 $formats_nav .=
6190 $cgi->a({-href => href(action=>"history", -replay=>1)},
6191 "history") .
6192 " | " .
6193 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6194 "raw") .
6195 " | " .
6196 $cgi->a({-href => href(action=>"blob",
6197 hash_base=>"HEAD", file_name=>$file_name)},
6198 "HEAD");
6199 } else {
6200 $formats_nav .=
6201 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6202 "raw");
6203 }
6204 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6205 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6206 } else {
6207 print "<div class=\"page_nav\">\n" .
6208 "<br/><br/></div>\n" .
6209 "<div class=\"title\">".esc_html($hash)."</div>\n";
6210 }
6211 git_print_page_path($file_name, "blob", $hash_base);
6212 print "<div class=\"page_body\">\n";
6213 if ($mimetype =~ m!^image/!) {
6214 print qq!<img type="!.esc_attr($mimetype).qq!"!;
6215 if ($file_name) {
6216 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
6217 }
6218 print qq! src="! .
6219 href(action=>"blob_plain", hash=>$hash,
6220 hash_base=>$hash_base, file_name=>$file_name) .
6221 qq!" />\n!;
6222 } else {
6223 my $nr;
6224 while (my $line = <$fd>) {
6225 chomp $line;
6226 $nr++;
6227 $line = untabify($line);
6228 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
6229 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
6230 }
6231 }
6232 close $fd
6233 or print "Reading blob failed.\n";
6234 print "</div>";
6235 git_footer_html();
6236 }
6237
6238 sub git_tree {
6239 if (!defined $hash_base) {
6240 $hash_base = "HEAD";
6241 }
6242 if (!defined $hash) {
6243 if (defined $file_name) {
6244 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
6245 } else {
6246 $hash = $hash_base;
6247 }
6248 }
6249 die_error(404, "No such tree") unless defined($hash);
6250
6251 my $show_sizes = gitweb_check_feature('show-sizes');
6252 my $have_blame = gitweb_check_feature('blame');
6253
6254 my @entries = ();
6255 {
6256 local $/ = "\0";
6257 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
6258 ($show_sizes ? '-l' : ()), @extra_options, $hash
6259 or die_error(500, "Open git-ls-tree failed");
6260 @entries = map { chomp; $_ } <$fd>;
6261 close $fd
6262 or die_error(404, "Reading tree failed");
6263 }
6264
6265 my $refs = git_get_references();
6266 my $ref = format_ref_marker($refs, $hash_base);
6267 git_header_html();
6268 my $basedir = '';
6269 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6270 my @views_nav = ();
6271 if (defined $file_name) {
6272 push @views_nav,
6273 $cgi->a({-href => href(action=>"history", -replay=>1)},
6274 "history"),
6275 $cgi->a({-href => href(action=>"tree",
6276 hash_base=>"HEAD", file_name=>$file_name)},
6277 "HEAD"),
6278 }
6279 my $snapshot_links = format_snapshot_links($hash);
6280 if (defined $snapshot_links) {
6281 # FIXME: Should be available when we have no hash base as well.
6282 push @views_nav, $snapshot_links;
6283 }
6284 git_print_page_nav('tree','', $hash_base, undef, undef,
6285 join(' | ', @views_nav));
6286 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
6287 } else {
6288 undef $hash_base;
6289 print "<div class=\"page_nav\">\n";
6290 print "<br/><br/></div>\n";
6291 print "<div class=\"title\">".esc_html($hash)."</div>\n";
6292 }
6293 if (defined $file_name) {
6294 $basedir = $file_name;
6295 if ($basedir ne '' && substr($basedir, -1) ne '/') {
6296 $basedir .= '/';
6297 }
6298 git_print_page_path($file_name, 'tree', $hash_base);
6299 }
6300 print "<div class=\"page_body\">\n";
6301 print "<table class=\"tree\">\n";
6302 my $alternate = 1;
6303 # '..' (top directory) link if possible
6304 if (defined $hash_base &&
6305 defined $file_name && $file_name =~ m![^/]+$!) {
6306 if ($alternate) {
6307 print "<tr class=\"dark\">\n";
6308 } else {
6309 print "<tr class=\"light\">\n";
6310 }
6311 $alternate ^= 1;
6312
6313 my $up = $file_name;
6314 $up =~ s!/?[^/]+$!!;
6315 undef $up unless $up;
6316 # based on git_print_tree_entry
6317 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6318 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
6319 print '<td class="list">';
6320 print $cgi->a({-href => href(action=>"tree",
6321 hash_base=>$hash_base,
6322 file_name=>$up)},
6323 "..");
6324 print "</td>\n";
6325 print "<td class=\"link\"></td>\n";
6326
6327 print "</tr>\n";
6328 }
6329 foreach my $line (@entries) {
6330 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6331
6332 if ($alternate) {
6333 print "<tr class=\"dark\">\n";
6334 } else {
6335 print "<tr class=\"light\">\n";
6336 }
6337 $alternate ^= 1;
6338
6339 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6340
6341 print "</tr>\n";
6342 }
6343 print "</table>\n" .
6344 "</div>";
6345 git_footer_html();
6346 }
6347
6348 sub snapshot_name {
6349 my ($project, $hash) = @_;
6350
6351 # path/to/project.git -> project
6352 # path/to/project/.git -> project
6353 my $name = to_utf8($project);
6354 $name =~ s,([^/])/*\.git$,$1,;
6355 $name = basename($name);
6356 # sanitize name
6357 $name =~ s/[[:cntrl:]]/?/g;
6358
6359 my $ver = $hash;
6360 if ($hash =~ /^[0-9a-fA-F]+$/) {
6361 # shorten SHA-1 hash
6362 my $full_hash = git_get_full_hash($project, $hash);
6363 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6364 $ver = git_get_short_hash($project, $hash);
6365 }
6366 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6367 # tags don't need shortened SHA-1 hash
6368 $ver = $1;
6369 } else {
6370 # branches and other need shortened SHA-1 hash
6371 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6372 $ver = $1;
6373 }
6374 $ver .= '-' . git_get_short_hash($project, $hash);
6375 }
6376 # in case of hierarchical branch names
6377 $ver =~ s!/!.!g;
6378
6379 # name = project-version_string
6380 $name = "$name-$ver";
6381
6382 return wantarray ? ($name, $name) : $name;
6383 }
6384
6385 sub git_snapshot {
6386 my $format = $input_params{'snapshot_format'};
6387 if (!@snapshot_fmts) {
6388 die_error(403, "Snapshots not allowed");
6389 }
6390 # default to first supported snapshot format
6391 $format ||= $snapshot_fmts[0];
6392 if ($format !~ m/^[a-z0-9]+$/) {
6393 die_error(400, "Invalid snapshot format parameter");
6394 } elsif (!exists($known_snapshot_formats{$format})) {
6395 die_error(400, "Unknown snapshot format");
6396 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6397 die_error(403, "Snapshot format not allowed");
6398 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6399 die_error(403, "Unsupported snapshot format");
6400 }
6401
6402 my $type = git_get_type("$hash^{}");
6403 if (!$type) {
6404 die_error(404, 'Object does not exist');
6405 } elsif ($type eq 'blob') {
6406 die_error(400, 'Object is not a tree-ish');
6407 }
6408
6409 my ($name, $prefix) = snapshot_name($project, $hash);
6410 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6411 my $cmd = quote_command(
6412 git_cmd(), 'archive',
6413 "--format=$known_snapshot_formats{$format}{'format'}",
6414 "--prefix=$prefix/", $hash);
6415 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6416 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6417 }
6418
6419 $filename =~ s/(["\\])/\\$1/g;
6420 print $cgi->header(
6421 -type => $known_snapshot_formats{$format}{'type'},
6422 -content_disposition => 'inline; filename="' . $filename . '"',
6423 -status => '200 OK');
6424
6425 open my $fd, "-|", $cmd
6426 or die_error(500, "Execute git-archive failed");
6427 binmode STDOUT, ':raw';
6428 print <$fd>;
6429 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6430 close $fd;
6431 }
6432
6433 sub git_log_generic {
6434 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6435
6436 my $head = git_get_head_hash($project);
6437 if (!defined $base) {
6438 $base = $head;
6439 }
6440 if (!defined $page) {
6441 $page = 0;
6442 }
6443 my $refs = git_get_references();
6444
6445 my $commit_hash = $base;
6446 if (defined $parent) {
6447 $commit_hash = "$parent..$base";
6448 }
6449 my @commitlist =
6450 parse_commits($commit_hash, 101, (100 * $page),
6451 defined $file_name ? ($file_name, "--full-history") : ());
6452
6453 my $ftype;
6454 if (!defined $file_hash && defined $file_name) {
6455 # some commits could have deleted file in question,
6456 # and not have it in tree, but one of them has to have it
6457 for (my $i = 0; $i < @commitlist; $i++) {
6458 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6459 last if defined $file_hash;
6460 }
6461 }
6462 if (defined $file_hash) {
6463 $ftype = git_get_type($file_hash);
6464 }
6465 if (defined $file_name && !defined $ftype) {
6466 die_error(500, "Unknown type of object");
6467 }
6468 my %co;
6469 if (defined $file_name) {
6470 %co = parse_commit($base)
6471 or die_error(404, "Unknown commit object");
6472 }
6473
6474
6475 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6476 my $next_link = '';
6477 if ($#commitlist >= 100) {
6478 $next_link =
6479 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6480 -accesskey => "n", -title => "Alt-n"}, "next");
6481 }
6482 my $patch_max = gitweb_get_feature('patches');
6483 if ($patch_max && !defined $file_name) {
6484 if ($patch_max < 0 || @commitlist <= $patch_max) {
6485 $paging_nav .= " &sdot; " .
6486 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6487 "patches");
6488 }
6489 }
6490
6491 git_header_html();
6492 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6493 if (defined $file_name) {
6494 git_print_header_div('commit', esc_html($co{'title'}), $base);
6495 } else {
6496 git_print_header_div('summary', $project)
6497 }
6498 git_print_page_path($file_name, $ftype, $hash_base)
6499 if (defined $file_name);
6500
6501 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6502 $file_name, $file_hash, $ftype);
6503
6504 git_footer_html();
6505 }
6506
6507 sub git_log {
6508 git_log_generic('log', \&git_log_body,
6509 $hash, $hash_parent);
6510 }
6511
6512 sub git_commit {
6513 $hash ||= $hash_base || "HEAD";
6514 my %co = parse_commit($hash)
6515 or die_error(404, "Unknown commit object");
6516
6517 my $parent = $co{'parent'};
6518 my $parents = $co{'parents'}; # listref
6519
6520 # we need to prepare $formats_nav before any parameter munging
6521 my $formats_nav;
6522 if (!defined $parent) {
6523 # --root commitdiff
6524 $formats_nav .= '(initial)';
6525 } elsif (@$parents == 1) {
6526 # single parent commit
6527 $formats_nav .=
6528 '(parent: ' .
6529 $cgi->a({-href => href(action=>"commit",
6530 hash=>$parent)},
6531 esc_html(substr($parent, 0, 7))) .
6532 ')';
6533 } else {
6534 # merge commit
6535 $formats_nav .=
6536 '(merge: ' .
6537 join(' ', map {
6538 $cgi->a({-href => href(action=>"commit",
6539 hash=>$_)},
6540 esc_html(substr($_, 0, 7)));
6541 } @$parents ) .
6542 ')';
6543 }
6544 if (gitweb_check_feature('patches') && @$parents <= 1) {
6545 $formats_nav .= " | " .
6546 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6547 "patch");
6548 }
6549
6550 if (!defined $parent) {
6551 $parent = "--root";
6552 }
6553 my @difftree;
6554 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6555 @diff_opts,
6556 (@$parents <= 1 ? $parent : '-c'),
6557 $hash, "--"
6558 or die_error(500, "Open git-diff-tree failed");
6559 @difftree = map { chomp; $_ } <$fd>;
6560 close $fd or die_error(404, "Reading git-diff-tree failed");
6561
6562 # non-textual hash id's can be cached
6563 my $expires;
6564 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6565 $expires = "+1d";
6566 }
6567 my $refs = git_get_references();
6568 my $ref = format_ref_marker($refs, $co{'id'});
6569
6570 git_header_html(undef, $expires);
6571 git_print_page_nav('commit', '',
6572 $hash, $co{'tree'}, $hash,
6573 $formats_nav);
6574
6575 if (defined $co{'parent'}) {
6576 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6577 } else {
6578 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6579 }
6580 print "<div class=\"title_text\">\n" .
6581 "<table class=\"object_header\">\n";
6582 git_print_authorship_rows(\%co);
6583 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6584 print "<tr>" .
6585 "<td>tree</td>" .
6586 "<td class=\"sha1\">" .
6587 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6588 class => "list"}, $co{'tree'}) .
6589 "</td>" .
6590 "<td class=\"link\">" .
6591 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6592 "tree");
6593 my $snapshot_links = format_snapshot_links($hash);
6594 if (defined $snapshot_links) {
6595 print " | " . $snapshot_links;
6596 }
6597 print "</td>" .
6598 "</tr>\n";
6599
6600 foreach my $par (@$parents) {
6601 print "<tr>" .
6602 "<td>parent</td>" .
6603 "<td class=\"sha1\">" .
6604 $cgi->a({-href => href(action=>"commit", hash=>$par),
6605 class => "list"}, $par) .
6606 "</td>" .
6607 "<td class=\"link\">" .
6608 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6609 " | " .
6610 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6611 "</td>" .
6612 "</tr>\n";
6613 }
6614 print "</table>".
6615 "</div>\n";
6616
6617 print "<div class=\"page_body\">\n";
6618 git_print_log($co{'comment'});
6619 print "</div>\n";
6620
6621 git_difftree_body(\@difftree, $hash, @$parents);
6622
6623 git_footer_html();
6624 }
6625
6626 sub git_object {
6627 # object is defined by:
6628 # - hash or hash_base alone
6629 # - hash_base and file_name
6630 my $type;
6631
6632 # - hash or hash_base alone
6633 if ($hash || ($hash_base && !defined $file_name)) {
6634 my $object_id = $hash || $hash_base;
6635
6636 open my $fd, "-|", quote_command(
6637 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6638 or die_error(404, "Object does not exist");
6639 $type = <$fd>;
6640 chomp $type;
6641 close $fd
6642 or die_error(404, "Object does not exist");
6643
6644 # - hash_base and file_name
6645 } elsif ($hash_base && defined $file_name) {
6646 $file_name =~ s,/+$,,;
6647
6648 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6649 or die_error(404, "Base object does not exist");
6650
6651 # here errors should not hapen
6652 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6653 or die_error(500, "Open git-ls-tree failed");
6654 my $line = <$fd>;
6655 close $fd;
6656
6657 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6658 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6659 die_error(404, "File or directory for given base does not exist");
6660 }
6661 $type = $2;
6662 $hash = $3;
6663 } else {
6664 die_error(400, "Not enough information to find object");
6665 }
6666
6667 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6668 hash=>$hash, hash_base=>$hash_base,
6669 file_name=>$file_name),
6670 -status => '302 Found');
6671 }
6672
6673 sub git_blobdiff {
6674 my $format = shift || 'html';
6675
6676 my $fd;
6677 my @difftree;
6678 my %diffinfo;
6679 my $expires;
6680
6681 # preparing $fd and %diffinfo for git_patchset_body
6682 # new style URI
6683 if (defined $hash_base && defined $hash_parent_base) {
6684 if (defined $file_name) {
6685 # read raw output
6686 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6687 $hash_parent_base, $hash_base,
6688 "--", (defined $file_parent ? $file_parent : ()), $file_name
6689 or die_error(500, "Open git-diff-tree failed");
6690 @difftree = map { chomp; $_ } <$fd>;
6691 close $fd
6692 or die_error(404, "Reading git-diff-tree failed");
6693 @difftree
6694 or die_error(404, "Blob diff not found");
6695
6696 } elsif (defined $hash &&
6697 $hash =~ /[0-9a-fA-F]{40}/) {
6698 # try to find filename from $hash
6699
6700 # read filtered raw output
6701 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6702 $hash_parent_base, $hash_base, "--"
6703 or die_error(500, "Open git-diff-tree failed");
6704 @difftree =
6705 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6706 # $hash == to_id
6707 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6708 map { chomp; $_ } <$fd>;
6709 close $fd
6710 or die_error(404, "Reading git-diff-tree failed");
6711 @difftree
6712 or die_error(404, "Blob diff not found");
6713
6714 } else {
6715 die_error(400, "Missing one of the blob diff parameters");
6716 }
6717
6718 if (@difftree > 1) {
6719 die_error(400, "Ambiguous blob diff specification");
6720 }
6721
6722 %diffinfo = parse_difftree_raw_line($difftree[0]);
6723 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6724 $file_name ||= $diffinfo{'to_file'};
6725
6726 $hash_parent ||= $diffinfo{'from_id'};
6727 $hash ||= $diffinfo{'to_id'};
6728
6729 # non-textual hash id's can be cached
6730 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6731 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6732 $expires = '+1d';
6733 }
6734
6735 # open patch output
6736 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6737 '-p', ($format eq 'html' ? "--full-index" : ()),
6738 $hash_parent_base, $hash_base,
6739 "--", (defined $file_parent ? $file_parent : ()), $file_name
6740 or die_error(500, "Open git-diff-tree failed");
6741 }
6742
6743 # old/legacy style URI -- not generated anymore since 1.4.3.
6744 if (!%diffinfo) {
6745 die_error('404 Not Found', "Missing one of the blob diff parameters")
6746 }
6747
6748 # header
6749 if ($format eq 'html') {
6750 my $formats_nav =
6751 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6752 "raw");
6753 git_header_html(undef, $expires);
6754 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6755 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6756 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6757 } else {
6758 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6759 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
6760 }
6761 if (defined $file_name) {
6762 git_print_page_path($file_name, "blob", $hash_base);
6763 } else {
6764 print "<div class=\"page_path\"></div>\n";
6765 }
6766
6767 } elsif ($format eq 'plain') {
6768 print $cgi->header(
6769 -type => 'text/plain',
6770 -charset => 'utf-8',
6771 -expires => $expires,
6772 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6773
6774 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6775
6776 } else {
6777 die_error(400, "Unknown blobdiff format");
6778 }
6779
6780 # patch
6781 if ($format eq 'html') {
6782 print "<div class=\"page_body\">\n";
6783
6784 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6785 close $fd;
6786
6787 print "</div>\n"; # class="page_body"
6788 git_footer_html();
6789
6790 } else {
6791 while (my $line = <$fd>) {
6792 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6793 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6794
6795 print $line;
6796
6797 last if $line =~ m!^\+\+\+!;
6798 }
6799 local $/ = undef;
6800 print <$fd>;
6801 close $fd;
6802 }
6803 }
6804
6805 sub git_blobdiff_plain {
6806 git_blobdiff('plain');
6807 }
6808
6809 sub git_commitdiff {
6810 my %params = @_;
6811 my $format = $params{-format} || 'html';
6812
6813 my ($patch_max) = gitweb_get_feature('patches');
6814 if ($format eq 'patch') {
6815 die_error(403, "Patch view not allowed") unless $patch_max;
6816 }
6817
6818 $hash ||= $hash_base || "HEAD";
6819 my %co = parse_commit($hash)
6820 or die_error(404, "Unknown commit object");
6821
6822 # choose format for commitdiff for merge
6823 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6824 $hash_parent = '--cc';
6825 }
6826 # we need to prepare $formats_nav before almost any parameter munging
6827 my $formats_nav;
6828 if ($format eq 'html') {
6829 $formats_nav =
6830 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6831 "raw");
6832 if ($patch_max && @{$co{'parents'}} <= 1) {
6833 $formats_nav .= " | " .
6834 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6835 "patch");
6836 }
6837
6838 if (defined $hash_parent &&
6839 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6840 # commitdiff with two commits given
6841 my $hash_parent_short = $hash_parent;
6842 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6843 $hash_parent_short = substr($hash_parent, 0, 7);
6844 }
6845 $formats_nav .=
6846 ' (from';
6847 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6848 if ($co{'parents'}[$i] eq $hash_parent) {
6849 $formats_nav .= ' parent ' . ($i+1);
6850 last;
6851 }
6852 }
6853 $formats_nav .= ': ' .
6854 $cgi->a({-href => href(action=>"commitdiff",
6855 hash=>$hash_parent)},
6856 esc_html($hash_parent_short)) .
6857 ')';
6858 } elsif (!$co{'parent'}) {
6859 # --root commitdiff
6860 $formats_nav .= ' (initial)';
6861 } elsif (scalar @{$co{'parents'}} == 1) {
6862 # single parent commit
6863 $formats_nav .=
6864 ' (parent: ' .
6865 $cgi->a({-href => href(action=>"commitdiff",
6866 hash=>$co{'parent'})},
6867 esc_html(substr($co{'parent'}, 0, 7))) .
6868 ')';
6869 } else {
6870 # merge commit
6871 if ($hash_parent eq '--cc') {
6872 $formats_nav .= ' | ' .
6873 $cgi->a({-href => href(action=>"commitdiff",
6874 hash=>$hash, hash_parent=>'-c')},
6875 'combined');
6876 } else { # $hash_parent eq '-c'
6877 $formats_nav .= ' | ' .
6878 $cgi->a({-href => href(action=>"commitdiff",
6879 hash=>$hash, hash_parent=>'--cc')},
6880 'compact');
6881 }
6882 $formats_nav .=
6883 ' (merge: ' .
6884 join(' ', map {
6885 $cgi->a({-href => href(action=>"commitdiff",
6886 hash=>$_)},
6887 esc_html(substr($_, 0, 7)));
6888 } @{$co{'parents'}} ) .
6889 ')';
6890 }
6891 }
6892
6893 my $hash_parent_param = $hash_parent;
6894 if (!defined $hash_parent_param) {
6895 # --cc for multiple parents, --root for parentless
6896 $hash_parent_param =
6897 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6898 }
6899
6900 # read commitdiff
6901 my $fd;
6902 my @difftree;
6903 if ($format eq 'html') {
6904 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6905 "--no-commit-id", "--patch-with-raw", "--full-index",
6906 $hash_parent_param, $hash, "--"
6907 or die_error(500, "Open git-diff-tree failed");
6908
6909 while (my $line = <$fd>) {
6910 chomp $line;
6911 # empty line ends raw part of diff-tree output
6912 last unless $line;
6913 push @difftree, scalar parse_difftree_raw_line($line);
6914 }
6915
6916 } elsif ($format eq 'plain') {
6917 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6918 '-p', $hash_parent_param, $hash, "--"
6919 or die_error(500, "Open git-diff-tree failed");
6920 } elsif ($format eq 'patch') {
6921 # For commit ranges, we limit the output to the number of
6922 # patches specified in the 'patches' feature.
6923 # For single commits, we limit the output to a single patch,
6924 # diverging from the git-format-patch default.
6925 my @commit_spec = ();
6926 if ($hash_parent) {
6927 if ($patch_max > 0) {
6928 push @commit_spec, "-$patch_max";
6929 }
6930 push @commit_spec, '-n', "$hash_parent..$hash";
6931 } else {
6932 if ($params{-single}) {
6933 push @commit_spec, '-1';
6934 } else {
6935 if ($patch_max > 0) {
6936 push @commit_spec, "-$patch_max";
6937 }
6938 push @commit_spec, "-n";
6939 }
6940 push @commit_spec, '--root', $hash;
6941 }
6942 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6943 '--encoding=utf8', '--stdout', @commit_spec
6944 or die_error(500, "Open git-format-patch failed");
6945 } else {
6946 die_error(400, "Unknown commitdiff format");
6947 }
6948
6949 # non-textual hash id's can be cached
6950 my $expires;
6951 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6952 $expires = "+1d";
6953 }
6954
6955 # write commit message
6956 if ($format eq 'html') {
6957 my $refs = git_get_references();
6958 my $ref = format_ref_marker($refs, $co{'id'});
6959
6960 git_header_html(undef, $expires);
6961 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6962 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6963 print "<div class=\"title_text\">\n" .
6964 "<table class=\"object_header\">\n";
6965 git_print_authorship_rows(\%co);
6966 print "</table>".
6967 "</div>\n";
6968 print "<div class=\"page_body\">\n";
6969 if (@{$co{'comment'}} > 1) {
6970 print "<div class=\"log\">\n";
6971 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6972 print "</div>\n"; # class="log"
6973 }
6974
6975 } elsif ($format eq 'plain') {
6976 my $refs = git_get_references("tags");
6977 my $tagname = git_get_rev_name_tags($hash);
6978 my $filename = basename($project) . "-$hash.patch";
6979
6980 print $cgi->header(
6981 -type => 'text/plain',
6982 -charset => 'utf-8',
6983 -expires => $expires,
6984 -content_disposition => 'inline; filename="' . "$filename" . '"');
6985 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6986 print "From: " . to_utf8($co{'author'}) . "\n";
6987 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6988 print "Subject: " . to_utf8($co{'title'}) . "\n";
6989
6990 print "X-Git-Tag: $tagname\n" if $tagname;
6991 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6992
6993 foreach my $line (@{$co{'comment'}}) {
6994 print to_utf8($line) . "\n";
6995 }
6996 print "---\n\n";
6997 } elsif ($format eq 'patch') {
6998 my $filename = basename($project) . "-$hash.patch";
6999
7000 print $cgi->header(
7001 -type => 'text/plain',
7002 -charset => 'utf-8',
7003 -expires => $expires,
7004 -content_disposition => 'inline; filename="' . "$filename" . '"');
7005 }
7006
7007 # write patch
7008 if ($format eq 'html') {
7009 my $use_parents = !defined $hash_parent ||
7010 $hash_parent eq '-c' || $hash_parent eq '--cc';
7011 git_difftree_body(\@difftree, $hash,
7012 $use_parents ? @{$co{'parents'}} : $hash_parent);
7013 print "<br/>\n";
7014
7015 git_patchset_body($fd, \@difftree, $hash,
7016 $use_parents ? @{$co{'parents'}} : $hash_parent);
7017 close $fd;
7018 print "</div>\n"; # class="page_body"
7019 git_footer_html();
7020
7021 } elsif ($format eq 'plain') {
7022 local $/ = undef;
7023 print <$fd>;
7024 close $fd
7025 or print "Reading git-diff-tree failed\n";
7026 } elsif ($format eq 'patch') {
7027 local $/ = undef;
7028 print <$fd>;
7029 close $fd
7030 or print "Reading git-format-patch failed\n";
7031 }
7032 }
7033
7034 sub git_commitdiff_plain {
7035 git_commitdiff(-format => 'plain');
7036 }
7037
7038 # format-patch-style patches
7039 sub git_patch {
7040 git_commitdiff(-format => 'patch', -single => 1);
7041 }
7042
7043 sub git_patches {
7044 git_commitdiff(-format => 'patch');
7045 }
7046
7047 sub git_history {
7048 git_log_generic('history', \&git_history_body,
7049 $hash_base, $hash_parent_base,
7050 $file_name, $hash);
7051 }
7052
7053 sub git_search {
7054 gitweb_check_feature('search') or die_error(403, "Search is disabled");
7055 if (!defined $searchtext) {
7056 die_error(400, "Text field is empty");
7057 }
7058 if (!defined $hash) {
7059 $hash = git_get_head_hash($project);
7060 }
7061 my %co = parse_commit($hash);
7062 if (!%co) {
7063 die_error(404, "Unknown commit object");
7064 }
7065 if (!defined $page) {
7066 $page = 0;
7067 }
7068
7069 $searchtype ||= 'commit';
7070 if ($searchtype eq 'pickaxe') {
7071 # pickaxe may take all resources of your box and run for several minutes
7072 # with every query - so decide by yourself how public you make this feature
7073 gitweb_check_feature('pickaxe')
7074 or die_error(403, "Pickaxe is disabled");
7075 }
7076 if ($searchtype eq 'grep') {
7077 gitweb_check_feature('grep')[0]
7078 or die_error(403, "Grep is disabled");
7079 }
7080
7081 git_header_html();
7082
7083 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
7084 my $greptype;
7085 if ($searchtype eq 'commit') {
7086 $greptype = "--grep=";
7087 } elsif ($searchtype eq 'author') {
7088 $greptype = "--author=";
7089 } elsif ($searchtype eq 'committer') {
7090 $greptype = "--committer=";
7091 }
7092 $greptype .= $searchtext;
7093 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
7094 $greptype, '--regexp-ignore-case',
7095 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
7096
7097 my $paging_nav = '';
7098 if ($page > 0) {
7099 $paging_nav .=
7100 $cgi->a({-href => href(action=>"search", hash=>$hash,
7101 searchtext=>$searchtext,
7102 searchtype=>$searchtype)},
7103 "first");
7104 $paging_nav .= " &sdot; " .
7105 $cgi->a({-href => href(-replay=>1, page=>$page-1),
7106 -accesskey => "p", -title => "Alt-p"}, "prev");
7107 } else {
7108 $paging_nav .= "first";
7109 $paging_nav .= " &sdot; prev";
7110 }
7111 my $next_link = '';
7112 if ($#commitlist >= 100) {
7113 $next_link =
7114 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7115 -accesskey => "n", -title => "Alt-n"}, "next");
7116 $paging_nav .= " &sdot; $next_link";
7117 } else {
7118 $paging_nav .= " &sdot; next";
7119 }
7120
7121 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
7122 git_print_header_div('commit', esc_html($co{'title'}), $hash);
7123 if ($page == 0 && !@commitlist) {
7124 print "<p>No match.</p>\n";
7125 } else {
7126 git_search_grep_body(\@commitlist, 0, 99, $next_link);
7127 }
7128 }
7129
7130 if ($searchtype eq 'pickaxe') {
7131 git_print_page_nav('','', $hash,$co{'tree'},$hash);
7132 git_print_header_div('commit', esc_html($co{'title'}), $hash);
7133
7134 print "<table class=\"pickaxe search\">\n";
7135 my $alternate = 1;
7136 local $/ = "\n";
7137 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
7138 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
7139 ($search_use_regexp ? '--pickaxe-regex' : ());
7140 undef %co;
7141 my @files;
7142 while (my $line = <$fd>) {
7143 chomp $line;
7144 next unless $line;
7145
7146 my %set = parse_difftree_raw_line($line);
7147 if (defined $set{'commit'}) {
7148 # finish previous commit
7149 if (%co) {
7150 print "</td>\n" .
7151 "<td class=\"link\">" .
7152 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
7153 " | " .
7154 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
7155 print "</td>\n" .
7156 "</tr>\n";
7157 }
7158
7159 if ($alternate) {
7160 print "<tr class=\"dark\">\n";
7161 } else {
7162 print "<tr class=\"light\">\n";
7163 }
7164 $alternate ^= 1;
7165 %co = parse_commit($set{'commit'});
7166 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
7167 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
7168 "<td><i>$author</i></td>\n" .
7169 "<td>" .
7170 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
7171 -class => "list subject"},
7172 chop_and_escape_str($co{'title'}, 50) . "<br/>");
7173 } elsif (defined $set{'to_id'}) {
7174 next if ($set{'to_id'} =~ m/^0{40}$/);
7175
7176 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
7177 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
7178 -class => "list"},
7179 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
7180 "<br/>\n";
7181 }
7182 }
7183 close $fd;
7184
7185 # finish last commit (warning: repetition!)
7186 if (%co) {
7187 print "</td>\n" .
7188 "<td class=\"link\">" .
7189 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
7190 " | " .
7191 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
7192 print "</td>\n" .
7193 "</tr>\n";
7194 }
7195
7196 print "</table>\n";
7197 }
7198
7199 if ($searchtype eq 'grep') {
7200 git_print_page_nav('','', $hash,$co{'tree'},$hash);
7201 git_print_header_div('commit', esc_html($co{'title'}), $hash);
7202
7203 print "<table class=\"grep_search\">\n";
7204 my $alternate = 1;
7205 my $matches = 0;
7206 local $/ = "\n";
7207 open my $fd, "-|", git_cmd(), 'grep', '-n',
7208 $search_use_regexp ? ('-E', '-i') : '-F',
7209 $searchtext, $co{'tree'};
7210 my $lastfile = '';
7211 while (my $line = <$fd>) {
7212 chomp $line;
7213 my ($file, $lno, $ltext, $binary);
7214 last if ($matches++ > 1000);
7215 if ($line =~ /^Binary file (.+) matches$/) {
7216 $file = $1;
7217 $binary = 1;
7218 } else {
7219 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
7220 }
7221 if ($file ne $lastfile) {
7222 $lastfile and print "</td></tr>\n";
7223 if ($alternate++) {
7224 print "<tr class=\"dark\">\n";
7225 } else {
7226 print "<tr class=\"light\">\n";
7227 }
7228 print "<td class=\"list\">".
7229 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
7230 file_name=>"$file"),
7231 -class => "list"}, esc_path($file));
7232 print "</td><td>\n";
7233 $lastfile = $file;
7234 }
7235 if ($binary) {
7236 print "<div class=\"binary\">Binary file</div>\n";
7237 } else {
7238 $ltext = untabify($ltext);
7239 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
7240 $ltext = esc_html($1, -nbsp=>1);
7241 $ltext .= '<span class="match">';
7242 $ltext .= esc_html($2, -nbsp=>1);
7243 $ltext .= '</span>';
7244 $ltext .= esc_html($3, -nbsp=>1);
7245 } else {
7246 $ltext = esc_html($ltext, -nbsp=>1);
7247 }
7248 print "<div class=\"pre\">" .
7249 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
7250 file_name=>"$file").'#l'.$lno,
7251 -class => "linenr"}, sprintf('%4i', $lno))
7252 . ' ' . $ltext . "</div>\n";
7253 }
7254 }
7255 if ($lastfile) {
7256 print "</td></tr>\n";
7257 if ($matches > 1000) {
7258 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
7259 }
7260 } else {
7261 print "<div class=\"diff nodifferences\">No matches found</div>\n";
7262 }
7263 close $fd;
7264
7265 print "</table>\n";
7266 }
7267 git_footer_html();
7268 }
7269
7270 sub git_search_help {
7271 git_header_html();
7272 git_print_page_nav('','', $hash,$hash,$hash);
7273 print <<EOT;
7274 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7275 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7276 the pattern entered is recognized as the POSIX extended
7277 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7278 insensitive).</p>
7279 <dl>
7280 <dt><b>commit</b></dt>
7281 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7282 EOT
7283 my $have_grep = gitweb_check_feature('grep');
7284 if ($have_grep) {
7285 print <<EOT;
7286 <dt><b>grep</b></dt>
7287 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7288 a different one) are searched for the given pattern. On large trees, this search can take
7289 a while and put some strain on the server, so please use it with some consideration. Note that
7290 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7291 case-sensitive.</dd>
7292 EOT
7293 }
7294 print <<EOT;
7295 <dt><b>author</b></dt>
7296 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7297 <dt><b>committer</b></dt>
7298 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7299 EOT
7300 my $have_pickaxe = gitweb_check_feature('pickaxe');
7301 if ($have_pickaxe) {
7302 print <<EOT;
7303 <dt><b>pickaxe</b></dt>
7304 <dd>All commits that caused the string to appear or disappear from any file (changes that
7305 added, removed or "modified" the string) will be listed. This search can take a while and
7306 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7307 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7308 EOT
7309 }
7310 print "</dl>\n";
7311 git_footer_html();
7312 }
7313
7314 sub git_shortlog {
7315 git_log_generic('shortlog', \&git_shortlog_body,
7316 $hash, $hash_parent);
7317 }
7318
7319 ## ......................................................................
7320 ## feeds (RSS, Atom; OPML)
7321
7322 sub git_feed {
7323 my $format = shift || 'atom';
7324 my $have_blame = gitweb_check_feature('blame');
7325
7326 # Atom: http://www.atomenabled.org/developers/syndication/
7327 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7328 if ($format ne 'rss' && $format ne 'atom') {
7329 die_error(400, "Unknown web feed format");
7330 }
7331
7332 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7333 my $head = $hash || 'HEAD';
7334 my @commitlist = parse_commits($head, 150, 0, $file_name);
7335
7336 my %latest_commit;
7337 my %latest_date;
7338 my $content_type = "application/$format+xml";
7339 if (defined $cgi->http('HTTP_ACCEPT') &&
7340 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7341 # browser (feed reader) prefers text/xml
7342 $content_type = 'text/xml';
7343 }
7344 if (defined($commitlist[0])) {
7345 %latest_commit = %{$commitlist[0]};
7346 my $latest_epoch = $latest_commit{'committer_epoch'};
7347 %latest_date = parse_date($latest_epoch, $latest_commit{'comitter_tz'});
7348 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7349 if (defined $if_modified) {
7350 my $since;
7351 if (eval { require HTTP::Date; 1; }) {
7352 $since = HTTP::Date::str2time($if_modified);
7353 } elsif (eval { require Time::ParseDate; 1; }) {
7354 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7355 }
7356 if (defined $since && $latest_epoch <= $since) {
7357 print $cgi->header(
7358 -type => $content_type,
7359 -charset => 'utf-8',
7360 -last_modified => $latest_date{'rfc2822'},
7361 -status => '304 Not Modified');
7362 return;
7363 }
7364 }
7365 print $cgi->header(
7366 -type => $content_type,
7367 -charset => 'utf-8',
7368 -last_modified => $latest_date{'rfc2822'});
7369 } else {
7370 print $cgi->header(
7371 -type => $content_type,
7372 -charset => 'utf-8');
7373 }
7374
7375 # Optimization: skip generating the body if client asks only
7376 # for Last-Modified date.
7377 return if ($cgi->request_method() eq 'HEAD');
7378
7379 # header variables
7380 my $title = "$site_name - $project/$action";
7381 my $feed_type = 'log';
7382 if (defined $hash) {
7383 $title .= " - '$hash'";
7384 $feed_type = 'branch log';
7385 if (defined $file_name) {
7386 $title .= " :: $file_name";
7387 $feed_type = 'history';
7388 }
7389 } elsif (defined $file_name) {
7390 $title .= " - $file_name";
7391 $feed_type = 'history';
7392 }
7393 $title .= " $feed_type";
7394 my $descr = git_get_project_description($project);
7395 if (defined $descr) {
7396 $descr = esc_html($descr);
7397 } else {
7398 $descr = "$project " .
7399 ($format eq 'rss' ? 'RSS' : 'Atom') .
7400 " feed";
7401 }
7402 my $owner = git_get_project_owner($project);
7403 $owner = esc_html($owner);
7404
7405 #header
7406 my $alt_url;
7407 if (defined $file_name) {
7408 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7409 } elsif (defined $hash) {
7410 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7411 } else {
7412 $alt_url = href(-full=>1, action=>"summary");
7413 }
7414 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7415 if ($format eq 'rss') {
7416 print <<XML;
7417 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7418 <channel>
7419 XML
7420 print "<title>$title</title>\n" .
7421 "<link>$alt_url</link>\n" .
7422 "<description>$descr</description>\n" .
7423 "<language>en</language>\n" .
7424 # project owner is responsible for 'editorial' content
7425 "<managingEditor>$owner</managingEditor>\n";
7426 if (defined $logo || defined $favicon) {
7427 # prefer the logo to the favicon, since RSS
7428 # doesn't allow both
7429 my $img = esc_url($logo || $favicon);
7430 print "<image>\n" .
7431 "<url>$img</url>\n" .
7432 "<title>$title</title>\n" .
7433 "<link>$alt_url</link>\n" .
7434 "</image>\n";
7435 }
7436 if (%latest_date) {
7437 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7438 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7439 }
7440 print "<generator>gitweb v.$version/$git_version</generator>\n";
7441 } elsif ($format eq 'atom') {
7442 print <<XML;
7443 <feed xmlns="http://www.w3.org/2005/Atom">
7444 XML
7445 print "<title>$title</title>\n" .
7446 "<subtitle>$descr</subtitle>\n" .
7447 '<link rel="alternate" type="text/html" href="' .
7448 $alt_url . '" />' . "\n" .
7449 '<link rel="self" type="' . $content_type . '" href="' .
7450 $cgi->self_url() . '" />' . "\n" .
7451 "<id>" . href(-full=>1) . "</id>\n" .
7452 # use project owner for feed author
7453 "<author><name>$owner</name></author>\n";
7454 if (defined $favicon) {
7455 print "<icon>" . esc_url($favicon) . "</icon>\n";
7456 }
7457 if (defined $logo) {
7458 # not twice as wide as tall: 72 x 27 pixels
7459 print "<logo>" . esc_url($logo) . "</logo>\n";
7460 }
7461 if (! %latest_date) {
7462 # dummy date to keep the feed valid until commits trickle in:
7463 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7464 } else {
7465 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7466 }
7467 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7468 }
7469
7470 # contents
7471 for (my $i = 0; $i <= $#commitlist; $i++) {
7472 my %co = %{$commitlist[$i]};
7473 my $commit = $co{'id'};
7474 # we read 150, we always show 30 and the ones more recent than 48 hours
7475 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7476 last;
7477 }
7478 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
7479
7480 # get list of changed files
7481 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7482 $co{'parent'} || "--root",
7483 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7484 or next;
7485 my @difftree = map { chomp; $_ } <$fd>;
7486 close $fd
7487 or next;
7488
7489 # print element (entry, item)
7490 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7491 if ($format eq 'rss') {
7492 print "<item>\n" .
7493 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7494 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7495 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7496 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7497 "<link>$co_url</link>\n" .
7498 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7499 "<content:encoded>" .
7500 "<![CDATA[\n";
7501 } elsif ($format eq 'atom') {
7502 print "<entry>\n" .
7503 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7504 "<updated>$cd{'iso-8601'}</updated>\n" .
7505 "<author>\n" .
7506 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7507 if ($co{'author_email'}) {
7508 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7509 }
7510 print "</author>\n" .
7511 # use committer for contributor
7512 "<contributor>\n" .
7513 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7514 if ($co{'committer_email'}) {
7515 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7516 }
7517 print "</contributor>\n" .
7518 "<published>$cd{'iso-8601'}</published>\n" .
7519 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7520 "<id>$co_url</id>\n" .
7521 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7522 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7523 }
7524 my $comment = $co{'comment'};
7525 print "<pre>\n";
7526 foreach my $line (@$comment) {
7527 $line = esc_html($line);
7528 print "$line\n";
7529 }
7530 print "</pre><ul>\n";
7531 foreach my $difftree_line (@difftree) {
7532 my %difftree = parse_difftree_raw_line($difftree_line);
7533 next if !$difftree{'from_id'};
7534
7535 my $file = $difftree{'file'} || $difftree{'to_file'};
7536
7537 print "<li>" .
7538 "[" .
7539 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7540 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7541 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7542 file_name=>$file, file_parent=>$difftree{'from_file'}),
7543 -title => "diff"}, 'D');
7544 if ($have_blame) {
7545 print $cgi->a({-href => href(-full=>1, action=>"blame",
7546 file_name=>$file, hash_base=>$commit),
7547 -title => "blame"}, 'B');
7548 }
7549 # if this is not a feed of a file history
7550 if (!defined $file_name || $file_name ne $file) {
7551 print $cgi->a({-href => href(-full=>1, action=>"history",
7552 file_name=>$file, hash=>$commit),
7553 -title => "history"}, 'H');
7554 }
7555 $file = esc_path($file);
7556 print "] ".
7557 "$file</li>\n";
7558 }
7559 if ($format eq 'rss') {
7560 print "</ul>]]>\n" .
7561 "</content:encoded>\n" .
7562 "</item>\n";
7563 } elsif ($format eq 'atom') {
7564 print "</ul>\n</div>\n" .
7565 "</content>\n" .
7566 "</entry>\n";
7567 }
7568 }
7569
7570 # end of feed
7571 if ($format eq 'rss') {
7572 print "</channel>\n</rss>\n";
7573 } elsif ($format eq 'atom') {
7574 print "</feed>\n";
7575 }
7576 }
7577
7578 sub git_rss {
7579 git_feed('rss');
7580 }
7581
7582 sub git_atom {
7583 git_feed('atom');
7584 }
7585
7586 sub git_opml {
7587 my @list = git_get_projects_list();
7588 if (!@list) {
7589 die_error(404, "No projects found");
7590 }
7591
7592 print $cgi->header(
7593 -type => 'text/xml',
7594 -charset => 'utf-8',
7595 -content_disposition => 'inline; filename="opml.xml"');
7596
7597 print <<XML;
7598 <?xml version="1.0" encoding="utf-8"?>
7599 <opml version="1.0">
7600 <head>
7601 <title>$site_name OPML Export</title>
7602 </head>
7603 <body>
7604 <outline text="git RSS feeds">
7605 XML
7606
7607 foreach my $pr (@list) {
7608 my %proj = %$pr;
7609 my $head = git_get_head_hash($proj{'path'});
7610 if (!defined $head) {
7611 next;
7612 }
7613 $git_dir = "$projectroot/$proj{'path'}";
7614 my %co = parse_commit($head);
7615 if (!%co) {
7616 next;
7617 }
7618
7619 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7620 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7621 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7622 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7623 }
7624 print <<XML;
7625 </outline>
7626 </body>
7627 </opml>
7628 XML
7629 }
This page took 7.123753 seconds and 5 git commands to generate.