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