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