]> Lady’s Gitweb - Gitweb/blob - gitweb.perl
7ee310ee82c5f7d3f0c26bcc9c704bc7b3bb3da63d0de8d43834e27746c40847
[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 sub git_get_project_description {
2567 my $path = shift;
2568
2569 $git_dir = "$projectroot/$path";
2570 open my $fd, '<', "$git_dir/description"
2571 or return git_get_project_config('description');
2572 my $descr = <$fd>;
2573 close $fd;
2574 if (defined $descr) {
2575 chomp $descr;
2576 }
2577 return $descr;
2578 }
2579
2580 # supported formats:
2581 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2582 # - if its contents is a number, use it as tag weight,
2583 # - otherwise add a tag with weight 1
2584 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2585 # the same value multiple times increases tag weight
2586 # * `gitweb.ctag' multi-valued repo config variable
2587 sub git_get_project_ctags {
2588 my $project = shift;
2589 my $ctags = {};
2590
2591 $git_dir = "$projectroot/$project";
2592 if (opendir my $dh, "$git_dir/ctags") {
2593 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2594 foreach my $tagfile (@files) {
2595 open my $ct, '<', $tagfile
2596 or next;
2597 my $val = <$ct>;
2598 chomp $val if $val;
2599 close $ct;
2600
2601 (my $ctag = $tagfile) =~ s#.*/##;
2602 if ($val =~ /\d+/) {
2603 $ctags->{$ctag} = $val;
2604 } else {
2605 $ctags->{$ctag} = 1;
2606 }
2607 }
2608 closedir $dh;
2609
2610 } elsif (open my $fh, '<', "$git_dir/ctags") {
2611 while (my $line = <$fh>) {
2612 chomp $line;
2613 $ctags->{$line}++ if $line;
2614 }
2615 close $fh;
2616
2617 } else {
2618 my $taglist = config_to_multi(git_get_project_config('ctag'));
2619 foreach my $tag (@$taglist) {
2620 $ctags->{$tag}++;
2621 }
2622 }
2623
2624 return $ctags;
2625 }
2626
2627 # return hash, where keys are content tags ('ctags'),
2628 # and values are sum of weights of given tag in every project
2629 sub git_gather_all_ctags {
2630 my $projects = shift;
2631 my $ctags = {};
2632
2633 foreach my $p (@$projects) {
2634 foreach my $ct (keys %{$p->{'ctags'}}) {
2635 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2636 }
2637 }
2638
2639 return $ctags;
2640 }
2641
2642 sub git_populate_project_tagcloud {
2643 my $ctags = shift;
2644
2645 # First, merge different-cased tags; tags vote on casing
2646 my %ctags_lc;
2647 foreach (keys %$ctags) {
2648 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2649 if (not $ctags_lc{lc $_}->{topcount}
2650 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2651 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2652 $ctags_lc{lc $_}->{topname} = $_;
2653 }
2654 }
2655
2656 my $cloud;
2657 if (eval { require HTML::TagCloud; 1; }) {
2658 $cloud = HTML::TagCloud->new;
2659 foreach my $ctag (sort keys %ctags_lc) {
2660 # Pad the title with spaces so that the cloud looks
2661 # less crammed.
2662 my $title = esc_html($ctags_lc{$ctag}->{topname});
2663 $title =~ s/ /&nbsp;/g;
2664 $title =~ s/^/&nbsp;/g;
2665 $title =~ s/$/&nbsp;/g;
2666 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2667 $ctags_lc{$ctag}->{count});
2668 }
2669 } else {
2670 $cloud = {};
2671 foreach my $ctag (keys %ctags_lc) {
2672 my $title = $ctags_lc{$ctag}->{topname};
2673 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
2674 $cloud->{$ctag}{ctag} =
2675 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)},
2676 esc_html($title, -nbsp=>1));
2677 }
2678 }
2679 return $cloud;
2680 }
2681
2682 sub git_show_project_tagcloud {
2683 my ($cloud, $count) = @_;
2684 if (ref $cloud eq 'HTML::TagCloud') {
2685 return $cloud->html_and_css($count);
2686 } else {
2687 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
2688 return
2689 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
2690 join (', ', map {
2691 $cloud->{$_}->{'ctag'}
2692 } splice(@tags, 0, $count)) .
2693 '</div>';
2694 }
2695 }
2696
2697 sub git_get_project_url_list {
2698 my $path = shift;
2699
2700 $git_dir = "$projectroot/$path";
2701 open my $fd, '<', "$git_dir/cloneurl"
2702 or return wantarray ?
2703 @{ config_to_multi(git_get_project_config('url')) } :
2704 config_to_multi(git_get_project_config('url'));
2705 my @git_project_url_list = map { chomp; $_ } <$fd>;
2706 close $fd;
2707
2708 return wantarray ? @git_project_url_list : \@git_project_url_list;
2709 }
2710
2711 sub git_get_projects_list {
2712 my ($filter) = @_;
2713 my @list;
2714
2715 $filter ||= '';
2716 $filter =~ s/\.git$//;
2717
2718 my $check_forks = gitweb_check_feature('forks');
2719
2720 if (-d $projects_list) {
2721 # search in directory
2722 my $dir = $projects_list . ($filter ? "/$filter" : '');
2723 # remove the trailing "/"
2724 $dir =~ s!/+$!!;
2725 my $pfxlen = length("$dir");
2726 my $pfxdepth = ($dir =~ tr!/!!);
2727
2728 File::Find::find({
2729 follow_fast => 1, # follow symbolic links
2730 follow_skip => 2, # ignore duplicates
2731 dangling_symlinks => 0, # ignore dangling symlinks, silently
2732 wanted => sub {
2733 # global variables
2734 our $project_maxdepth;
2735 our $projectroot;
2736 # skip project-list toplevel, if we get it.
2737 return if (m!^[/.]$!);
2738 # only directories can be git repositories
2739 return unless (-d $_);
2740 # don't traverse too deep (Find is super slow on os x)
2741 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2742 $File::Find::prune = 1;
2743 return;
2744 }
2745
2746 my $subdir = substr($File::Find::name, $pfxlen + 1);
2747 # we check related file in $projectroot
2748 my $path = ($filter ? "$filter/" : '') . $subdir;
2749 if (check_export_ok("$projectroot/$path")) {
2750 push @list, { path => $path };
2751 $File::Find::prune = 1;
2752 }
2753 },
2754 }, "$dir");
2755
2756 } elsif (-f $projects_list) {
2757 # read from file(url-encoded):
2758 # 'git%2Fgit.git Linus+Torvalds'
2759 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2760 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2761 my %paths;
2762 open my $fd, '<', $projects_list or return;
2763 PROJECT:
2764 while (my $line = <$fd>) {
2765 chomp $line;
2766 my ($path, $owner) = split ' ', $line;
2767 $path = unescape($path);
2768 $owner = unescape($owner);
2769 if (!defined $path) {
2770 next;
2771 }
2772 if ($filter ne '') {
2773 # looking for forks;
2774 my $pfx = substr($path, 0, length($filter));
2775 if ($pfx ne $filter) {
2776 next PROJECT;
2777 }
2778 my $sfx = substr($path, length($filter));
2779 if ($sfx !~ /^\/.*\.git$/) {
2780 next PROJECT;
2781 }
2782 } elsif ($check_forks) {
2783 PATH:
2784 foreach my $filter (keys %paths) {
2785 # looking for forks;
2786 my $pfx = substr($path, 0, length($filter));
2787 if ($pfx ne $filter) {
2788 next PATH;
2789 }
2790 my $sfx = substr($path, length($filter));
2791 if ($sfx !~ /^\/.*\.git$/) {
2792 next PATH;
2793 }
2794 # is a fork, don't include it in
2795 # the list
2796 next PROJECT;
2797 }
2798 }
2799 if (check_export_ok("$projectroot/$path")) {
2800 my $pr = {
2801 path => $path,
2802 owner => to_utf8($owner),
2803 };
2804 push @list, $pr;
2805 (my $forks_path = $path) =~ s/\.git$//;
2806 $paths{$forks_path}++;
2807 }
2808 }
2809 close $fd;
2810 }
2811 return @list;
2812 }
2813
2814 our $gitweb_project_owner = undef;
2815 sub git_get_project_list_from_file {
2816
2817 return if (defined $gitweb_project_owner);
2818
2819 $gitweb_project_owner = {};
2820 # read from file (url-encoded):
2821 # 'git%2Fgit.git Linus+Torvalds'
2822 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2823 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2824 if (-f $projects_list) {
2825 open(my $fd, '<', $projects_list);
2826 while (my $line = <$fd>) {
2827 chomp $line;
2828 my ($pr, $ow) = split ' ', $line;
2829 $pr = unescape($pr);
2830 $ow = unescape($ow);
2831 $gitweb_project_owner->{$pr} = to_utf8($ow);
2832 }
2833 close $fd;
2834 }
2835 }
2836
2837 sub git_get_project_owner {
2838 my $project = shift;
2839 my $owner;
2840
2841 return undef unless $project;
2842 $git_dir = "$projectroot/$project";
2843
2844 if (!defined $gitweb_project_owner) {
2845 git_get_project_list_from_file();
2846 }
2847
2848 if (exists $gitweb_project_owner->{$project}) {
2849 $owner = $gitweb_project_owner->{$project};
2850 }
2851 if (!defined $owner){
2852 $owner = git_get_project_config('owner');
2853 }
2854 if (!defined $owner) {
2855 $owner = get_file_owner("$git_dir");
2856 }
2857
2858 return $owner;
2859 }
2860
2861 sub git_get_last_activity {
2862 my ($path) = @_;
2863 my $fd;
2864
2865 $git_dir = "$projectroot/$path";
2866 open($fd, "-|", git_cmd(), 'for-each-ref',
2867 '--format=%(committer)',
2868 '--sort=-committerdate',
2869 '--count=1',
2870 'refs/heads') or return;
2871 my $most_recent = <$fd>;
2872 close $fd or return;
2873 if (defined $most_recent &&
2874 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2875 my $timestamp = $1;
2876 my $age = time - $timestamp;
2877 return ($age, age_string($age));
2878 }
2879 return (undef, undef);
2880 }
2881
2882 # Implementation note: when a single remote is wanted, we cannot use 'git
2883 # remote show -n' because that command always work (assuming it's a remote URL
2884 # if it's not defined), and we cannot use 'git remote show' because that would
2885 # try to make a network roundtrip. So the only way to find if that particular
2886 # remote is defined is to walk the list provided by 'git remote -v' and stop if
2887 # and when we find what we want.
2888 sub git_get_remotes_list {
2889 my $wanted = shift;
2890 my %remotes = ();
2891
2892 open my $fd, '-|' , git_cmd(), 'remote', '-v';
2893 return unless $fd;
2894 while (my $remote = <$fd>) {
2895 chomp $remote;
2896 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
2897 next if $wanted and not $remote eq $wanted;
2898 my ($url, $key) = ($1, $2);
2899
2900 $remotes{$remote} ||= { 'heads' => () };
2901 $remotes{$remote}{$key} = $url;
2902 }
2903 close $fd or return;
2904 return wantarray ? %remotes : \%remotes;
2905 }
2906
2907 # Takes a hash of remotes as first parameter and fills it by adding the
2908 # available remote heads for each of the indicated remotes.
2909 sub fill_remote_heads {
2910 my $remotes = shift;
2911 my @heads = map { "remotes/$_" } keys %$remotes;
2912 my @remoteheads = git_get_heads_list(undef, @heads);
2913 foreach my $remote (keys %$remotes) {
2914 $remotes->{$remote}{'heads'} = [ grep {
2915 $_->{'name'} =~ s!^$remote/!!
2916 } @remoteheads ];
2917 }
2918 }
2919
2920 sub git_get_references {
2921 my $type = shift || "";
2922 my %refs;
2923 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2924 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2925 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2926 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2927 or return;
2928
2929 while (my $line = <$fd>) {
2930 chomp $line;
2931 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2932 if (defined $refs{$1}) {
2933 push @{$refs{$1}}, $2;
2934 } else {
2935 $refs{$1} = [ $2 ];
2936 }
2937 }
2938 }
2939 close $fd or return;
2940 return \%refs;
2941 }
2942
2943 sub git_get_rev_name_tags {
2944 my $hash = shift || return undef;
2945
2946 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2947 or return;
2948 my $name_rev = <$fd>;
2949 close $fd;
2950
2951 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2952 return $1;
2953 } else {
2954 # catches also '$hash undefined' output
2955 return undef;
2956 }
2957 }
2958
2959 ## ----------------------------------------------------------------------
2960 ## parse to hash functions
2961
2962 sub parse_date {
2963 my $epoch = shift;
2964 my $tz = shift || "-0000";
2965
2966 my %date;
2967 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2968 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2969 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2970 $date{'hour'} = $hour;
2971 $date{'minute'} = $min;
2972 $date{'mday'} = $mday;
2973 $date{'day'} = $days[$wday];
2974 $date{'month'} = $months[$mon];
2975 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2976 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2977 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2978 $mday, $months[$mon], $hour ,$min;
2979 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2980 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2981
2982 my ($tz_sign, $tz_hour, $tz_min) =
2983 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
2984 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
2985 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
2986 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2987 $date{'hour_local'} = $hour;
2988 $date{'minute_local'} = $min;
2989 $date{'tz_local'} = $tz;
2990 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2991 1900+$year, $mon+1, $mday,
2992 $hour, $min, $sec, $tz);
2993 return %date;
2994 }
2995
2996 sub parse_tag {
2997 my $tag_id = shift;
2998 my %tag;
2999 my @comment;
3000
3001 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3002 $tag{'id'} = $tag_id;
3003 while (my $line = <$fd>) {
3004 chomp $line;
3005 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3006 $tag{'object'} = $1;
3007 } elsif ($line =~ m/^type (.+)$/) {
3008 $tag{'type'} = $1;
3009 } elsif ($line =~ m/^tag (.+)$/) {
3010 $tag{'name'} = $1;
3011 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3012 $tag{'author'} = $1;
3013 $tag{'author_epoch'} = $2;
3014 $tag{'author_tz'} = $3;
3015 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3016 $tag{'author_name'} = $1;
3017 $tag{'author_email'} = $2;
3018 } else {
3019 $tag{'author_name'} = $tag{'author'};
3020 }
3021 } elsif ($line =~ m/--BEGIN/) {
3022 push @comment, $line;
3023 last;
3024 } elsif ($line eq "") {
3025 last;
3026 }
3027 }
3028 push @comment, <$fd>;
3029 $tag{'comment'} = \@comment;
3030 close $fd or return;
3031 if (!defined $tag{'name'}) {
3032 return
3033 };
3034 return %tag
3035 }
3036
3037 sub parse_commit_text {
3038 my ($commit_text, $withparents) = @_;
3039 my @commit_lines = split '\n', $commit_text;
3040 my %co;
3041
3042 pop @commit_lines; # Remove '\0'
3043
3044 if (! @commit_lines) {
3045 return;
3046 }
3047
3048 my $header = shift @commit_lines;
3049 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3050 return;
3051 }
3052 ($co{'id'}, my @parents) = split ' ', $header;
3053 while (my $line = shift @commit_lines) {
3054 last if $line eq "\n";
3055 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3056 $co{'tree'} = $1;
3057 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3058 push @parents, $1;
3059 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3060 $co{'author'} = to_utf8($1);
3061 $co{'author_epoch'} = $2;
3062 $co{'author_tz'} = $3;
3063 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3064 $co{'author_name'} = $1;
3065 $co{'author_email'} = $2;
3066 } else {
3067 $co{'author_name'} = $co{'author'};
3068 }
3069 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3070 $co{'committer'} = to_utf8($1);
3071 $co{'committer_epoch'} = $2;
3072 $co{'committer_tz'} = $3;
3073 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3074 $co{'committer_name'} = $1;
3075 $co{'committer_email'} = $2;
3076 } else {
3077 $co{'committer_name'} = $co{'committer'};
3078 }
3079 }
3080 }
3081 if (!defined $co{'tree'}) {
3082 return;
3083 };
3084 $co{'parents'} = \@parents;
3085 $co{'parent'} = $parents[0];
3086
3087 foreach my $title (@commit_lines) {
3088 $title =~ s/^ //;
3089 if ($title ne "") {
3090 $co{'title'} = chop_str($title, 80, 5);
3091 # remove leading stuff of merges to make the interesting part visible
3092 if (length($title) > 50) {
3093 $title =~ s/^Automatic //;
3094 $title =~ s/^merge (of|with) /Merge ... /i;
3095 if (length($title) > 50) {
3096 $title =~ s/(http|rsync):\/\///;
3097 }
3098 if (length($title) > 50) {
3099 $title =~ s/(master|www|rsync)\.//;
3100 }
3101 if (length($title) > 50) {
3102 $title =~ s/kernel.org:?//;
3103 }
3104 if (length($title) > 50) {
3105 $title =~ s/\/pub\/scm//;
3106 }
3107 }
3108 $co{'title_short'} = chop_str($title, 50, 5);
3109 last;
3110 }
3111 }
3112 if (! defined $co{'title'} || $co{'title'} eq "") {
3113 $co{'title'} = $co{'title_short'} = '(no commit message)';
3114 }
3115 # remove added spaces
3116 foreach my $line (@commit_lines) {
3117 $line =~ s/^ //;
3118 }
3119 $co{'comment'} = \@commit_lines;
3120
3121 my $age = time - $co{'committer_epoch'};
3122 $co{'age'} = $age;
3123 $co{'age_string'} = age_string($age);
3124 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3125 if ($age > 60*60*24*7*2) {
3126 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3127 $co{'age_string_age'} = $co{'age_string'};
3128 } else {
3129 $co{'age_string_date'} = $co{'age_string'};
3130 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3131 }
3132 return %co;
3133 }
3134
3135 sub parse_commit {
3136 my ($commit_id) = @_;
3137 my %co;
3138
3139 local $/ = "\0";
3140
3141 open my $fd, "-|", git_cmd(), "rev-list",
3142 "--parents",
3143 "--header",
3144 "--max-count=1",
3145 $commit_id,
3146 "--",
3147 or die_error(500, "Open git-rev-list failed");
3148 %co = parse_commit_text(<$fd>, 1);
3149 close $fd;
3150
3151 return %co;
3152 }
3153
3154 sub parse_commits {
3155 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3156 my @cos;
3157
3158 $maxcount ||= 1;
3159 $skip ||= 0;
3160
3161 local $/ = "\0";
3162
3163 open my $fd, "-|", git_cmd(), "rev-list",
3164 "--header",
3165 @args,
3166 ("--max-count=" . $maxcount),
3167 ("--skip=" . $skip),
3168 @extra_options,
3169 $commit_id,
3170 "--",
3171 ($filename ? ($filename) : ())
3172 or die_error(500, "Open git-rev-list failed");
3173 while (my $line = <$fd>) {
3174 my %co = parse_commit_text($line);
3175 push @cos, \%co;
3176 }
3177 close $fd;
3178
3179 return wantarray ? @cos : \@cos;
3180 }
3181
3182 # parse line of git-diff-tree "raw" output
3183 sub parse_difftree_raw_line {
3184 my $line = shift;
3185 my %res;
3186
3187 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3188 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3189 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3190 $res{'from_mode'} = $1;
3191 $res{'to_mode'} = $2;
3192 $res{'from_id'} = $3;
3193 $res{'to_id'} = $4;
3194 $res{'status'} = $5;
3195 $res{'similarity'} = $6;
3196 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3197 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3198 } else {
3199 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3200 }
3201 }
3202 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3203 # combined diff (for merge commit)
3204 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3205 $res{'nparents'} = length($1);
3206 $res{'from_mode'} = [ split(' ', $2) ];
3207 $res{'to_mode'} = pop @{$res{'from_mode'}};
3208 $res{'from_id'} = [ split(' ', $3) ];
3209 $res{'to_id'} = pop @{$res{'from_id'}};
3210 $res{'status'} = [ split('', $4) ];
3211 $res{'to_file'} = unquote($5);
3212 }
3213 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3214 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3215 $res{'commit'} = $1;
3216 }
3217
3218 return wantarray ? %res : \%res;
3219 }
3220
3221 # wrapper: return parsed line of git-diff-tree "raw" output
3222 # (the argument might be raw line, or parsed info)
3223 sub parsed_difftree_line {
3224 my $line_or_ref = shift;
3225
3226 if (ref($line_or_ref) eq "HASH") {
3227 # pre-parsed (or generated by hand)
3228 return $line_or_ref;
3229 } else {
3230 return parse_difftree_raw_line($line_or_ref);
3231 }
3232 }
3233
3234 # parse line of git-ls-tree output
3235 sub parse_ls_tree_line {
3236 my $line = shift;
3237 my %opts = @_;
3238 my %res;
3239
3240 if ($opts{'-l'}) {
3241 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3242 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3243
3244 $res{'mode'} = $1;
3245 $res{'type'} = $2;
3246 $res{'hash'} = $3;
3247 $res{'size'} = $4;
3248 if ($opts{'-z'}) {
3249 $res{'name'} = $5;
3250 } else {
3251 $res{'name'} = unquote($5);
3252 }
3253 } else {
3254 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3255 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3256
3257 $res{'mode'} = $1;
3258 $res{'type'} = $2;
3259 $res{'hash'} = $3;
3260 if ($opts{'-z'}) {
3261 $res{'name'} = $4;
3262 } else {
3263 $res{'name'} = unquote($4);
3264 }
3265 }
3266
3267 return wantarray ? %res : \%res;
3268 }
3269
3270 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3271 sub parse_from_to_diffinfo {
3272 my ($diffinfo, $from, $to, @parents) = @_;
3273
3274 if ($diffinfo->{'nparents'}) {
3275 # combined diff
3276 $from->{'file'} = [];
3277 $from->{'href'} = [];
3278 fill_from_file_info($diffinfo, @parents)
3279 unless exists $diffinfo->{'from_file'};
3280 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3281 $from->{'file'}[$i] =
3282 defined $diffinfo->{'from_file'}[$i] ?
3283 $diffinfo->{'from_file'}[$i] :
3284 $diffinfo->{'to_file'};
3285 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3286 $from->{'href'}[$i] = href(action=>"blob",
3287 hash_base=>$parents[$i],
3288 hash=>$diffinfo->{'from_id'}[$i],
3289 file_name=>$from->{'file'}[$i]);
3290 } else {
3291 $from->{'href'}[$i] = undef;
3292 }
3293 }
3294 } else {
3295 # ordinary (not combined) diff
3296 $from->{'file'} = $diffinfo->{'from_file'};
3297 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3298 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3299 hash=>$diffinfo->{'from_id'},
3300 file_name=>$from->{'file'});
3301 } else {
3302 delete $from->{'href'};
3303 }
3304 }
3305
3306 $to->{'file'} = $diffinfo->{'to_file'};
3307 if (!is_deleted($diffinfo)) { # file exists in result
3308 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3309 hash=>$diffinfo->{'to_id'},
3310 file_name=>$to->{'file'});
3311 } else {
3312 delete $to->{'href'};
3313 }
3314 }
3315
3316 ## ......................................................................
3317 ## parse to array of hashes functions
3318
3319 sub git_get_heads_list {
3320 my ($limit, @classes) = @_;
3321 @classes = ('heads') unless @classes;
3322 my @patterns = map { "refs/$_" } @classes;
3323 my @headslist;
3324
3325 open my $fd, '-|', git_cmd(), 'for-each-ref',
3326 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3327 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3328 @patterns
3329 or return;
3330 while (my $line = <$fd>) {
3331 my %ref_item;
3332
3333 chomp $line;
3334 my ($refinfo, $committerinfo) = split(/\0/, $line);
3335 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3336 my ($committer, $epoch, $tz) =
3337 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3338 $ref_item{'fullname'} = $name;
3339 $name =~ s!^refs/(?:head|remote)s/!!;
3340
3341 $ref_item{'name'} = $name;
3342 $ref_item{'id'} = $hash;
3343 $ref_item{'title'} = $title || '(no commit message)';
3344 $ref_item{'epoch'} = $epoch;
3345 if ($epoch) {
3346 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3347 } else {
3348 $ref_item{'age'} = "unknown";
3349 }
3350
3351 push @headslist, \%ref_item;
3352 }
3353 close $fd;
3354
3355 return wantarray ? @headslist : \@headslist;
3356 }
3357
3358 sub git_get_tags_list {
3359 my $limit = shift;
3360 my @tagslist;
3361
3362 open my $fd, '-|', git_cmd(), 'for-each-ref',
3363 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3364 '--format=%(objectname) %(objecttype) %(refname) '.
3365 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3366 'refs/tags'
3367 or return;
3368 while (my $line = <$fd>) {
3369 my %ref_item;
3370
3371 chomp $line;
3372 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3373 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3374 my ($creator, $epoch, $tz) =
3375 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3376 $ref_item{'fullname'} = $name;
3377 $name =~ s!^refs/tags/!!;
3378
3379 $ref_item{'type'} = $type;
3380 $ref_item{'id'} = $id;
3381 $ref_item{'name'} = $name;
3382 if ($type eq "tag") {
3383 $ref_item{'subject'} = $title;
3384 $ref_item{'reftype'} = $reftype;
3385 $ref_item{'refid'} = $refid;
3386 } else {
3387 $ref_item{'reftype'} = $type;
3388 $ref_item{'refid'} = $id;
3389 }
3390
3391 if ($type eq "tag" || $type eq "commit") {
3392 $ref_item{'epoch'} = $epoch;
3393 if ($epoch) {
3394 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3395 } else {
3396 $ref_item{'age'} = "unknown";
3397 }
3398 }
3399
3400 push @tagslist, \%ref_item;
3401 }
3402 close $fd;
3403
3404 return wantarray ? @tagslist : \@tagslist;
3405 }
3406
3407 ## ----------------------------------------------------------------------
3408 ## filesystem-related functions
3409
3410 sub get_file_owner {
3411 my $path = shift;
3412
3413 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3414 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3415 if (!defined $gcos) {
3416 return undef;
3417 }
3418 my $owner = $gcos;
3419 $owner =~ s/[,;].*$//;
3420 return to_utf8($owner);
3421 }
3422
3423 # assume that file exists
3424 sub insert_file {
3425 my $filename = shift;
3426
3427 open my $fd, '<', $filename;
3428 print map { to_utf8($_) } <$fd>;
3429 close $fd;
3430 }
3431
3432 ## ......................................................................
3433 ## mimetype related functions
3434
3435 sub mimetype_guess_file {
3436 my $filename = shift;
3437 my $mimemap = shift;
3438 -r $mimemap or return undef;
3439
3440 my %mimemap;
3441 open(my $mh, '<', $mimemap) or return undef;
3442 while (<$mh>) {
3443 next if m/^#/; # skip comments
3444 my ($mimetype, $exts) = split(/\t+/);
3445 if (defined $exts) {
3446 my @exts = split(/\s+/, $exts);
3447 foreach my $ext (@exts) {
3448 $mimemap{$ext} = $mimetype;
3449 }
3450 }
3451 }
3452 close($mh);
3453
3454 $filename =~ /\.([^.]*)$/;
3455 return $mimemap{$1};
3456 }
3457
3458 sub mimetype_guess {
3459 my $filename = shift;
3460 my $mime;
3461 $filename =~ /\./ or return undef;
3462
3463 if ($mimetypes_file) {
3464 my $file = $mimetypes_file;
3465 if ($file !~ m!^/!) { # if it is relative path
3466 # it is relative to project
3467 $file = "$projectroot/$project/$file";
3468 }
3469 $mime = mimetype_guess_file($filename, $file);
3470 }
3471 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3472 return $mime;
3473 }
3474
3475 sub blob_mimetype {
3476 my $fd = shift;
3477 my $filename = shift;
3478
3479 if ($filename) {
3480 my $mime = mimetype_guess($filename);
3481 $mime and return $mime;
3482 }
3483
3484 # just in case
3485 return $default_blob_plain_mimetype unless $fd;
3486
3487 if (-T $fd) {
3488 return 'text/plain';
3489 } elsif (! $filename) {
3490 return 'application/octet-stream';
3491 } elsif ($filename =~ m/\.png$/i) {
3492 return 'image/png';
3493 } elsif ($filename =~ m/\.gif$/i) {
3494 return 'image/gif';
3495 } elsif ($filename =~ m/\.jpe?g$/i) {
3496 return 'image/jpeg';
3497 } else {
3498 return 'application/octet-stream';
3499 }
3500 }
3501
3502 sub blob_contenttype {
3503 my ($fd, $file_name, $type) = @_;
3504
3505 $type ||= blob_mimetype($fd, $file_name);
3506 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3507 $type .= "; charset=$default_text_plain_charset";
3508 }
3509
3510 return $type;
3511 }
3512
3513 # guess file syntax for syntax highlighting; return undef if no highlighting
3514 # the name of syntax can (in the future) depend on syntax highlighter used
3515 sub guess_file_syntax {
3516 my ($highlight, $mimetype, $file_name) = @_;
3517 return undef unless ($highlight && defined $file_name);
3518 my $basename = basename($file_name, '.in');
3519 return $highlight_basename{$basename}
3520 if exists $highlight_basename{$basename};
3521
3522 $basename =~ /\.([^.]*)$/;
3523 my $ext = $1 or return undef;
3524 return $highlight_ext{$ext}
3525 if exists $highlight_ext{$ext};
3526
3527 return undef;
3528 }
3529
3530 # run highlighter and return FD of its output,
3531 # or return original FD if no highlighting
3532 sub run_highlighter {
3533 my ($fd, $highlight, $syntax) = @_;
3534 return $fd unless ($highlight && defined $syntax);
3535
3536 close $fd;
3537 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3538 quote_command($highlight_bin).
3539 " --replace-tabs=8 --fragment --syntax $syntax |"
3540 or die_error(500, "Couldn't open file or run syntax highlighter");
3541 return $fd;
3542 }
3543
3544 ## ======================================================================
3545 ## functions printing HTML: header, footer, error page
3546
3547 sub get_page_title {
3548 my $title = to_utf8($site_name);
3549
3550 return $title unless (defined $project);
3551 $title .= " - " . to_utf8($project);
3552
3553 return $title unless (defined $action);
3554 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3555
3556 return $title unless (defined $file_name);
3557 $title .= " - " . esc_path($file_name);
3558 if ($action eq "tree" && $file_name !~ m|/$|) {
3559 $title .= "/";
3560 }
3561
3562 return $title;
3563 }
3564
3565 sub print_feed_meta {
3566 if (defined $project) {
3567 my %href_params = get_feed_info();
3568 if (!exists $href_params{'-title'}) {
3569 $href_params{'-title'} = 'log';
3570 }
3571
3572 foreach my $format (qw(RSS Atom)) {
3573 my $type = lc($format);
3574 my %link_attr = (
3575 '-rel' => 'alternate',
3576 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3577 '-type' => "application/$type+xml"
3578 );
3579
3580 $href_params{'action'} = $type;
3581 $link_attr{'-href'} = href(%href_params);
3582 print "<link ".
3583 "rel=\"$link_attr{'-rel'}\" ".
3584 "title=\"$link_attr{'-title'}\" ".
3585 "href=\"$link_attr{'-href'}\" ".
3586 "type=\"$link_attr{'-type'}\" ".
3587 "/>\n";
3588
3589 $href_params{'extra_options'} = '--no-merges';
3590 $link_attr{'-href'} = href(%href_params);
3591 $link_attr{'-title'} .= ' (no merges)';
3592 print "<link ".
3593 "rel=\"$link_attr{'-rel'}\" ".
3594 "title=\"$link_attr{'-title'}\" ".
3595 "href=\"$link_attr{'-href'}\" ".
3596 "type=\"$link_attr{'-type'}\" ".
3597 "/>\n";
3598 }
3599
3600 } else {
3601 printf('<link rel="alternate" title="%s projects list" '.
3602 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3603 esc_attr($site_name), href(project=>undef, action=>"project_index"));
3604 printf('<link rel="alternate" title="%s projects feeds" '.
3605 'href="%s" type="text/x-opml" />'."\n",
3606 esc_attr($site_name), href(project=>undef, action=>"opml"));
3607 }
3608 }
3609
3610 sub git_header_html {
3611 my $status = shift || "200 OK";
3612 my $expires = shift;
3613 my %opts = @_;
3614
3615 my $title = get_page_title();
3616 my $content_type;
3617 # require explicit support from the UA if we are to send the page as
3618 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3619 # we have to do this because MSIE sometimes globs '*/*', pretending to
3620 # support xhtml+xml but choking when it gets what it asked for.
3621 if (defined $cgi->http('HTTP_ACCEPT') &&
3622 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3623 $cgi->Accept('application/xhtml+xml') != 0) {
3624 $content_type = 'application/xhtml+xml';
3625 } else {
3626 $content_type = 'text/html';
3627 }
3628 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3629 -status=> $status, -expires => $expires)
3630 unless ($opts{'-no_http_header'});
3631 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3632 print <<EOF;
3633 <?xml version="1.0" encoding="utf-8"?>
3634 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3635 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3636 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3637 <!-- git core binaries version $git_version -->
3638 <head>
3639 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3640 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3641 <meta name="robots" content="index, nofollow"/>
3642 <title>$title</title>
3643 EOF
3644 # the stylesheet, favicon etc urls won't work correctly with path_info
3645 # unless we set the appropriate base URL
3646 if ($ENV{'PATH_INFO'}) {
3647 print "<base href=\"".esc_url($base_url)."\" />\n";
3648 }
3649 # print out each stylesheet that exist, providing backwards capability
3650 # for those people who defined $stylesheet in a config file
3651 if (defined $stylesheet) {
3652 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3653 } else {
3654 foreach my $stylesheet (@stylesheets) {
3655 next unless $stylesheet;
3656 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3657 }
3658 }
3659 print_feed_meta()
3660 if ($status eq '200 OK');
3661 if (defined $favicon) {
3662 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
3663 }
3664
3665 print "</head>\n" .
3666 "<body>\n";
3667
3668 if (defined $site_header && -f $site_header) {
3669 insert_file($site_header);
3670 }
3671
3672 print "<div class=\"page_header\">\n";
3673 if (defined $logo) {
3674 print $cgi->a({-href => esc_url($logo_url),
3675 -title => $logo_label},
3676 $cgi->img({-src => esc_url($logo),
3677 -width => 72, -height => 27,
3678 -alt => "git",
3679 -class => "logo"}));
3680 }
3681 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3682 if (defined $project) {
3683 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3684 if (defined $action) {
3685 my $action_print = $action ;
3686 if (defined $opts{-action_extra}) {
3687 $action_print = $cgi->a({-href => href(action=>$action)},
3688 $action);
3689 }
3690 print " / $action_print";
3691 }
3692 if (defined $opts{-action_extra}) {
3693 print " / $opts{-action_extra}";
3694 }
3695 print "\n";
3696 }
3697 print "</div>\n";
3698
3699 my $have_search = gitweb_check_feature('search');
3700 if (defined $project && $have_search) {
3701 if (!defined $searchtext) {
3702 $searchtext = "";
3703 }
3704 my $search_hash;
3705 if (defined $hash_base) {
3706 $search_hash = $hash_base;
3707 } elsif (defined $hash) {
3708 $search_hash = $hash;
3709 } else {
3710 $search_hash = "HEAD";
3711 }
3712 my $action = $my_uri;
3713 my $use_pathinfo = gitweb_check_feature('pathinfo');
3714 if ($use_pathinfo) {
3715 $action .= "/".esc_url($project);
3716 }
3717 print $cgi->startform(-method => "get", -action => $action) .
3718 "<div class=\"search\">\n" .
3719 (!$use_pathinfo &&
3720 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3721 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3722 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3723 $cgi->popup_menu(-name => 'st', -default => 'commit',
3724 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3725 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3726 " search:\n",
3727 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3728 "<span title=\"Extended regular expression\">" .
3729 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3730 -checked => $search_use_regexp) .
3731 "</span>" .
3732 "</div>" .
3733 $cgi->end_form() . "\n";
3734 }
3735 }
3736
3737 sub git_footer_html {
3738 my $feed_class = 'rss_logo';
3739
3740 print "<div class=\"page_footer\">\n";
3741 if (defined $project) {
3742 my $descr = git_get_project_description($project);
3743 if (defined $descr) {
3744 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3745 }
3746
3747 my %href_params = get_feed_info();
3748 if (!%href_params) {
3749 $feed_class .= ' generic';
3750 }
3751 $href_params{'-title'} ||= 'log';
3752
3753 foreach my $format (qw(RSS Atom)) {
3754 $href_params{'action'} = lc($format);
3755 print $cgi->a({-href => href(%href_params),
3756 -title => "$href_params{'-title'} $format feed",
3757 -class => $feed_class}, $format)."\n";
3758 }
3759
3760 } else {
3761 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3762 -class => $feed_class}, "OPML") . " ";
3763 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3764 -class => $feed_class}, "TXT") . "\n";
3765 }
3766 print "</div>\n"; # class="page_footer"
3767
3768 if (defined $t0 && gitweb_check_feature('timed')) {
3769 print "<div id=\"generating_info\">\n";
3770 print 'This page took '.
3771 '<span id="generating_time" class="time_span">'.
3772 tv_interval($t0, [ gettimeofday() ]).
3773 ' seconds </span>'.
3774 ' and '.
3775 '<span id="generating_cmd">'.
3776 $number_of_git_cmds.
3777 '</span> git commands '.
3778 " to generate.\n";
3779 print "</div>\n"; # class="page_footer"
3780 }
3781
3782 if (defined $site_footer && -f $site_footer) {
3783 insert_file($site_footer);
3784 }
3785
3786 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
3787 if (defined $action &&
3788 $action eq 'blame_incremental') {
3789 print qq!<script type="text/javascript">\n!.
3790 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3791 qq! "!. href() .qq!");\n!.
3792 qq!</script>\n!;
3793 } elsif (gitweb_check_feature('javascript-actions')) {
3794 print qq!<script type="text/javascript">\n!.
3795 qq!window.onload = fixLinks;\n!.
3796 qq!</script>\n!;
3797 }
3798
3799 print "</body>\n" .
3800 "</html>";
3801 }
3802
3803 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3804 # Example: die_error(404, 'Hash not found')
3805 # By convention, use the following status codes (as defined in RFC 2616):
3806 # 400: Invalid or missing CGI parameters, or
3807 # requested object exists but has wrong type.
3808 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3809 # this server or project.
3810 # 404: Requested object/revision/project doesn't exist.
3811 # 500: The server isn't configured properly, or
3812 # an internal error occurred (e.g. failed assertions caused by bugs), or
3813 # an unknown error occurred (e.g. the git binary died unexpectedly).
3814 # 503: The server is currently unavailable (because it is overloaded,
3815 # or down for maintenance). Generally, this is a temporary state.
3816 sub die_error {
3817 my $status = shift || 500;
3818 my $error = esc_html(shift) || "Internal Server Error";
3819 my $extra = shift;
3820 my %opts = @_;
3821
3822 my %http_responses = (
3823 400 => '400 Bad Request',
3824 403 => '403 Forbidden',
3825 404 => '404 Not Found',
3826 500 => '500 Internal Server Error',
3827 503 => '503 Service Unavailable',
3828 );
3829 git_header_html($http_responses{$status}, undef, %opts);
3830 print <<EOF;
3831 <div class="page_body">
3832 <br /><br />
3833 $status - $error
3834 <br />
3835 EOF
3836 if (defined $extra) {
3837 print "<hr />\n" .
3838 "$extra\n";
3839 }
3840 print "</div>\n";
3841
3842 git_footer_html();
3843 goto DONE_GITWEB
3844 unless ($opts{'-error_handler'});
3845 }
3846
3847 ## ----------------------------------------------------------------------
3848 ## functions printing or outputting HTML: navigation
3849
3850 sub git_print_page_nav {
3851 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3852 $extra = '' if !defined $extra; # pager or formats
3853
3854 my @navs = qw(summary shortlog log commit commitdiff tree);
3855 if ($suppress) {
3856 @navs = grep { $_ ne $suppress } @navs;
3857 }
3858
3859 my %arg = map { $_ => {action=>$_} } @navs;
3860 if (defined $head) {
3861 for (qw(commit commitdiff)) {
3862 $arg{$_}{'hash'} = $head;
3863 }
3864 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3865 for (qw(shortlog log)) {
3866 $arg{$_}{'hash'} = $head;
3867 }
3868 }
3869 }
3870
3871 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3872 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3873
3874 my @actions = gitweb_get_feature('actions');
3875 my %repl = (
3876 '%' => '%',
3877 'n' => $project, # project name
3878 'f' => $git_dir, # project path within filesystem
3879 'h' => $treehead || '', # current hash ('h' parameter)
3880 'b' => $treebase || '', # hash base ('hb' parameter)
3881 );
3882 while (@actions) {
3883 my ($label, $link, $pos) = splice(@actions,0,3);
3884 # insert
3885 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3886 # munch munch
3887 $link =~ s/%([%nfhb])/$repl{$1}/g;
3888 $arg{$label}{'_href'} = $link;
3889 }
3890
3891 print "<div class=\"page_nav\">\n" .
3892 (join " | ",
3893 map { $_ eq $current ?
3894 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3895 } @navs);
3896 print "<br/>\n$extra<br/>\n" .
3897 "</div>\n";
3898 }
3899
3900 # returns a submenu for the nagivation of the refs views (tags, heads,
3901 # remotes) with the current view disabled and the remotes view only
3902 # available if the feature is enabled
3903 sub format_ref_views {
3904 my ($current) = @_;
3905 my @ref_views = qw{tags heads};
3906 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
3907 return join " | ", map {
3908 $_ eq $current ? $_ :
3909 $cgi->a({-href => href(action=>$_)}, $_)
3910 } @ref_views
3911 }
3912
3913 sub format_paging_nav {
3914 my ($action, $page, $has_next_link) = @_;
3915 my $paging_nav;
3916
3917
3918 if ($page > 0) {
3919 $paging_nav .=
3920 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3921 " &sdot; " .
3922 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3923 -accesskey => "p", -title => "Alt-p"}, "prev");
3924 } else {
3925 $paging_nav .= "first &sdot; prev";
3926 }
3927
3928 if ($has_next_link) {
3929 $paging_nav .= " &sdot; " .
3930 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3931 -accesskey => "n", -title => "Alt-n"}, "next");
3932 } else {
3933 $paging_nav .= " &sdot; next";
3934 }
3935
3936 return $paging_nav;
3937 }
3938
3939 ## ......................................................................
3940 ## functions printing or outputting HTML: div
3941
3942 sub git_print_header_div {
3943 my ($action, $title, $hash, $hash_base) = @_;
3944 my %args = ();
3945
3946 $args{'action'} = $action;
3947 $args{'hash'} = $hash if $hash;
3948 $args{'hash_base'} = $hash_base if $hash_base;
3949
3950 print "<div class=\"header\">\n" .
3951 $cgi->a({-href => href(%args), -class => "title"},
3952 $title ? $title : $action) .
3953 "\n</div>\n";
3954 }
3955
3956 sub format_repo_url {
3957 my ($name, $url) = @_;
3958 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
3959 }
3960
3961 # Group output by placing it in a DIV element and adding a header.
3962 # Options for start_div() can be provided by passing a hash reference as the
3963 # first parameter to the function.
3964 # Options to git_print_header_div() can be provided by passing an array
3965 # reference. This must follow the options to start_div if they are present.
3966 # The content can be a scalar, which is output as-is, a scalar reference, which
3967 # is output after html escaping, an IO handle passed either as *handle or
3968 # *handle{IO}, or a function reference. In the latter case all following
3969 # parameters will be taken as argument to the content function call.
3970 sub git_print_section {
3971 my ($div_args, $header_args, $content);
3972 my $arg = shift;
3973 if (ref($arg) eq 'HASH') {
3974 $div_args = $arg;
3975 $arg = shift;
3976 }
3977 if (ref($arg) eq 'ARRAY') {
3978 $header_args = $arg;
3979 $arg = shift;
3980 }
3981 $content = $arg;
3982
3983 print $cgi->start_div($div_args);
3984 git_print_header_div(@$header_args);
3985
3986 if (ref($content) eq 'CODE') {
3987 $content->(@_);
3988 } elsif (ref($content) eq 'SCALAR') {
3989 print esc_html($$content);
3990 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
3991 print <$content>;
3992 } elsif (!ref($content) && defined($content)) {
3993 print $content;
3994 }
3995
3996 print $cgi->end_div;
3997 }
3998
3999 sub print_local_time {
4000 print format_local_time(@_);
4001 }
4002
4003 sub format_local_time {
4004 my $localtime = '';
4005 my %date = @_;
4006 if ($date{'hour_local'} < 6) {
4007 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4008 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4009 } else {
4010 $localtime .= sprintf(" (%02d:%02d %s)",
4011 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4012 }
4013
4014 return $localtime;
4015 }
4016
4017 # Outputs the author name and date in long form
4018 sub git_print_authorship {
4019 my $co = shift;
4020 my %opts = @_;
4021 my $tag = $opts{-tag} || 'div';
4022 my $author = $co->{'author_name'};
4023
4024 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4025 print "<$tag class=\"author_date\">" .
4026 format_search_author($author, "author", esc_html($author)) .
4027 " [$ad{'rfc2822'}";
4028 print_local_time(%ad) if ($opts{-localtime});
4029 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
4030 . "</$tag>\n";
4031 }
4032
4033 # Outputs table rows containing the full author or committer information,
4034 # in the format expected for 'commit' view (& similar).
4035 # Parameters are a commit hash reference, followed by the list of people
4036 # to output information for. If the list is empty it defaults to both
4037 # author and committer.
4038 sub git_print_authorship_rows {
4039 my $co = shift;
4040 # too bad we can't use @people = @_ || ('author', 'committer')
4041 my @people = @_;
4042 @people = ('author', 'committer') unless @people;
4043 foreach my $who (@people) {
4044 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4045 print "<tr><td>$who</td><td>" .
4046 format_search_author($co->{"${who}_name"}, $who,
4047 esc_html($co->{"${who}_name"})) . " " .
4048 format_search_author($co->{"${who}_email"}, $who,
4049 esc_html("<" . $co->{"${who}_email"} . ">")) .
4050 "</td><td rowspan=\"2\">" .
4051 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4052 "</td></tr>\n" .
4053 "<tr>" .
4054 "<td></td><td> $wd{'rfc2822'}";
4055 print_local_time(%wd);
4056 print "</td>" .
4057 "</tr>\n";
4058 }
4059 }
4060
4061 sub git_print_page_path {
4062 my $name = shift;
4063 my $type = shift;
4064 my $hb = shift;
4065
4066
4067 print "<div class=\"page_path\">";
4068 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4069 -title => 'tree root'}, to_utf8("[$project]"));
4070 print " / ";
4071 if (defined $name) {
4072 my @dirname = split '/', $name;
4073 my $basename = pop @dirname;
4074 my $fullname = '';
4075
4076 foreach my $dir (@dirname) {
4077 $fullname .= ($fullname ? '/' : '') . $dir;
4078 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4079 hash_base=>$hb),
4080 -title => $fullname}, esc_path($dir));
4081 print " / ";
4082 }
4083 if (defined $type && $type eq 'blob') {
4084 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4085 hash_base=>$hb),
4086 -title => $name}, esc_path($basename));
4087 } elsif (defined $type && $type eq 'tree') {
4088 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4089 hash_base=>$hb),
4090 -title => $name}, esc_path($basename));
4091 print " / ";
4092 } else {
4093 print esc_path($basename);
4094 }
4095 }
4096 print "<br/></div>\n";
4097 }
4098
4099 sub git_print_log {
4100 my $log = shift;
4101 my %opts = @_;
4102
4103 if ($opts{'-remove_title'}) {
4104 # remove title, i.e. first line of log
4105 shift @$log;
4106 }
4107 # remove leading empty lines
4108 while (defined $log->[0] && $log->[0] eq "") {
4109 shift @$log;
4110 }
4111
4112 # print log
4113 my $signoff = 0;
4114 my $empty = 0;
4115 foreach my $line (@$log) {
4116 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4117 $signoff = 1;
4118 $empty = 0;
4119 if (! $opts{'-remove_signoff'}) {
4120 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4121 next;
4122 } else {
4123 # remove signoff lines
4124 next;
4125 }
4126 } else {
4127 $signoff = 0;
4128 }
4129
4130 # print only one empty line
4131 # do not print empty line after signoff
4132 if ($line eq "") {
4133 next if ($empty || $signoff);
4134 $empty = 1;
4135 } else {
4136 $empty = 0;
4137 }
4138
4139 print format_log_line_html($line) . "<br/>\n";
4140 }
4141
4142 if ($opts{'-final_empty_line'}) {
4143 # end with single empty line
4144 print "<br/>\n" unless $empty;
4145 }
4146 }
4147
4148 # return link target (what link points to)
4149 sub git_get_link_target {
4150 my $hash = shift;
4151 my $link_target;
4152
4153 # read link
4154 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4155 or return;
4156 {
4157 local $/ = undef;
4158 $link_target = <$fd>;
4159 }
4160 close $fd
4161 or return;
4162
4163 return $link_target;
4164 }
4165
4166 # given link target, and the directory (basedir) the link is in,
4167 # return target of link relative to top directory (top tree);
4168 # return undef if it is not possible (including absolute links).
4169 sub normalize_link_target {
4170 my ($link_target, $basedir) = @_;
4171
4172 # absolute symlinks (beginning with '/') cannot be normalized
4173 return if (substr($link_target, 0, 1) eq '/');
4174
4175 # normalize link target to path from top (root) tree (dir)
4176 my $path;
4177 if ($basedir) {
4178 $path = $basedir . '/' . $link_target;
4179 } else {
4180 # we are in top (root) tree (dir)
4181 $path = $link_target;
4182 }
4183
4184 # remove //, /./, and /../
4185 my @path_parts;
4186 foreach my $part (split('/', $path)) {
4187 # discard '.' and ''
4188 next if (!$part || $part eq '.');
4189 # handle '..'
4190 if ($part eq '..') {
4191 if (@path_parts) {
4192 pop @path_parts;
4193 } else {
4194 # link leads outside repository (outside top dir)
4195 return;
4196 }
4197 } else {
4198 push @path_parts, $part;
4199 }
4200 }
4201 $path = join('/', @path_parts);
4202
4203 return $path;
4204 }
4205
4206 # print tree entry (row of git_tree), but without encompassing <tr> element
4207 sub git_print_tree_entry {
4208 my ($t, $basedir, $hash_base, $have_blame) = @_;
4209
4210 my %base_key = ();
4211 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4212
4213 # The format of a table row is: mode list link. Where mode is
4214 # the mode of the entry, list is the name of the entry, an href,
4215 # and link is the action links of the entry.
4216
4217 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4218 if (exists $t->{'size'}) {
4219 print "<td class=\"size\">$t->{'size'}</td>\n";
4220 }
4221 if ($t->{'type'} eq "blob") {
4222 print "<td class=\"list\">" .
4223 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4224 file_name=>"$basedir$t->{'name'}", %base_key),
4225 -class => "list"}, esc_path($t->{'name'}));
4226 if (S_ISLNK(oct $t->{'mode'})) {
4227 my $link_target = git_get_link_target($t->{'hash'});
4228 if ($link_target) {
4229 my $norm_target = normalize_link_target($link_target, $basedir);
4230 if (defined $norm_target) {
4231 print " -> " .
4232 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4233 file_name=>$norm_target),
4234 -title => $norm_target}, esc_path($link_target));
4235 } else {
4236 print " -> " . esc_path($link_target);
4237 }
4238 }
4239 }
4240 print "</td>\n";
4241 print "<td class=\"link\">";
4242 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4243 file_name=>"$basedir$t->{'name'}", %base_key)},
4244 "blob");
4245 if ($have_blame) {
4246 print " | " .
4247 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4248 file_name=>"$basedir$t->{'name'}", %base_key)},
4249 "blame");
4250 }
4251 if (defined $hash_base) {
4252 print " | " .
4253 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4254 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4255 "history");
4256 }
4257 print " | " .
4258 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4259 file_name=>"$basedir$t->{'name'}")},
4260 "raw");
4261 print "</td>\n";
4262
4263 } elsif ($t->{'type'} eq "tree") {
4264 print "<td class=\"list\">";
4265 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4266 file_name=>"$basedir$t->{'name'}",
4267 %base_key)},
4268 esc_path($t->{'name'}));
4269 print "</td>\n";
4270 print "<td class=\"link\">";
4271 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4272 file_name=>"$basedir$t->{'name'}",
4273 %base_key)},
4274 "tree");
4275 if (defined $hash_base) {
4276 print " | " .
4277 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4278 file_name=>"$basedir$t->{'name'}")},
4279 "history");
4280 }
4281 print "</td>\n";
4282 } else {
4283 # unknown object: we can only present history for it
4284 # (this includes 'commit' object, i.e. submodule support)
4285 print "<td class=\"list\">" .
4286 esc_path($t->{'name'}) .
4287 "</td>\n";
4288 print "<td class=\"link\">";
4289 if (defined $hash_base) {
4290 print $cgi->a({-href => href(action=>"history",
4291 hash_base=>$hash_base,
4292 file_name=>"$basedir$t->{'name'}")},
4293 "history");
4294 }
4295 print "</td>\n";
4296 }
4297 }
4298
4299 ## ......................................................................
4300 ## functions printing large fragments of HTML
4301
4302 # get pre-image filenames for merge (combined) diff
4303 sub fill_from_file_info {
4304 my ($diff, @parents) = @_;
4305
4306 $diff->{'from_file'} = [ ];
4307 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4308 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4309 if ($diff->{'status'}[$i] eq 'R' ||
4310 $diff->{'status'}[$i] eq 'C') {
4311 $diff->{'from_file'}[$i] =
4312 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4313 }
4314 }
4315
4316 return $diff;
4317 }
4318
4319 # is current raw difftree line of file deletion
4320 sub is_deleted {
4321 my $diffinfo = shift;
4322
4323 return $diffinfo->{'to_id'} eq ('0' x 40);
4324 }
4325
4326 # does patch correspond to [previous] difftree raw line
4327 # $diffinfo - hashref of parsed raw diff format
4328 # $patchinfo - hashref of parsed patch diff format
4329 # (the same keys as in $diffinfo)
4330 sub is_patch_split {
4331 my ($diffinfo, $patchinfo) = @_;
4332
4333 return defined $diffinfo && defined $patchinfo
4334 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4335 }
4336
4337
4338 sub git_difftree_body {
4339 my ($difftree, $hash, @parents) = @_;
4340 my ($parent) = $parents[0];
4341 my $have_blame = gitweb_check_feature('blame');
4342 print "<div class=\"list_head\">\n";
4343 if ($#{$difftree} > 10) {
4344 print(($#{$difftree} + 1) . " files changed:\n");
4345 }
4346 print "</div>\n";
4347
4348 print "<table class=\"" .
4349 (@parents > 1 ? "combined " : "") .
4350 "diff_tree\">\n";
4351
4352 # header only for combined diff in 'commitdiff' view
4353 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4354 if ($has_header) {
4355 # table header
4356 print "<thead><tr>\n" .
4357 "<th></th><th></th>\n"; # filename, patchN link
4358 for (my $i = 0; $i < @parents; $i++) {
4359 my $par = $parents[$i];
4360 print "<th>" .
4361 $cgi->a({-href => href(action=>"commitdiff",
4362 hash=>$hash, hash_parent=>$par),
4363 -title => 'commitdiff to parent number ' .
4364 ($i+1) . ': ' . substr($par,0,7)},
4365 $i+1) .
4366 "&nbsp;</th>\n";
4367 }
4368 print "</tr></thead>\n<tbody>\n";
4369 }
4370
4371 my $alternate = 1;
4372 my $patchno = 0;
4373 foreach my $line (@{$difftree}) {
4374 my $diff = parsed_difftree_line($line);
4375
4376 if ($alternate) {
4377 print "<tr class=\"dark\">\n";
4378 } else {
4379 print "<tr class=\"light\">\n";
4380 }
4381 $alternate ^= 1;
4382
4383 if (exists $diff->{'nparents'}) { # combined diff
4384
4385 fill_from_file_info($diff, @parents)
4386 unless exists $diff->{'from_file'};
4387
4388 if (!is_deleted($diff)) {
4389 # file exists in the result (child) commit
4390 print "<td>" .
4391 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4392 file_name=>$diff->{'to_file'},
4393 hash_base=>$hash),
4394 -class => "list"}, esc_path($diff->{'to_file'})) .
4395 "</td>\n";
4396 } else {
4397 print "<td>" .
4398 esc_path($diff->{'to_file'}) .
4399 "</td>\n";
4400 }
4401
4402 if ($action eq 'commitdiff') {
4403 # link to patch
4404 $patchno++;
4405 print "<td class=\"link\">" .
4406 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4407 "patch") .
4408 " | " .
4409 "</td>\n";
4410 }
4411
4412 my $has_history = 0;
4413 my $not_deleted = 0;
4414 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4415 my $hash_parent = $parents[$i];
4416 my $from_hash = $diff->{'from_id'}[$i];
4417 my $from_path = $diff->{'from_file'}[$i];
4418 my $status = $diff->{'status'}[$i];
4419
4420 $has_history ||= ($status ne 'A');
4421 $not_deleted ||= ($status ne 'D');
4422
4423 if ($status eq 'A') {
4424 print "<td class=\"link\" align=\"right\"> | </td>\n";
4425 } elsif ($status eq 'D') {
4426 print "<td class=\"link\">" .
4427 $cgi->a({-href => href(action=>"blob",
4428 hash_base=>$hash,
4429 hash=>$from_hash,
4430 file_name=>$from_path)},
4431 "blob" . ($i+1)) .
4432 " | </td>\n";
4433 } else {
4434 if ($diff->{'to_id'} eq $from_hash) {
4435 print "<td class=\"link nochange\">";
4436 } else {
4437 print "<td class=\"link\">";
4438 }
4439 print $cgi->a({-href => href(action=>"blobdiff",
4440 hash=>$diff->{'to_id'},
4441 hash_parent=>$from_hash,
4442 hash_base=>$hash,
4443 hash_parent_base=>$hash_parent,
4444 file_name=>$diff->{'to_file'},
4445 file_parent=>$from_path)},
4446 "diff" . ($i+1)) .
4447 " | </td>\n";
4448 }
4449 }
4450
4451 print "<td class=\"link\">";
4452 if ($not_deleted) {
4453 print $cgi->a({-href => href(action=>"blob",
4454 hash=>$diff->{'to_id'},
4455 file_name=>$diff->{'to_file'},
4456 hash_base=>$hash)},
4457 "blob");
4458 print " | " if ($has_history);
4459 }
4460 if ($has_history) {
4461 print $cgi->a({-href => href(action=>"history",
4462 file_name=>$diff->{'to_file'},
4463 hash_base=>$hash)},
4464 "history");
4465 }
4466 print "</td>\n";
4467
4468 print "</tr>\n";
4469 next; # instead of 'else' clause, to avoid extra indent
4470 }
4471 # else ordinary diff
4472
4473 my ($to_mode_oct, $to_mode_str, $to_file_type);
4474 my ($from_mode_oct, $from_mode_str, $from_file_type);
4475 if ($diff->{'to_mode'} ne ('0' x 6)) {
4476 $to_mode_oct = oct $diff->{'to_mode'};
4477 if (S_ISREG($to_mode_oct)) { # only for regular file
4478 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4479 }
4480 $to_file_type = file_type($diff->{'to_mode'});
4481 }
4482 if ($diff->{'from_mode'} ne ('0' x 6)) {
4483 $from_mode_oct = oct $diff->{'from_mode'};
4484 if (S_ISREG($from_mode_oct)) { # only for regular file
4485 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4486 }
4487 $from_file_type = file_type($diff->{'from_mode'});
4488 }
4489
4490 if ($diff->{'status'} eq "A") { # created
4491 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4492 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4493 $mode_chng .= "]</span>";
4494 print "<td>";
4495 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4496 hash_base=>$hash, file_name=>$diff->{'file'}),
4497 -class => "list"}, esc_path($diff->{'file'}));
4498 print "</td>\n";
4499 print "<td>$mode_chng</td>\n";
4500 print "<td class=\"link\">";
4501 if ($action eq 'commitdiff') {
4502 # link to patch
4503 $patchno++;
4504 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4505 "patch") .
4506 " | ";
4507 }
4508 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4509 hash_base=>$hash, file_name=>$diff->{'file'})},
4510 "blob");
4511 print "</td>\n";
4512
4513 } elsif ($diff->{'status'} eq "D") { # deleted
4514 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4515 print "<td>";
4516 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4517 hash_base=>$parent, file_name=>$diff->{'file'}),
4518 -class => "list"}, esc_path($diff->{'file'}));
4519 print "</td>\n";
4520 print "<td>$mode_chng</td>\n";
4521 print "<td class=\"link\">";
4522 if ($action eq 'commitdiff') {
4523 # link to patch
4524 $patchno++;
4525 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4526 "patch") .
4527 " | ";
4528 }
4529 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4530 hash_base=>$parent, file_name=>$diff->{'file'})},
4531 "blob") . " | ";
4532 if ($have_blame) {
4533 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4534 file_name=>$diff->{'file'})},
4535 "blame") . " | ";
4536 }
4537 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4538 file_name=>$diff->{'file'})},
4539 "history");
4540 print "</td>\n";
4541
4542 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4543 my $mode_chnge = "";
4544 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4545 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4546 if ($from_file_type ne $to_file_type) {
4547 $mode_chnge .= " from $from_file_type to $to_file_type";
4548 }
4549 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4550 if ($from_mode_str && $to_mode_str) {
4551 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4552 } elsif ($to_mode_str) {
4553 $mode_chnge .= " mode: $to_mode_str";
4554 }
4555 }
4556 $mode_chnge .= "]</span>\n";
4557 }
4558 print "<td>";
4559 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4560 hash_base=>$hash, file_name=>$diff->{'file'}),
4561 -class => "list"}, esc_path($diff->{'file'}));
4562 print "</td>\n";
4563 print "<td>$mode_chnge</td>\n";
4564 print "<td class=\"link\">";
4565 if ($action eq 'commitdiff') {
4566 # link to patch
4567 $patchno++;
4568 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4569 "patch") .
4570 " | ";
4571 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4572 # "commit" view and modified file (not onlu mode changed)
4573 print $cgi->a({-href => href(action=>"blobdiff",
4574 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4575 hash_base=>$hash, hash_parent_base=>$parent,
4576 file_name=>$diff->{'file'})},
4577 "diff") .
4578 " | ";
4579 }
4580 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4581 hash_base=>$hash, file_name=>$diff->{'file'})},
4582 "blob") . " | ";
4583 if ($have_blame) {
4584 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4585 file_name=>$diff->{'file'})},
4586 "blame") . " | ";
4587 }
4588 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4589 file_name=>$diff->{'file'})},
4590 "history");
4591 print "</td>\n";
4592
4593 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4594 my %status_name = ('R' => 'moved', 'C' => 'copied');
4595 my $nstatus = $status_name{$diff->{'status'}};
4596 my $mode_chng = "";
4597 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4598 # mode also for directories, so we cannot use $to_mode_str
4599 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4600 }
4601 print "<td>" .
4602 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4603 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4604 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4605 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4606 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4607 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4608 -class => "list"}, esc_path($diff->{'from_file'})) .
4609 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4610 "<td class=\"link\">";
4611 if ($action eq 'commitdiff') {
4612 # link to patch
4613 $patchno++;
4614 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4615 "patch") .
4616 " | ";
4617 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4618 # "commit" view and modified file (not only pure rename or copy)
4619 print $cgi->a({-href => href(action=>"blobdiff",
4620 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4621 hash_base=>$hash, hash_parent_base=>$parent,
4622 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4623 "diff") .
4624 " | ";
4625 }
4626 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4627 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4628 "blob") . " | ";
4629 if ($have_blame) {
4630 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4631 file_name=>$diff->{'to_file'})},
4632 "blame") . " | ";
4633 }
4634 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4635 file_name=>$diff->{'to_file'})},
4636 "history");
4637 print "</td>\n";
4638
4639 } # we should not encounter Unmerged (U) or Unknown (X) status
4640 print "</tr>\n";
4641 }
4642 print "</tbody>" if $has_header;
4643 print "</table>\n";
4644 }
4645
4646 sub git_patchset_body {
4647 my ($fd, $difftree, $hash, @hash_parents) = @_;
4648 my ($hash_parent) = $hash_parents[0];
4649
4650 my $is_combined = (@hash_parents > 1);
4651 my $patch_idx = 0;
4652 my $patch_number = 0;
4653 my $patch_line;
4654 my $diffinfo;
4655 my $to_name;
4656 my (%from, %to);
4657
4658 print "<div class=\"patchset\">\n";
4659
4660 # skip to first patch
4661 while ($patch_line = <$fd>) {
4662 chomp $patch_line;
4663
4664 last if ($patch_line =~ m/^diff /);
4665 }
4666
4667 PATCH:
4668 while ($patch_line) {
4669
4670 # parse "git diff" header line
4671 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4672 # $1 is from_name, which we do not use
4673 $to_name = unquote($2);
4674 $to_name =~ s!^b/!!;
4675 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4676 # $1 is 'cc' or 'combined', which we do not use
4677 $to_name = unquote($2);
4678 } else {
4679 $to_name = undef;
4680 }
4681
4682 # check if current patch belong to current raw line
4683 # and parse raw git-diff line if needed
4684 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4685 # this is continuation of a split patch
4686 print "<div class=\"patch cont\">\n";
4687 } else {
4688 # advance raw git-diff output if needed
4689 $patch_idx++ if defined $diffinfo;
4690
4691 # read and prepare patch information
4692 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4693
4694 # compact combined diff output can have some patches skipped
4695 # find which patch (using pathname of result) we are at now;
4696 if ($is_combined) {
4697 while ($to_name ne $diffinfo->{'to_file'}) {
4698 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4699 format_diff_cc_simplified($diffinfo, @hash_parents) .
4700 "</div>\n"; # class="patch"
4701
4702 $patch_idx++;
4703 $patch_number++;
4704
4705 last if $patch_idx > $#$difftree;
4706 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4707 }
4708 }
4709
4710 # modifies %from, %to hashes
4711 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4712
4713 # this is first patch for raw difftree line with $patch_idx index
4714 # we index @$difftree array from 0, but number patches from 1
4715 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4716 }
4717
4718 # git diff header
4719 #assert($patch_line =~ m/^diff /) if DEBUG;
4720 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4721 $patch_number++;
4722 # print "git diff" header
4723 print format_git_diff_header_line($patch_line, $diffinfo,
4724 \%from, \%to);
4725
4726 # print extended diff header
4727 print "<div class=\"diff extended_header\">\n";
4728 EXTENDED_HEADER:
4729 while ($patch_line = <$fd>) {
4730 chomp $patch_line;
4731
4732 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4733
4734 print format_extended_diff_header_line($patch_line, $diffinfo,
4735 \%from, \%to);
4736 }
4737 print "</div>\n"; # class="diff extended_header"
4738
4739 # from-file/to-file diff header
4740 if (! $patch_line) {
4741 print "</div>\n"; # class="patch"
4742 last PATCH;
4743 }
4744 next PATCH if ($patch_line =~ m/^diff /);
4745 #assert($patch_line =~ m/^---/) if DEBUG;
4746
4747 my $last_patch_line = $patch_line;
4748 $patch_line = <$fd>;
4749 chomp $patch_line;
4750 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4751
4752 print format_diff_from_to_header($last_patch_line, $patch_line,
4753 $diffinfo, \%from, \%to,
4754 @hash_parents);
4755
4756 # the patch itself
4757 LINE:
4758 while ($patch_line = <$fd>) {
4759 chomp $patch_line;
4760
4761 next PATCH if ($patch_line =~ m/^diff /);
4762
4763 print format_diff_line($patch_line, \%from, \%to);
4764 }
4765
4766 } continue {
4767 print "</div>\n"; # class="patch"
4768 }
4769
4770 # for compact combined (--cc) format, with chunk and patch simplification
4771 # the patchset might be empty, but there might be unprocessed raw lines
4772 for (++$patch_idx if $patch_number > 0;
4773 $patch_idx < @$difftree;
4774 ++$patch_idx) {
4775 # read and prepare patch information
4776 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4777
4778 # generate anchor for "patch" links in difftree / whatchanged part
4779 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4780 format_diff_cc_simplified($diffinfo, @hash_parents) .
4781 "</div>\n"; # class="patch"
4782
4783 $patch_number++;
4784 }
4785
4786 if ($patch_number == 0) {
4787 if (@hash_parents > 1) {
4788 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4789 } else {
4790 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4791 }
4792 }
4793
4794 print "</div>\n"; # class="patchset"
4795 }
4796
4797 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4798
4799 # fills project list info (age, description, owner, forks) for each
4800 # project in the list, removing invalid projects from returned list
4801 # NOTE: modifies $projlist, but does not remove entries from it
4802 sub fill_project_list_info {
4803 my ($projlist, $check_forks) = @_;
4804 my @projects;
4805
4806 my $show_ctags = gitweb_check_feature('ctags');
4807 PROJECT:
4808 foreach my $pr (@$projlist) {
4809 my (@activity) = git_get_last_activity($pr->{'path'});
4810 unless (@activity) {
4811 next PROJECT;
4812 }
4813 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4814 if (!defined $pr->{'descr'}) {
4815 my $descr = git_get_project_description($pr->{'path'}) || "";
4816 $descr = to_utf8($descr);
4817 $pr->{'descr_long'} = $descr;
4818 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4819 }
4820 if (!defined $pr->{'owner'}) {
4821 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4822 }
4823 if ($check_forks) {
4824 my $pname = $pr->{'path'};
4825 if (($pname =~ s/\.git$//) &&
4826 ($pname !~ /\/$/) &&
4827 (-d "$projectroot/$pname")) {
4828 $pr->{'forks'} = "-d $projectroot/$pname";
4829 } else {
4830 $pr->{'forks'} = 0;
4831 }
4832 }
4833 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4834 push @projects, $pr;
4835 }
4836
4837 return @projects;
4838 }
4839
4840 # print 'sort by' <th> element, generating 'sort by $name' replay link
4841 # if that order is not selected
4842 sub print_sort_th {
4843 print format_sort_th(@_);
4844 }
4845
4846 sub format_sort_th {
4847 my ($name, $order, $header) = @_;
4848 my $sort_th = "";
4849 $header ||= ucfirst($name);
4850
4851 if ($order eq $name) {
4852 $sort_th .= "<th>$header</th>\n";
4853 } else {
4854 $sort_th .= "<th>" .
4855 $cgi->a({-href => href(-replay=>1, order=>$name),
4856 -class => "header"}, $header) .
4857 "</th>\n";
4858 }
4859
4860 return $sort_th;
4861 }
4862
4863 sub git_project_list_rows {
4864 my ($projlist, $from, $to, $check_forks) = @_;
4865
4866 $from = 0 unless defined $from;
4867 $to = $#$projlist if (!defined $to || $#$projlist < $to);
4868
4869 my $alternate = 1;
4870 my $tagfilter = $cgi->param('by_tag');
4871 for (my $i = $from; $i <= $to; $i++) {
4872 my $pr = $projlist->[$i];
4873
4874 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4875 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4876 and not $pr->{'descr_long'} =~ /$searchtext/;
4877 # Weed out forks or non-matching entries of search
4878 if ($check_forks) {
4879 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4880 $forkbase="^$forkbase" if $forkbase;
4881 next if not $searchtext and not $tagfilter and $show_ctags
4882 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4883 }
4884
4885 if ($alternate) {
4886 print "<tr class=\"dark\">\n";
4887 } else {
4888 print "<tr class=\"light\">\n";
4889 }
4890 $alternate ^= 1;
4891 if ($check_forks) {
4892 print "<td>";
4893 if ($pr->{'forks'}) {
4894 print "<!-- $pr->{'forks'} -->\n";
4895 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4896 }
4897 print "</td>\n";
4898 }
4899 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4900 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4901 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4902 -class => "list", -title => $pr->{'descr_long'}},
4903 esc_html($pr->{'descr'})) . "</td>\n" .
4904 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4905 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4906 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4907 "<td class=\"link\">" .
4908 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4909 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4910 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4911 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4912 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4913 "</td>\n" .
4914 "</tr>\n";
4915 }
4916 }
4917
4918 sub git_project_list_body {
4919 # actually uses global variable $project
4920 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4921
4922 my $check_forks = gitweb_check_feature('forks');
4923 my @projects = fill_project_list_info($projlist, $check_forks);
4924
4925 $order ||= $default_projects_order;
4926 $from = 0 unless defined $from;
4927 $to = $#projects if (!defined $to || $#projects < $to);
4928
4929 my %order_info = (
4930 project => { key => 'path', type => 'str' },
4931 descr => { key => 'descr_long', type => 'str' },
4932 owner => { key => 'owner', type => 'str' },
4933 age => { key => 'age', type => 'num' }
4934 );
4935 my $oi = $order_info{$order};
4936 if ($oi->{'type'} eq 'str') {
4937 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4938 } else {
4939 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4940 }
4941
4942 my $show_ctags = gitweb_check_feature('ctags');
4943 if ($show_ctags) {
4944 my $ctags = git_gather_all_ctags(\@projects);
4945 my $cloud = git_populate_project_tagcloud($ctags);
4946 print git_show_project_tagcloud($cloud, 64);
4947 }
4948
4949 print "<table class=\"project_list\">\n";
4950 unless ($no_header) {
4951 print "<tr>\n";
4952 if ($check_forks) {
4953 print "<th></th>\n";
4954 }
4955 print_sort_th('project', $order, 'Project');
4956 print_sort_th('descr', $order, 'Description');
4957 print_sort_th('owner', $order, 'Owner');
4958 print_sort_th('age', $order, 'Last Change');
4959 print "<th></th>\n" . # for links
4960 "</tr>\n";
4961 }
4962 git_project_list_rows(\@projects, $from, $to, $check_forks);
4963
4964 if (defined $extra) {
4965 print "<tr>\n";
4966 if ($check_forks) {
4967 print "<td></td>\n";
4968 }
4969 print "<td colspan=\"5\">$extra</td>\n" .
4970 "</tr>\n";
4971 }
4972 print "</table>\n";
4973 }
4974
4975 sub git_log_body {
4976 # uses global variable $project
4977 my ($commitlist, $from, $to, $refs, $extra) = @_;
4978
4979 $from = 0 unless defined $from;
4980 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4981
4982 for (my $i = 0; $i <= $to; $i++) {
4983 my %co = %{$commitlist->[$i]};
4984 next if !%co;
4985 my $commit = $co{'id'};
4986 my $ref = format_ref_marker($refs, $commit);
4987 git_print_header_div('commit',
4988 "<span class=\"age\">$co{'age_string'}</span>" .
4989 esc_html($co{'title'}) . $ref,
4990 $commit);
4991 print "<div class=\"title_text\">\n" .
4992 "<div class=\"log_link\">\n" .
4993 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4994 " | " .
4995 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4996 " | " .
4997 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4998 "<br/>\n" .
4999 "</div>\n";
5000 git_print_authorship(\%co, -tag => 'span');
5001 print "<br/>\n</div>\n";
5002
5003 print "<div class=\"log_body\">\n";
5004 git_print_log($co{'comment'}, -final_empty_line=> 1);
5005 print "</div>\n";
5006 }
5007 if ($extra) {
5008 print "<div class=\"page_nav\">\n";
5009 print "$extra\n";
5010 print "</div>\n";
5011 }
5012 }
5013
5014 sub git_shortlog_body {
5015 # uses global variable $project
5016 my ($commitlist, $from, $to, $refs, $extra) = @_;
5017
5018 $from = 0 unless defined $from;
5019 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5020
5021 print "<table class=\"shortlog\">\n";
5022 my $alternate = 1;
5023 for (my $i = $from; $i <= $to; $i++) {
5024 my %co = %{$commitlist->[$i]};
5025 my $commit = $co{'id'};
5026 my $ref = format_ref_marker($refs, $commit);
5027 if ($alternate) {
5028 print "<tr class=\"dark\">\n";
5029 } else {
5030 print "<tr class=\"light\">\n";
5031 }
5032 $alternate ^= 1;
5033 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5034 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5035 format_author_html('td', \%co, 10) . "<td>";
5036 print format_subject_html($co{'title'}, $co{'title_short'},
5037 href(action=>"commit", hash=>$commit), $ref);
5038 print "</td>\n" .
5039 "<td class=\"link\">" .
5040 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5041 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5042 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5043 my $snapshot_links = format_snapshot_links($commit);
5044 if (defined $snapshot_links) {
5045 print " | " . $snapshot_links;
5046 }
5047 print "</td>\n" .
5048 "</tr>\n";
5049 }
5050 if (defined $extra) {
5051 print "<tr>\n" .
5052 "<td colspan=\"4\">$extra</td>\n" .
5053 "</tr>\n";
5054 }
5055 print "</table>\n";
5056 }
5057
5058 sub git_history_body {
5059 # Warning: assumes constant type (blob or tree) during history
5060 my ($commitlist, $from, $to, $refs, $extra,
5061 $file_name, $file_hash, $ftype) = @_;
5062
5063 $from = 0 unless defined $from;
5064 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5065
5066 print "<table class=\"history\">\n";
5067 my $alternate = 1;
5068 for (my $i = $from; $i <= $to; $i++) {
5069 my %co = %{$commitlist->[$i]};
5070 if (!%co) {
5071 next;
5072 }
5073 my $commit = $co{'id'};
5074
5075 my $ref = format_ref_marker($refs, $commit);
5076
5077 if ($alternate) {
5078 print "<tr class=\"dark\">\n";
5079 } else {
5080 print "<tr class=\"light\">\n";
5081 }
5082 $alternate ^= 1;
5083 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5084 # shortlog: format_author_html('td', \%co, 10)
5085 format_author_html('td', \%co, 15, 3) . "<td>";
5086 # originally git_history used chop_str($co{'title'}, 50)
5087 print format_subject_html($co{'title'}, $co{'title_short'},
5088 href(action=>"commit", hash=>$commit), $ref);
5089 print "</td>\n" .
5090 "<td class=\"link\">" .
5091 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5092 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5093
5094 if ($ftype eq 'blob') {
5095 my $blob_current = $file_hash;
5096 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5097 if (defined $blob_current && defined $blob_parent &&
5098 $blob_current ne $blob_parent) {
5099 print " | " .
5100 $cgi->a({-href => href(action=>"blobdiff",
5101 hash=>$blob_current, hash_parent=>$blob_parent,
5102 hash_base=>$hash_base, hash_parent_base=>$commit,
5103 file_name=>$file_name)},
5104 "diff to current");
5105 }
5106 }
5107 print "</td>\n" .
5108 "</tr>\n";
5109 }
5110 if (defined $extra) {
5111 print "<tr>\n" .
5112 "<td colspan=\"4\">$extra</td>\n" .
5113 "</tr>\n";
5114 }
5115 print "</table>\n";
5116 }
5117
5118 sub git_tags_body {
5119 # uses global variable $project
5120 my ($taglist, $from, $to, $extra) = @_;
5121 $from = 0 unless defined $from;
5122 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5123
5124 print "<table class=\"tags\">\n";
5125 my $alternate = 1;
5126 for (my $i = $from; $i <= $to; $i++) {
5127 my $entry = $taglist->[$i];
5128 my %tag = %$entry;
5129 my $comment = $tag{'subject'};
5130 my $comment_short;
5131 if (defined $comment) {
5132 $comment_short = chop_str($comment, 30, 5);
5133 }
5134 if ($alternate) {
5135 print "<tr class=\"dark\">\n";
5136 } else {
5137 print "<tr class=\"light\">\n";
5138 }
5139 $alternate ^= 1;
5140 if (defined $tag{'age'}) {
5141 print "<td><i>$tag{'age'}</i></td>\n";
5142 } else {
5143 print "<td></td>\n";
5144 }
5145 print "<td>" .
5146 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5147 -class => "list name"}, esc_html($tag{'name'})) .
5148 "</td>\n" .
5149 "<td>";
5150 if (defined $comment) {
5151 print format_subject_html($comment, $comment_short,
5152 href(action=>"tag", hash=>$tag{'id'}));
5153 }
5154 print "</td>\n" .
5155 "<td class=\"selflink\">";
5156 if ($tag{'type'} eq "tag") {
5157 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5158 } else {
5159 print "&nbsp;";
5160 }
5161 print "</td>\n" .
5162 "<td class=\"link\">" . " | " .
5163 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5164 if ($tag{'reftype'} eq "commit") {
5165 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5166 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5167 } elsif ($tag{'reftype'} eq "blob") {
5168 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5169 }
5170 print "</td>\n" .
5171 "</tr>";
5172 }
5173 if (defined $extra) {
5174 print "<tr>\n" .
5175 "<td colspan=\"5\">$extra</td>\n" .
5176 "</tr>\n";
5177 }
5178 print "</table>\n";
5179 }
5180
5181 sub git_heads_body {
5182 # uses global variable $project
5183 my ($headlist, $head, $from, $to, $extra) = @_;
5184 $from = 0 unless defined $from;
5185 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5186
5187 print "<table class=\"heads\">\n";
5188 my $alternate = 1;
5189 for (my $i = $from; $i <= $to; $i++) {
5190 my $entry = $headlist->[$i];
5191 my %ref = %$entry;
5192 my $curr = $ref{'id'} eq $head;
5193 if ($alternate) {
5194 print "<tr class=\"dark\">\n";
5195 } else {
5196 print "<tr class=\"light\">\n";
5197 }
5198 $alternate ^= 1;
5199 print "<td><i>$ref{'age'}</i></td>\n" .
5200 ($curr ? "<td class=\"current_head\">" : "<td>") .
5201 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5202 -class => "list name"},esc_html($ref{'name'})) .
5203 "</td>\n" .
5204 "<td class=\"link\">" .
5205 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5206 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5207 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
5208 "</td>\n" .
5209 "</tr>";
5210 }
5211 if (defined $extra) {
5212 print "<tr>\n" .
5213 "<td colspan=\"3\">$extra</td>\n" .
5214 "</tr>\n";
5215 }
5216 print "</table>\n";
5217 }
5218
5219 # Display a single remote block
5220 sub git_remote_block {
5221 my ($remote, $rdata, $limit, $head) = @_;
5222
5223 my $heads = $rdata->{'heads'};
5224 my $fetch = $rdata->{'fetch'};
5225 my $push = $rdata->{'push'};
5226
5227 my $urls_table = "<table class=\"projects_list\">\n" ;
5228
5229 if (defined $fetch) {
5230 if ($fetch eq $push) {
5231 $urls_table .= format_repo_url("URL", $fetch);
5232 } else {
5233 $urls_table .= format_repo_url("Fetch URL", $fetch);
5234 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
5235 }
5236 } elsif (defined $push) {
5237 $urls_table .= format_repo_url("Push URL", $push);
5238 } else {
5239 $urls_table .= format_repo_url("", "No remote URL");
5240 }
5241
5242 $urls_table .= "</table>\n";
5243
5244 my $dots;
5245 if (defined $limit && $limit < @$heads) {
5246 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
5247 }
5248
5249 print $urls_table;
5250 git_heads_body($heads, $head, 0, $limit, $dots);
5251 }
5252
5253 # Display a list of remote names with the respective fetch and push URLs
5254 sub git_remotes_list {
5255 my ($remotedata, $limit) = @_;
5256 print "<table class=\"heads\">\n";
5257 my $alternate = 1;
5258 my @remotes = sort keys %$remotedata;
5259
5260 my $limited = $limit && $limit < @remotes;
5261
5262 $#remotes = $limit - 1 if $limited;
5263
5264 while (my $remote = shift @remotes) {
5265 my $rdata = $remotedata->{$remote};
5266 my $fetch = $rdata->{'fetch'};
5267 my $push = $rdata->{'push'};
5268 if ($alternate) {
5269 print "<tr class=\"dark\">\n";
5270 } else {
5271 print "<tr class=\"light\">\n";
5272 }
5273 $alternate ^= 1;
5274 print "<td>" .
5275 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
5276 -class=> "list name"},esc_html($remote)) .
5277 "</td>";
5278 print "<td class=\"link\">" .
5279 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
5280 " | " .
5281 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
5282 "</td>";
5283
5284 print "</tr>\n";
5285 }
5286
5287 if ($limited) {
5288 print "<tr>\n" .
5289 "<td colspan=\"3\">" .
5290 $cgi->a({-href => href(action=>"remotes")}, "...") .
5291 "</td>\n" . "</tr>\n";
5292 }
5293
5294 print "</table>";
5295 }
5296
5297 # Display remote heads grouped by remote, unless there are too many
5298 # remotes, in which case we only display the remote names
5299 sub git_remotes_body {
5300 my ($remotedata, $limit, $head) = @_;
5301 if ($limit and $limit < keys %$remotedata) {
5302 git_remotes_list($remotedata, $limit);
5303 } else {
5304 fill_remote_heads($remotedata);
5305 while (my ($remote, $rdata) = each %$remotedata) {
5306 git_print_section({-class=>"remote", -id=>$remote},
5307 ["remotes", $remote, $remote], sub {
5308 git_remote_block($remote, $rdata, $limit, $head);
5309 });
5310 }
5311 }
5312 }
5313
5314 sub git_search_grep_body {
5315 my ($commitlist, $from, $to, $extra) = @_;
5316 $from = 0 unless defined $from;
5317 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5318
5319 print "<table class=\"commit_search\">\n";
5320 my $alternate = 1;
5321 for (my $i = $from; $i <= $to; $i++) {
5322 my %co = %{$commitlist->[$i]};
5323 if (!%co) {
5324 next;
5325 }
5326 my $commit = $co{'id'};
5327 if ($alternate) {
5328 print "<tr class=\"dark\">\n";
5329 } else {
5330 print "<tr class=\"light\">\n";
5331 }
5332 $alternate ^= 1;
5333 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5334 format_author_html('td', \%co, 15, 5) .
5335 "<td>" .
5336 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5337 -class => "list subject"},
5338 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5339 my $comment = $co{'comment'};
5340 foreach my $line (@$comment) {
5341 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5342 my ($lead, $match, $trail) = ($1, $2, $3);
5343 $match = chop_str($match, 70, 5, 'center');
5344 my $contextlen = int((80 - length($match))/2);
5345 $contextlen = 30 if ($contextlen > 30);
5346 $lead = chop_str($lead, $contextlen, 10, 'left');
5347 $trail = chop_str($trail, $contextlen, 10, 'right');
5348
5349 $lead = esc_html($lead);
5350 $match = esc_html($match);
5351 $trail = esc_html($trail);
5352
5353 print "$lead<span class=\"match\">$match</span>$trail<br />";
5354 }
5355 }
5356 print "</td>\n" .
5357 "<td class=\"link\">" .
5358 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5359 " | " .
5360 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5361 " | " .
5362 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5363 print "</td>\n" .
5364 "</tr>\n";
5365 }
5366 if (defined $extra) {
5367 print "<tr>\n" .
5368 "<td colspan=\"3\">$extra</td>\n" .
5369 "</tr>\n";
5370 }
5371 print "</table>\n";
5372 }
5373
5374 ## ======================================================================
5375 ## ======================================================================
5376 ## actions
5377
5378 sub git_project_list {
5379 my $order = $input_params{'order'};
5380 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5381 die_error(400, "Unknown order parameter");
5382 }
5383
5384 my @list = git_get_projects_list();
5385 if (!@list) {
5386 die_error(404, "No projects found");
5387 }
5388
5389 git_header_html();
5390 if (defined $home_text && -f $home_text) {
5391 print "<div class=\"index_include\">\n";
5392 insert_file($home_text);
5393 print "</div>\n";
5394 }
5395 print $cgi->startform(-method => "get") .
5396 "<p class=\"projsearch\">Search:\n" .
5397 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5398 "</p>" .
5399 $cgi->end_form() . "\n";
5400 git_project_list_body(\@list, $order);
5401 git_footer_html();
5402 }
5403
5404 sub git_forks {
5405 my $order = $input_params{'order'};
5406 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5407 die_error(400, "Unknown order parameter");
5408 }
5409
5410 my @list = git_get_projects_list($project);
5411 if (!@list) {
5412 die_error(404, "No forks found");
5413 }
5414
5415 git_header_html();
5416 git_print_page_nav('','');
5417 git_print_header_div('summary', "$project forks");
5418 git_project_list_body(\@list, $order);
5419 git_footer_html();
5420 }
5421
5422 sub git_project_index {
5423 my @projects = git_get_projects_list($project);
5424
5425 print $cgi->header(
5426 -type => 'text/plain',
5427 -charset => 'utf-8',
5428 -content_disposition => 'inline; filename="index.aux"');
5429
5430 foreach my $pr (@projects) {
5431 if (!exists $pr->{'owner'}) {
5432 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5433 }
5434
5435 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5436 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5437 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5438 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5439 $path =~ s/ /\+/g;
5440 $owner =~ s/ /\+/g;
5441
5442 print "$path $owner\n";
5443 }
5444 }
5445
5446 sub git_summary {
5447 my $descr = git_get_project_description($project) || "none";
5448 my %co = parse_commit("HEAD");
5449 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5450 my $head = $co{'id'};
5451 my $remote_heads = gitweb_check_feature('remote_heads');
5452
5453 my $owner = git_get_project_owner($project);
5454
5455 my $refs = git_get_references();
5456 # These get_*_list functions return one more to allow us to see if
5457 # there are more ...
5458 my @taglist = git_get_tags_list(16);
5459 my @headlist = git_get_heads_list(16);
5460 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
5461 my @forklist;
5462 my $check_forks = gitweb_check_feature('forks');
5463
5464 if ($check_forks) {
5465 @forklist = git_get_projects_list($project);
5466 }
5467
5468 git_header_html();
5469 git_print_page_nav('summary','', $head);
5470
5471 print "<div class=\"title\">&nbsp;</div>\n";
5472 print "<table class=\"projects_list\">\n" .
5473 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5474 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5475 if (defined $cd{'rfc2822'}) {
5476 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5477 }
5478
5479 # use per project git URL list in $projectroot/$project/cloneurl
5480 # or make project git URL from git base URL and project name
5481 my $url_tag = "URL";
5482 my @url_list = git_get_project_url_list($project);
5483 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5484 foreach my $git_url (@url_list) {
5485 next unless $git_url;
5486 print format_repo_url($url_tag, $git_url);
5487 $url_tag = "";
5488 }
5489
5490 # Tag cloud
5491 my $show_ctags = gitweb_check_feature('ctags');
5492 if ($show_ctags) {
5493 my $ctags = git_get_project_ctags($project);
5494 if (%$ctags) {
5495 # without ability to add tags, don't show if there are none
5496 my $cloud = git_populate_project_tagcloud($ctags);
5497 print "<tr id=\"metadata_ctags\">" .
5498 "<td>content tags</td>" .
5499 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
5500 "</tr>\n";
5501 }
5502 }
5503
5504 print "</table>\n";
5505
5506 # If XSS prevention is on, we don't include README.html.
5507 # TODO: Allow a readme in some safe format.
5508 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5509 print "<div class=\"title\">readme</div>\n" .
5510 "<div class=\"readme\">\n";
5511 insert_file("$projectroot/$project/README.html");
5512 print "\n</div>\n"; # class="readme"
5513 }
5514
5515 # we need to request one more than 16 (0..15) to check if
5516 # those 16 are all
5517 my @commitlist = $head ? parse_commits($head, 17) : ();
5518 if (@commitlist) {
5519 git_print_header_div('shortlog');
5520 git_shortlog_body(\@commitlist, 0, 15, $refs,
5521 $#commitlist <= 15 ? undef :
5522 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5523 }
5524
5525 if (@taglist) {
5526 git_print_header_div('tags');
5527 git_tags_body(\@taglist, 0, 15,
5528 $#taglist <= 15 ? undef :
5529 $cgi->a({-href => href(action=>"tags")}, "..."));
5530 }
5531
5532 if (@headlist) {
5533 git_print_header_div('heads');
5534 git_heads_body(\@headlist, $head, 0, 15,
5535 $#headlist <= 15 ? undef :
5536 $cgi->a({-href => href(action=>"heads")}, "..."));
5537 }
5538
5539 if (%remotedata) {
5540 git_print_header_div('remotes');
5541 git_remotes_body(\%remotedata, 15, $head);
5542 }
5543
5544 if (@forklist) {
5545 git_print_header_div('forks');
5546 git_project_list_body(\@forklist, 'age', 0, 15,
5547 $#forklist <= 15 ? undef :
5548 $cgi->a({-href => href(action=>"forks")}, "..."),
5549 'no_header');
5550 }
5551
5552 git_footer_html();
5553 }
5554
5555 sub git_tag {
5556 my %tag = parse_tag($hash);
5557
5558 if (! %tag) {
5559 die_error(404, "Unknown tag object");
5560 }
5561
5562 my $head = git_get_head_hash($project);
5563 git_header_html();
5564 git_print_page_nav('','', $head,undef,$head);
5565 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5566 print "<div class=\"title_text\">\n" .
5567 "<table class=\"object_header\">\n" .
5568 "<tr>\n" .
5569 "<td>object</td>\n" .
5570 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5571 $tag{'object'}) . "</td>\n" .
5572 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5573 $tag{'type'}) . "</td>\n" .
5574 "</tr>\n";
5575 if (defined($tag{'author'})) {
5576 git_print_authorship_rows(\%tag, 'author');
5577 }
5578 print "</table>\n\n" .
5579 "</div>\n";
5580 print "<div class=\"page_body\">";
5581 my $comment = $tag{'comment'};
5582 foreach my $line (@$comment) {
5583 chomp $line;
5584 print esc_html($line, -nbsp=>1) . "<br/>\n";
5585 }
5586 print "</div>\n";
5587 git_footer_html();
5588 }
5589
5590 sub git_blame_common {
5591 my $format = shift || 'porcelain';
5592 if ($format eq 'porcelain' && $cgi->param('js')) {
5593 $format = 'incremental';
5594 $action = 'blame_incremental'; # for page title etc
5595 }
5596
5597 # permissions
5598 gitweb_check_feature('blame')
5599 or die_error(403, "Blame view not allowed");
5600
5601 # error checking
5602 die_error(400, "No file name given") unless $file_name;
5603 $hash_base ||= git_get_head_hash($project);
5604 die_error(404, "Couldn't find base commit") unless $hash_base;
5605 my %co = parse_commit($hash_base)
5606 or die_error(404, "Commit not found");
5607 my $ftype = "blob";
5608 if (!defined $hash) {
5609 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5610 or die_error(404, "Error looking up file");
5611 } else {
5612 $ftype = git_get_type($hash);
5613 if ($ftype !~ "blob") {
5614 die_error(400, "Object is not a blob");
5615 }
5616 }
5617
5618 my $fd;
5619 if ($format eq 'incremental') {
5620 # get file contents (as base)
5621 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5622 or die_error(500, "Open git-cat-file failed");
5623 } elsif ($format eq 'data') {
5624 # run git-blame --incremental
5625 open $fd, "-|", git_cmd(), "blame", "--incremental",
5626 $hash_base, "--", $file_name
5627 or die_error(500, "Open git-blame --incremental failed");
5628 } else {
5629 # run git-blame --porcelain
5630 open $fd, "-|", git_cmd(), "blame", '-p',
5631 $hash_base, '--', $file_name
5632 or die_error(500, "Open git-blame --porcelain failed");
5633 }
5634
5635 # incremental blame data returns early
5636 if ($format eq 'data') {
5637 print $cgi->header(
5638 -type=>"text/plain", -charset => "utf-8",
5639 -status=> "200 OK");
5640 local $| = 1; # output autoflush
5641 print while <$fd>;
5642 close $fd
5643 or print "ERROR $!\n";
5644
5645 print 'END';
5646 if (defined $t0 && gitweb_check_feature('timed')) {
5647 print ' '.
5648 tv_interval($t0, [ gettimeofday() ]).
5649 ' '.$number_of_git_cmds;
5650 }
5651 print "\n";
5652
5653 return;
5654 }
5655
5656 # page header
5657 git_header_html();
5658 my $formats_nav =
5659 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5660 "blob") .
5661 " | ";
5662 if ($format eq 'incremental') {
5663 $formats_nav .=
5664 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5665 "blame") . " (non-incremental)";
5666 } else {
5667 $formats_nav .=
5668 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5669 "blame") . " (incremental)";
5670 }
5671 $formats_nav .=
5672 " | " .
5673 $cgi->a({-href => href(action=>"history", -replay=>1)},
5674 "history") .
5675 " | " .
5676 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5677 "HEAD");
5678 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5679 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5680 git_print_page_path($file_name, $ftype, $hash_base);
5681
5682 # page body
5683 if ($format eq 'incremental') {
5684 print "<noscript>\n<div class=\"error\"><center><b>\n".
5685 "This page requires JavaScript to run.\n Use ".
5686 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5687 'this page').
5688 " instead.\n".
5689 "</b></center></div>\n</noscript>\n";
5690
5691 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5692 }
5693
5694 print qq!<div class="page_body">\n!;
5695 print qq!<div id="progress_info">... / ...</div>\n!
5696 if ($format eq 'incremental');
5697 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5698 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5699 qq!<thead>\n!.
5700 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5701 qq!</thead>\n!.
5702 qq!<tbody>\n!;
5703
5704 my @rev_color = qw(light dark);
5705 my $num_colors = scalar(@rev_color);
5706 my $current_color = 0;
5707
5708 if ($format eq 'incremental') {
5709 my $color_class = $rev_color[$current_color];
5710
5711 #contents of a file
5712 my $linenr = 0;
5713 LINE:
5714 while (my $line = <$fd>) {
5715 chomp $line;
5716 $linenr++;
5717
5718 print qq!<tr id="l$linenr" class="$color_class">!.
5719 qq!<td class="sha1"><a href=""> </a></td>!.
5720 qq!<td class="linenr">!.
5721 qq!<a class="linenr" href="">$linenr</a></td>!;
5722 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5723 print qq!</tr>\n!;
5724 }
5725
5726 } else { # porcelain, i.e. ordinary blame
5727 my %metainfo = (); # saves information about commits
5728
5729 # blame data
5730 LINE:
5731 while (my $line = <$fd>) {
5732 chomp $line;
5733 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5734 # no <lines in group> for subsequent lines in group of lines
5735 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5736 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5737 if (!exists $metainfo{$full_rev}) {
5738 $metainfo{$full_rev} = { 'nprevious' => 0 };
5739 }
5740 my $meta = $metainfo{$full_rev};
5741 my $data;
5742 while ($data = <$fd>) {
5743 chomp $data;
5744 last if ($data =~ s/^\t//); # contents of line
5745 if ($data =~ /^(\S+)(?: (.*))?$/) {
5746 $meta->{$1} = $2 unless exists $meta->{$1};
5747 }
5748 if ($data =~ /^previous /) {
5749 $meta->{'nprevious'}++;
5750 }
5751 }
5752 my $short_rev = substr($full_rev, 0, 8);
5753 my $author = $meta->{'author'};
5754 my %date =
5755 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5756 my $date = $date{'iso-tz'};
5757 if ($group_size) {
5758 $current_color = ($current_color + 1) % $num_colors;
5759 }
5760 my $tr_class = $rev_color[$current_color];
5761 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5762 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5763 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5764 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5765 if ($group_size) {
5766 print "<td class=\"sha1\"";
5767 print " title=\"". esc_html($author) . ", $date\"";
5768 print " rowspan=\"$group_size\"" if ($group_size > 1);
5769 print ">";
5770 print $cgi->a({-href => href(action=>"commit",
5771 hash=>$full_rev,
5772 file_name=>$file_name)},
5773 esc_html($short_rev));
5774 if ($group_size >= 2) {
5775 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5776 if (@author_initials) {
5777 print "<br />" .
5778 esc_html(join('', @author_initials));
5779 # or join('.', ...)
5780 }
5781 }
5782 print "</td>\n";
5783 }
5784 # 'previous' <sha1 of parent commit> <filename at commit>
5785 if (exists $meta->{'previous'} &&
5786 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5787 $meta->{'parent'} = $1;
5788 $meta->{'file_parent'} = unquote($2);
5789 }
5790 my $linenr_commit =
5791 exists($meta->{'parent'}) ?
5792 $meta->{'parent'} : $full_rev;
5793 my $linenr_filename =
5794 exists($meta->{'file_parent'}) ?
5795 $meta->{'file_parent'} : unquote($meta->{'filename'});
5796 my $blamed = href(action => 'blame',
5797 file_name => $linenr_filename,
5798 hash_base => $linenr_commit);
5799 print "<td class=\"linenr\">";
5800 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5801 -class => "linenr" },
5802 esc_html($lineno));
5803 print "</td>";
5804 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5805 print "</tr>\n";
5806 } # end while
5807
5808 }
5809
5810 # footer
5811 print "</tbody>\n".
5812 "</table>\n"; # class="blame"
5813 print "</div>\n"; # class="blame_body"
5814 close $fd
5815 or print "Reading blob failed\n";
5816
5817 git_footer_html();
5818 }
5819
5820 sub git_blame {
5821 git_blame_common();
5822 }
5823
5824 sub git_blame_incremental {
5825 git_blame_common('incremental');
5826 }
5827
5828 sub git_blame_data {
5829 git_blame_common('data');
5830 }
5831
5832 sub git_tags {
5833 my $head = git_get_head_hash($project);
5834 git_header_html();
5835 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
5836 git_print_header_div('summary', $project);
5837
5838 my @tagslist = git_get_tags_list();
5839 if (@tagslist) {
5840 git_tags_body(\@tagslist);
5841 }
5842 git_footer_html();
5843 }
5844
5845 sub git_heads {
5846 my $head = git_get_head_hash($project);
5847 git_header_html();
5848 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
5849 git_print_header_div('summary', $project);
5850
5851 my @headslist = git_get_heads_list();
5852 if (@headslist) {
5853 git_heads_body(\@headslist, $head);
5854 }
5855 git_footer_html();
5856 }
5857
5858 # used both for single remote view and for list of all the remotes
5859 sub git_remotes {
5860 gitweb_check_feature('remote_heads')
5861 or die_error(403, "Remote heads view is disabled");
5862
5863 my $head = git_get_head_hash($project);
5864 my $remote = $input_params{'hash'};
5865
5866 my $remotedata = git_get_remotes_list($remote);
5867 die_error(500, "Unable to get remote information") unless defined $remotedata;
5868
5869 unless (%$remotedata) {
5870 die_error(404, defined $remote ?
5871 "Remote $remote not found" :
5872 "No remotes found");
5873 }
5874
5875 git_header_html(undef, undef, -action_extra => $remote);
5876 git_print_page_nav('', '', $head, undef, $head,
5877 format_ref_views($remote ? '' : 'remotes'));
5878
5879 fill_remote_heads($remotedata);
5880 if (defined $remote) {
5881 git_print_header_div('remotes', "$remote remote for $project");
5882 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
5883 } else {
5884 git_print_header_div('summary', "$project remotes");
5885 git_remotes_body($remotedata, undef, $head);
5886 }
5887
5888 git_footer_html();
5889 }
5890
5891 sub git_blob_plain {
5892 my $type = shift;
5893 my $expires;
5894
5895 if (!defined $hash) {
5896 if (defined $file_name) {
5897 my $base = $hash_base || git_get_head_hash($project);
5898 $hash = git_get_hash_by_path($base, $file_name, "blob")
5899 or die_error(404, "Cannot find file");
5900 } else {
5901 die_error(400, "No file name defined");
5902 }
5903 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5904 # blobs defined by non-textual hash id's can be cached
5905 $expires = "+1d";
5906 }
5907
5908 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5909 or die_error(500, "Open git-cat-file blob '$hash' failed");
5910
5911 # content-type (can include charset)
5912 $type = blob_contenttype($fd, $file_name, $type);
5913
5914 # "save as" filename, even when no $file_name is given
5915 my $save_as = "$hash";
5916 if (defined $file_name) {
5917 $save_as = $file_name;
5918 } elsif ($type =~ m/^text\//) {
5919 $save_as .= '.txt';
5920 }
5921
5922 # With XSS prevention on, blobs of all types except a few known safe
5923 # ones are served with "Content-Disposition: attachment" to make sure
5924 # they don't run in our security domain. For certain image types,
5925 # blob view writes an <img> tag referring to blob_plain view, and we
5926 # want to be sure not to break that by serving the image as an
5927 # attachment (though Firefox 3 doesn't seem to care).
5928 my $sandbox = $prevent_xss &&
5929 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5930
5931 print $cgi->header(
5932 -type => $type,
5933 -expires => $expires,
5934 -content_disposition =>
5935 ($sandbox ? 'attachment' : 'inline')
5936 . '; filename="' . $save_as . '"');
5937 local $/ = undef;
5938 binmode STDOUT, ':raw';
5939 print <$fd>;
5940 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5941 close $fd;
5942 }
5943
5944 sub git_blob {
5945 my $expires;
5946
5947 if (!defined $hash) {
5948 if (defined $file_name) {
5949 my $base = $hash_base || git_get_head_hash($project);
5950 $hash = git_get_hash_by_path($base, $file_name, "blob")
5951 or die_error(404, "Cannot find file");
5952 } else {
5953 die_error(400, "No file name defined");
5954 }
5955 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5956 # blobs defined by non-textual hash id's can be cached
5957 $expires = "+1d";
5958 }
5959
5960 my $have_blame = gitweb_check_feature('blame');
5961 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5962 or die_error(500, "Couldn't cat $file_name, $hash");
5963 my $mimetype = blob_mimetype($fd, $file_name);
5964 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5965 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5966 close $fd;
5967 return git_blob_plain($mimetype);
5968 }
5969 # we can have blame only for text/* mimetype
5970 $have_blame &&= ($mimetype =~ m!^text/!);
5971
5972 my $highlight = gitweb_check_feature('highlight');
5973 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5974 $fd = run_highlighter($fd, $highlight, $syntax)
5975 if $syntax;
5976
5977 git_header_html(undef, $expires);
5978 my $formats_nav = '';
5979 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5980 if (defined $file_name) {
5981 if ($have_blame) {
5982 $formats_nav .=
5983 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5984 "blame") .
5985 " | ";
5986 }
5987 $formats_nav .=
5988 $cgi->a({-href => href(action=>"history", -replay=>1)},
5989 "history") .
5990 " | " .
5991 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5992 "raw") .
5993 " | " .
5994 $cgi->a({-href => href(action=>"blob",
5995 hash_base=>"HEAD", file_name=>$file_name)},
5996 "HEAD");
5997 } else {
5998 $formats_nav .=
5999 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6000 "raw");
6001 }
6002 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6003 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6004 } else {
6005 print "<div class=\"page_nav\">\n" .
6006 "<br/><br/></div>\n" .
6007 "<div class=\"title\">".esc_html($hash)."</div>\n";
6008 }
6009 git_print_page_path($file_name, "blob", $hash_base);
6010 print "<div class=\"page_body\">\n";
6011 if ($mimetype =~ m!^image/!) {
6012 print qq!<img type="!.esc_attr($mimetype).qq!"!;
6013 if ($file_name) {
6014 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
6015 }
6016 print qq! src="! .
6017 href(action=>"blob_plain", hash=>$hash,
6018 hash_base=>$hash_base, file_name=>$file_name) .
6019 qq!" />\n!;
6020 } else {
6021 my $nr;
6022 while (my $line = <$fd>) {
6023 chomp $line;
6024 $nr++;
6025 $line = untabify($line);
6026 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
6027 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
6028 }
6029 }
6030 close $fd
6031 or print "Reading blob failed.\n";
6032 print "</div>";
6033 git_footer_html();
6034 }
6035
6036 sub git_tree {
6037 if (!defined $hash_base) {
6038 $hash_base = "HEAD";
6039 }
6040 if (!defined $hash) {
6041 if (defined $file_name) {
6042 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
6043 } else {
6044 $hash = $hash_base;
6045 }
6046 }
6047 die_error(404, "No such tree") unless defined($hash);
6048
6049 my $show_sizes = gitweb_check_feature('show-sizes');
6050 my $have_blame = gitweb_check_feature('blame');
6051
6052 my @entries = ();
6053 {
6054 local $/ = "\0";
6055 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
6056 ($show_sizes ? '-l' : ()), @extra_options, $hash
6057 or die_error(500, "Open git-ls-tree failed");
6058 @entries = map { chomp; $_ } <$fd>;
6059 close $fd
6060 or die_error(404, "Reading tree failed");
6061 }
6062
6063 my $refs = git_get_references();
6064 my $ref = format_ref_marker($refs, $hash_base);
6065 git_header_html();
6066 my $basedir = '';
6067 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6068 my @views_nav = ();
6069 if (defined $file_name) {
6070 push @views_nav,
6071 $cgi->a({-href => href(action=>"history", -replay=>1)},
6072 "history"),
6073 $cgi->a({-href => href(action=>"tree",
6074 hash_base=>"HEAD", file_name=>$file_name)},
6075 "HEAD"),
6076 }
6077 my $snapshot_links = format_snapshot_links($hash);
6078 if (defined $snapshot_links) {
6079 # FIXME: Should be available when we have no hash base as well.
6080 push @views_nav, $snapshot_links;
6081 }
6082 git_print_page_nav('tree','', $hash_base, undef, undef,
6083 join(' | ', @views_nav));
6084 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
6085 } else {
6086 undef $hash_base;
6087 print "<div class=\"page_nav\">\n";
6088 print "<br/><br/></div>\n";
6089 print "<div class=\"title\">".esc_html($hash)."</div>\n";
6090 }
6091 if (defined $file_name) {
6092 $basedir = $file_name;
6093 if ($basedir ne '' && substr($basedir, -1) ne '/') {
6094 $basedir .= '/';
6095 }
6096 git_print_page_path($file_name, 'tree', $hash_base);
6097 }
6098 print "<div class=\"page_body\">\n";
6099 print "<table class=\"tree\">\n";
6100 my $alternate = 1;
6101 # '..' (top directory) link if possible
6102 if (defined $hash_base &&
6103 defined $file_name && $file_name =~ m![^/]+$!) {
6104 if ($alternate) {
6105 print "<tr class=\"dark\">\n";
6106 } else {
6107 print "<tr class=\"light\">\n";
6108 }
6109 $alternate ^= 1;
6110
6111 my $up = $file_name;
6112 $up =~ s!/?[^/]+$!!;
6113 undef $up unless $up;
6114 # based on git_print_tree_entry
6115 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6116 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
6117 print '<td class="list">';
6118 print $cgi->a({-href => href(action=>"tree",
6119 hash_base=>$hash_base,
6120 file_name=>$up)},
6121 "..");
6122 print "</td>\n";
6123 print "<td class=\"link\"></td>\n";
6124
6125 print "</tr>\n";
6126 }
6127 foreach my $line (@entries) {
6128 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6129
6130 if ($alternate) {
6131 print "<tr class=\"dark\">\n";
6132 } else {
6133 print "<tr class=\"light\">\n";
6134 }
6135 $alternate ^= 1;
6136
6137 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6138
6139 print "</tr>\n";
6140 }
6141 print "</table>\n" .
6142 "</div>";
6143 git_footer_html();
6144 }
6145
6146 sub snapshot_name {
6147 my ($project, $hash) = @_;
6148
6149 # path/to/project.git -> project
6150 # path/to/project/.git -> project
6151 my $name = to_utf8($project);
6152 $name =~ s,([^/])/*\.git$,$1,;
6153 $name = basename($name);
6154 # sanitize name
6155 $name =~ s/[[:cntrl:]]/?/g;
6156
6157 my $ver = $hash;
6158 if ($hash =~ /^[0-9a-fA-F]+$/) {
6159 # shorten SHA-1 hash
6160 my $full_hash = git_get_full_hash($project, $hash);
6161 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6162 $ver = git_get_short_hash($project, $hash);
6163 }
6164 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6165 # tags don't need shortened SHA-1 hash
6166 $ver = $1;
6167 } else {
6168 # branches and other need shortened SHA-1 hash
6169 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6170 $ver = $1;
6171 }
6172 $ver .= '-' . git_get_short_hash($project, $hash);
6173 }
6174 # in case of hierarchical branch names
6175 $ver =~ s!/!.!g;
6176
6177 # name = project-version_string
6178 $name = "$name-$ver";
6179
6180 return wantarray ? ($name, $name) : $name;
6181 }
6182
6183 sub git_snapshot {
6184 my $format = $input_params{'snapshot_format'};
6185 if (!@snapshot_fmts) {
6186 die_error(403, "Snapshots not allowed");
6187 }
6188 # default to first supported snapshot format
6189 $format ||= $snapshot_fmts[0];
6190 if ($format !~ m/^[a-z0-9]+$/) {
6191 die_error(400, "Invalid snapshot format parameter");
6192 } elsif (!exists($known_snapshot_formats{$format})) {
6193 die_error(400, "Unknown snapshot format");
6194 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6195 die_error(403, "Snapshot format not allowed");
6196 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6197 die_error(403, "Unsupported snapshot format");
6198 }
6199
6200 my $type = git_get_type("$hash^{}");
6201 if (!$type) {
6202 die_error(404, 'Object does not exist');
6203 } elsif ($type eq 'blob') {
6204 die_error(400, 'Object is not a tree-ish');
6205 }
6206
6207 my ($name, $prefix) = snapshot_name($project, $hash);
6208 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6209 my $cmd = quote_command(
6210 git_cmd(), 'archive',
6211 "--format=$known_snapshot_formats{$format}{'format'}",
6212 "--prefix=$prefix/", $hash);
6213 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6214 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6215 }
6216
6217 $filename =~ s/(["\\])/\\$1/g;
6218 print $cgi->header(
6219 -type => $known_snapshot_formats{$format}{'type'},
6220 -content_disposition => 'inline; filename="' . $filename . '"',
6221 -status => '200 OK');
6222
6223 open my $fd, "-|", $cmd
6224 or die_error(500, "Execute git-archive failed");
6225 binmode STDOUT, ':raw';
6226 print <$fd>;
6227 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6228 close $fd;
6229 }
6230
6231 sub git_log_generic {
6232 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6233
6234 my $head = git_get_head_hash($project);
6235 if (!defined $base) {
6236 $base = $head;
6237 }
6238 if (!defined $page) {
6239 $page = 0;
6240 }
6241 my $refs = git_get_references();
6242
6243 my $commit_hash = $base;
6244 if (defined $parent) {
6245 $commit_hash = "$parent..$base";
6246 }
6247 my @commitlist =
6248 parse_commits($commit_hash, 101, (100 * $page),
6249 defined $file_name ? ($file_name, "--full-history") : ());
6250
6251 my $ftype;
6252 if (!defined $file_hash && defined $file_name) {
6253 # some commits could have deleted file in question,
6254 # and not have it in tree, but one of them has to have it
6255 for (my $i = 0; $i < @commitlist; $i++) {
6256 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6257 last if defined $file_hash;
6258 }
6259 }
6260 if (defined $file_hash) {
6261 $ftype = git_get_type($file_hash);
6262 }
6263 if (defined $file_name && !defined $ftype) {
6264 die_error(500, "Unknown type of object");
6265 }
6266 my %co;
6267 if (defined $file_name) {
6268 %co = parse_commit($base)
6269 or die_error(404, "Unknown commit object");
6270 }
6271
6272
6273 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6274 my $next_link = '';
6275 if ($#commitlist >= 100) {
6276 $next_link =
6277 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6278 -accesskey => "n", -title => "Alt-n"}, "next");
6279 }
6280 my $patch_max = gitweb_get_feature('patches');
6281 if ($patch_max && !defined $file_name) {
6282 if ($patch_max < 0 || @commitlist <= $patch_max) {
6283 $paging_nav .= " &sdot; " .
6284 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6285 "patches");
6286 }
6287 }
6288
6289 git_header_html();
6290 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6291 if (defined $file_name) {
6292 git_print_header_div('commit', esc_html($co{'title'}), $base);
6293 } else {
6294 git_print_header_div('summary', $project)
6295 }
6296 git_print_page_path($file_name, $ftype, $hash_base)
6297 if (defined $file_name);
6298
6299 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6300 $file_name, $file_hash, $ftype);
6301
6302 git_footer_html();
6303 }
6304
6305 sub git_log {
6306 git_log_generic('log', \&git_log_body,
6307 $hash, $hash_parent);
6308 }
6309
6310 sub git_commit {
6311 $hash ||= $hash_base || "HEAD";
6312 my %co = parse_commit($hash)
6313 or die_error(404, "Unknown commit object");
6314
6315 my $parent = $co{'parent'};
6316 my $parents = $co{'parents'}; # listref
6317
6318 # we need to prepare $formats_nav before any parameter munging
6319 my $formats_nav;
6320 if (!defined $parent) {
6321 # --root commitdiff
6322 $formats_nav .= '(initial)';
6323 } elsif (@$parents == 1) {
6324 # single parent commit
6325 $formats_nav .=
6326 '(parent: ' .
6327 $cgi->a({-href => href(action=>"commit",
6328 hash=>$parent)},
6329 esc_html(substr($parent, 0, 7))) .
6330 ')';
6331 } else {
6332 # merge commit
6333 $formats_nav .=
6334 '(merge: ' .
6335 join(' ', map {
6336 $cgi->a({-href => href(action=>"commit",
6337 hash=>$_)},
6338 esc_html(substr($_, 0, 7)));
6339 } @$parents ) .
6340 ')';
6341 }
6342 if (gitweb_check_feature('patches') && @$parents <= 1) {
6343 $formats_nav .= " | " .
6344 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6345 "patch");
6346 }
6347
6348 if (!defined $parent) {
6349 $parent = "--root";
6350 }
6351 my @difftree;
6352 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6353 @diff_opts,
6354 (@$parents <= 1 ? $parent : '-c'),
6355 $hash, "--"
6356 or die_error(500, "Open git-diff-tree failed");
6357 @difftree = map { chomp; $_ } <$fd>;
6358 close $fd or die_error(404, "Reading git-diff-tree failed");
6359
6360 # non-textual hash id's can be cached
6361 my $expires;
6362 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6363 $expires = "+1d";
6364 }
6365 my $refs = git_get_references();
6366 my $ref = format_ref_marker($refs, $co{'id'});
6367
6368 git_header_html(undef, $expires);
6369 git_print_page_nav('commit', '',
6370 $hash, $co{'tree'}, $hash,
6371 $formats_nav);
6372
6373 if (defined $co{'parent'}) {
6374 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6375 } else {
6376 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6377 }
6378 print "<div class=\"title_text\">\n" .
6379 "<table class=\"object_header\">\n";
6380 git_print_authorship_rows(\%co);
6381 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6382 print "<tr>" .
6383 "<td>tree</td>" .
6384 "<td class=\"sha1\">" .
6385 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6386 class => "list"}, $co{'tree'}) .
6387 "</td>" .
6388 "<td class=\"link\">" .
6389 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6390 "tree");
6391 my $snapshot_links = format_snapshot_links($hash);
6392 if (defined $snapshot_links) {
6393 print " | " . $snapshot_links;
6394 }
6395 print "</td>" .
6396 "</tr>\n";
6397
6398 foreach my $par (@$parents) {
6399 print "<tr>" .
6400 "<td>parent</td>" .
6401 "<td class=\"sha1\">" .
6402 $cgi->a({-href => href(action=>"commit", hash=>$par),
6403 class => "list"}, $par) .
6404 "</td>" .
6405 "<td class=\"link\">" .
6406 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6407 " | " .
6408 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6409 "</td>" .
6410 "</tr>\n";
6411 }
6412 print "</table>".
6413 "</div>\n";
6414
6415 print "<div class=\"page_body\">\n";
6416 git_print_log($co{'comment'});
6417 print "</div>\n";
6418
6419 git_difftree_body(\@difftree, $hash, @$parents);
6420
6421 git_footer_html();
6422 }
6423
6424 sub git_object {
6425 # object is defined by:
6426 # - hash or hash_base alone
6427 # - hash_base and file_name
6428 my $type;
6429
6430 # - hash or hash_base alone
6431 if ($hash || ($hash_base && !defined $file_name)) {
6432 my $object_id = $hash || $hash_base;
6433
6434 open my $fd, "-|", quote_command(
6435 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6436 or die_error(404, "Object does not exist");
6437 $type = <$fd>;
6438 chomp $type;
6439 close $fd
6440 or die_error(404, "Object does not exist");
6441
6442 # - hash_base and file_name
6443 } elsif ($hash_base && defined $file_name) {
6444 $file_name =~ s,/+$,,;
6445
6446 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6447 or die_error(404, "Base object does not exist");
6448
6449 # here errors should not hapen
6450 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6451 or die_error(500, "Open git-ls-tree failed");
6452 my $line = <$fd>;
6453 close $fd;
6454
6455 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6456 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6457 die_error(404, "File or directory for given base does not exist");
6458 }
6459 $type = $2;
6460 $hash = $3;
6461 } else {
6462 die_error(400, "Not enough information to find object");
6463 }
6464
6465 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6466 hash=>$hash, hash_base=>$hash_base,
6467 file_name=>$file_name),
6468 -status => '302 Found');
6469 }
6470
6471 sub git_blobdiff {
6472 my $format = shift || 'html';
6473
6474 my $fd;
6475 my @difftree;
6476 my %diffinfo;
6477 my $expires;
6478
6479 # preparing $fd and %diffinfo for git_patchset_body
6480 # new style URI
6481 if (defined $hash_base && defined $hash_parent_base) {
6482 if (defined $file_name) {
6483 # read raw output
6484 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6485 $hash_parent_base, $hash_base,
6486 "--", (defined $file_parent ? $file_parent : ()), $file_name
6487 or die_error(500, "Open git-diff-tree failed");
6488 @difftree = map { chomp; $_ } <$fd>;
6489 close $fd
6490 or die_error(404, "Reading git-diff-tree failed");
6491 @difftree
6492 or die_error(404, "Blob diff not found");
6493
6494 } elsif (defined $hash &&
6495 $hash =~ /[0-9a-fA-F]{40}/) {
6496 # try to find filename from $hash
6497
6498 # read filtered raw output
6499 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6500 $hash_parent_base, $hash_base, "--"
6501 or die_error(500, "Open git-diff-tree failed");
6502 @difftree =
6503 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6504 # $hash == to_id
6505 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6506 map { chomp; $_ } <$fd>;
6507 close $fd
6508 or die_error(404, "Reading git-diff-tree failed");
6509 @difftree
6510 or die_error(404, "Blob diff not found");
6511
6512 } else {
6513 die_error(400, "Missing one of the blob diff parameters");
6514 }
6515
6516 if (@difftree > 1) {
6517 die_error(400, "Ambiguous blob diff specification");
6518 }
6519
6520 %diffinfo = parse_difftree_raw_line($difftree[0]);
6521 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6522 $file_name ||= $diffinfo{'to_file'};
6523
6524 $hash_parent ||= $diffinfo{'from_id'};
6525 $hash ||= $diffinfo{'to_id'};
6526
6527 # non-textual hash id's can be cached
6528 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6529 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6530 $expires = '+1d';
6531 }
6532
6533 # open patch output
6534 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6535 '-p', ($format eq 'html' ? "--full-index" : ()),
6536 $hash_parent_base, $hash_base,
6537 "--", (defined $file_parent ? $file_parent : ()), $file_name
6538 or die_error(500, "Open git-diff-tree failed");
6539 }
6540
6541 # old/legacy style URI -- not generated anymore since 1.4.3.
6542 if (!%diffinfo) {
6543 die_error('404 Not Found', "Missing one of the blob diff parameters")
6544 }
6545
6546 # header
6547 if ($format eq 'html') {
6548 my $formats_nav =
6549 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6550 "raw");
6551 git_header_html(undef, $expires);
6552 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6553 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6554 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6555 } else {
6556 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6557 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
6558 }
6559 if (defined $file_name) {
6560 git_print_page_path($file_name, "blob", $hash_base);
6561 } else {
6562 print "<div class=\"page_path\"></div>\n";
6563 }
6564
6565 } elsif ($format eq 'plain') {
6566 print $cgi->header(
6567 -type => 'text/plain',
6568 -charset => 'utf-8',
6569 -expires => $expires,
6570 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6571
6572 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6573
6574 } else {
6575 die_error(400, "Unknown blobdiff format");
6576 }
6577
6578 # patch
6579 if ($format eq 'html') {
6580 print "<div class=\"page_body\">\n";
6581
6582 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6583 close $fd;
6584
6585 print "</div>\n"; # class="page_body"
6586 git_footer_html();
6587
6588 } else {
6589 while (my $line = <$fd>) {
6590 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6591 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6592
6593 print $line;
6594
6595 last if $line =~ m!^\+\+\+!;
6596 }
6597 local $/ = undef;
6598 print <$fd>;
6599 close $fd;
6600 }
6601 }
6602
6603 sub git_blobdiff_plain {
6604 git_blobdiff('plain');
6605 }
6606
6607 sub git_commitdiff {
6608 my %params = @_;
6609 my $format = $params{-format} || 'html';
6610
6611 my ($patch_max) = gitweb_get_feature('patches');
6612 if ($format eq 'patch') {
6613 die_error(403, "Patch view not allowed") unless $patch_max;
6614 }
6615
6616 $hash ||= $hash_base || "HEAD";
6617 my %co = parse_commit($hash)
6618 or die_error(404, "Unknown commit object");
6619
6620 # choose format for commitdiff for merge
6621 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6622 $hash_parent = '--cc';
6623 }
6624 # we need to prepare $formats_nav before almost any parameter munging
6625 my $formats_nav;
6626 if ($format eq 'html') {
6627 $formats_nav =
6628 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6629 "raw");
6630 if ($patch_max && @{$co{'parents'}} <= 1) {
6631 $formats_nav .= " | " .
6632 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6633 "patch");
6634 }
6635
6636 if (defined $hash_parent &&
6637 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6638 # commitdiff with two commits given
6639 my $hash_parent_short = $hash_parent;
6640 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6641 $hash_parent_short = substr($hash_parent, 0, 7);
6642 }
6643 $formats_nav .=
6644 ' (from';
6645 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6646 if ($co{'parents'}[$i] eq $hash_parent) {
6647 $formats_nav .= ' parent ' . ($i+1);
6648 last;
6649 }
6650 }
6651 $formats_nav .= ': ' .
6652 $cgi->a({-href => href(action=>"commitdiff",
6653 hash=>$hash_parent)},
6654 esc_html($hash_parent_short)) .
6655 ')';
6656 } elsif (!$co{'parent'}) {
6657 # --root commitdiff
6658 $formats_nav .= ' (initial)';
6659 } elsif (scalar @{$co{'parents'}} == 1) {
6660 # single parent commit
6661 $formats_nav .=
6662 ' (parent: ' .
6663 $cgi->a({-href => href(action=>"commitdiff",
6664 hash=>$co{'parent'})},
6665 esc_html(substr($co{'parent'}, 0, 7))) .
6666 ')';
6667 } else {
6668 # merge commit
6669 if ($hash_parent eq '--cc') {
6670 $formats_nav .= ' | ' .
6671 $cgi->a({-href => href(action=>"commitdiff",
6672 hash=>$hash, hash_parent=>'-c')},
6673 'combined');
6674 } else { # $hash_parent eq '-c'
6675 $formats_nav .= ' | ' .
6676 $cgi->a({-href => href(action=>"commitdiff",
6677 hash=>$hash, hash_parent=>'--cc')},
6678 'compact');
6679 }
6680 $formats_nav .=
6681 ' (merge: ' .
6682 join(' ', map {
6683 $cgi->a({-href => href(action=>"commitdiff",
6684 hash=>$_)},
6685 esc_html(substr($_, 0, 7)));
6686 } @{$co{'parents'}} ) .
6687 ')';
6688 }
6689 }
6690
6691 my $hash_parent_param = $hash_parent;
6692 if (!defined $hash_parent_param) {
6693 # --cc for multiple parents, --root for parentless
6694 $hash_parent_param =
6695 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6696 }
6697
6698 # read commitdiff
6699 my $fd;
6700 my @difftree;
6701 if ($format eq 'html') {
6702 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6703 "--no-commit-id", "--patch-with-raw", "--full-index",
6704 $hash_parent_param, $hash, "--"
6705 or die_error(500, "Open git-diff-tree failed");
6706
6707 while (my $line = <$fd>) {
6708 chomp $line;
6709 # empty line ends raw part of diff-tree output
6710 last unless $line;
6711 push @difftree, scalar parse_difftree_raw_line($line);
6712 }
6713
6714 } elsif ($format eq 'plain') {
6715 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6716 '-p', $hash_parent_param, $hash, "--"
6717 or die_error(500, "Open git-diff-tree failed");
6718 } elsif ($format eq 'patch') {
6719 # For commit ranges, we limit the output to the number of
6720 # patches specified in the 'patches' feature.
6721 # For single commits, we limit the output to a single patch,
6722 # diverging from the git-format-patch default.
6723 my @commit_spec = ();
6724 if ($hash_parent) {
6725 if ($patch_max > 0) {
6726 push @commit_spec, "-$patch_max";
6727 }
6728 push @commit_spec, '-n', "$hash_parent..$hash";
6729 } else {
6730 if ($params{-single}) {
6731 push @commit_spec, '-1';
6732 } else {
6733 if ($patch_max > 0) {
6734 push @commit_spec, "-$patch_max";
6735 }
6736 push @commit_spec, "-n";
6737 }
6738 push @commit_spec, '--root', $hash;
6739 }
6740 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6741 '--encoding=utf8', '--stdout', @commit_spec
6742 or die_error(500, "Open git-format-patch failed");
6743 } else {
6744 die_error(400, "Unknown commitdiff format");
6745 }
6746
6747 # non-textual hash id's can be cached
6748 my $expires;
6749 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6750 $expires = "+1d";
6751 }
6752
6753 # write commit message
6754 if ($format eq 'html') {
6755 my $refs = git_get_references();
6756 my $ref = format_ref_marker($refs, $co{'id'});
6757
6758 git_header_html(undef, $expires);
6759 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6760 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6761 print "<div class=\"title_text\">\n" .
6762 "<table class=\"object_header\">\n";
6763 git_print_authorship_rows(\%co);
6764 print "</table>".
6765 "</div>\n";
6766 print "<div class=\"page_body\">\n";
6767 if (@{$co{'comment'}} > 1) {
6768 print "<div class=\"log\">\n";
6769 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6770 print "</div>\n"; # class="log"
6771 }
6772
6773 } elsif ($format eq 'plain') {
6774 my $refs = git_get_references("tags");
6775 my $tagname = git_get_rev_name_tags($hash);
6776 my $filename = basename($project) . "-$hash.patch";
6777
6778 print $cgi->header(
6779 -type => 'text/plain',
6780 -charset => 'utf-8',
6781 -expires => $expires,
6782 -content_disposition => 'inline; filename="' . "$filename" . '"');
6783 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6784 print "From: " . to_utf8($co{'author'}) . "\n";
6785 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6786 print "Subject: " . to_utf8($co{'title'}) . "\n";
6787
6788 print "X-Git-Tag: $tagname\n" if $tagname;
6789 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6790
6791 foreach my $line (@{$co{'comment'}}) {
6792 print to_utf8($line) . "\n";
6793 }
6794 print "---\n\n";
6795 } elsif ($format eq 'patch') {
6796 my $filename = basename($project) . "-$hash.patch";
6797
6798 print $cgi->header(
6799 -type => 'text/plain',
6800 -charset => 'utf-8',
6801 -expires => $expires,
6802 -content_disposition => 'inline; filename="' . "$filename" . '"');
6803 }
6804
6805 # write patch
6806 if ($format eq 'html') {
6807 my $use_parents = !defined $hash_parent ||
6808 $hash_parent eq '-c' || $hash_parent eq '--cc';
6809 git_difftree_body(\@difftree, $hash,
6810 $use_parents ? @{$co{'parents'}} : $hash_parent);
6811 print "<br/>\n";
6812
6813 git_patchset_body($fd, \@difftree, $hash,
6814 $use_parents ? @{$co{'parents'}} : $hash_parent);
6815 close $fd;
6816 print "</div>\n"; # class="page_body"
6817 git_footer_html();
6818
6819 } elsif ($format eq 'plain') {
6820 local $/ = undef;
6821 print <$fd>;
6822 close $fd
6823 or print "Reading git-diff-tree failed\n";
6824 } elsif ($format eq 'patch') {
6825 local $/ = undef;
6826 print <$fd>;
6827 close $fd
6828 or print "Reading git-format-patch failed\n";
6829 }
6830 }
6831
6832 sub git_commitdiff_plain {
6833 git_commitdiff(-format => 'plain');
6834 }
6835
6836 # format-patch-style patches
6837 sub git_patch {
6838 git_commitdiff(-format => 'patch', -single => 1);
6839 }
6840
6841 sub git_patches {
6842 git_commitdiff(-format => 'patch');
6843 }
6844
6845 sub git_history {
6846 git_log_generic('history', \&git_history_body,
6847 $hash_base, $hash_parent_base,
6848 $file_name, $hash);
6849 }
6850
6851 sub git_search {
6852 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6853 if (!defined $searchtext) {
6854 die_error(400, "Text field is empty");
6855 }
6856 if (!defined $hash) {
6857 $hash = git_get_head_hash($project);
6858 }
6859 my %co = parse_commit($hash);
6860 if (!%co) {
6861 die_error(404, "Unknown commit object");
6862 }
6863 if (!defined $page) {
6864 $page = 0;
6865 }
6866
6867 $searchtype ||= 'commit';
6868 if ($searchtype eq 'pickaxe') {
6869 # pickaxe may take all resources of your box and run for several minutes
6870 # with every query - so decide by yourself how public you make this feature
6871 gitweb_check_feature('pickaxe')
6872 or die_error(403, "Pickaxe is disabled");
6873 }
6874 if ($searchtype eq 'grep') {
6875 gitweb_check_feature('grep')[0]
6876 or die_error(403, "Grep is disabled");
6877 }
6878
6879 git_header_html();
6880
6881 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6882 my $greptype;
6883 if ($searchtype eq 'commit') {
6884 $greptype = "--grep=";
6885 } elsif ($searchtype eq 'author') {
6886 $greptype = "--author=";
6887 } elsif ($searchtype eq 'committer') {
6888 $greptype = "--committer=";
6889 }
6890 $greptype .= $searchtext;
6891 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6892 $greptype, '--regexp-ignore-case',
6893 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6894
6895 my $paging_nav = '';
6896 if ($page > 0) {
6897 $paging_nav .=
6898 $cgi->a({-href => href(action=>"search", hash=>$hash,
6899 searchtext=>$searchtext,
6900 searchtype=>$searchtype)},
6901 "first");
6902 $paging_nav .= " &sdot; " .
6903 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6904 -accesskey => "p", -title => "Alt-p"}, "prev");
6905 } else {
6906 $paging_nav .= "first";
6907 $paging_nav .= " &sdot; prev";
6908 }
6909 my $next_link = '';
6910 if ($#commitlist >= 100) {
6911 $next_link =
6912 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6913 -accesskey => "n", -title => "Alt-n"}, "next");
6914 $paging_nav .= " &sdot; $next_link";
6915 } else {
6916 $paging_nav .= " &sdot; next";
6917 }
6918
6919 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6920 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6921 if ($page == 0 && !@commitlist) {
6922 print "<p>No match.</p>\n";
6923 } else {
6924 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6925 }
6926 }
6927
6928 if ($searchtype eq 'pickaxe') {
6929 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6930 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6931
6932 print "<table class=\"pickaxe search\">\n";
6933 my $alternate = 1;
6934 local $/ = "\n";
6935 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6936 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6937 ($search_use_regexp ? '--pickaxe-regex' : ());
6938 undef %co;
6939 my @files;
6940 while (my $line = <$fd>) {
6941 chomp $line;
6942 next unless $line;
6943
6944 my %set = parse_difftree_raw_line($line);
6945 if (defined $set{'commit'}) {
6946 # finish previous commit
6947 if (%co) {
6948 print "</td>\n" .
6949 "<td class=\"link\">" .
6950 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6951 " | " .
6952 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6953 print "</td>\n" .
6954 "</tr>\n";
6955 }
6956
6957 if ($alternate) {
6958 print "<tr class=\"dark\">\n";
6959 } else {
6960 print "<tr class=\"light\">\n";
6961 }
6962 $alternate ^= 1;
6963 %co = parse_commit($set{'commit'});
6964 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6965 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6966 "<td><i>$author</i></td>\n" .
6967 "<td>" .
6968 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6969 -class => "list subject"},
6970 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6971 } elsif (defined $set{'to_id'}) {
6972 next if ($set{'to_id'} =~ m/^0{40}$/);
6973
6974 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6975 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6976 -class => "list"},
6977 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6978 "<br/>\n";
6979 }
6980 }
6981 close $fd;
6982
6983 # finish last commit (warning: repetition!)
6984 if (%co) {
6985 print "</td>\n" .
6986 "<td class=\"link\">" .
6987 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6988 " | " .
6989 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6990 print "</td>\n" .
6991 "</tr>\n";
6992 }
6993
6994 print "</table>\n";
6995 }
6996
6997 if ($searchtype eq 'grep') {
6998 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6999 git_print_header_div('commit', esc_html($co{'title'}), $hash);
7000
7001 print "<table class=\"grep_search\">\n";
7002 my $alternate = 1;
7003 my $matches = 0;
7004 local $/ = "\n";
7005 open my $fd, "-|", git_cmd(), 'grep', '-n',
7006 $search_use_regexp ? ('-E', '-i') : '-F',
7007 $searchtext, $co{'tree'};
7008 my $lastfile = '';
7009 while (my $line = <$fd>) {
7010 chomp $line;
7011 my ($file, $lno, $ltext, $binary);
7012 last if ($matches++ > 1000);
7013 if ($line =~ /^Binary file (.+) matches$/) {
7014 $file = $1;
7015 $binary = 1;
7016 } else {
7017 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
7018 }
7019 if ($file ne $lastfile) {
7020 $lastfile and print "</td></tr>\n";
7021 if ($alternate++) {
7022 print "<tr class=\"dark\">\n";
7023 } else {
7024 print "<tr class=\"light\">\n";
7025 }
7026 print "<td class=\"list\">".
7027 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
7028 file_name=>"$file"),
7029 -class => "list"}, esc_path($file));
7030 print "</td><td>\n";
7031 $lastfile = $file;
7032 }
7033 if ($binary) {
7034 print "<div class=\"binary\">Binary file</div>\n";
7035 } else {
7036 $ltext = untabify($ltext);
7037 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
7038 $ltext = esc_html($1, -nbsp=>1);
7039 $ltext .= '<span class="match">';
7040 $ltext .= esc_html($2, -nbsp=>1);
7041 $ltext .= '</span>';
7042 $ltext .= esc_html($3, -nbsp=>1);
7043 } else {
7044 $ltext = esc_html($ltext, -nbsp=>1);
7045 }
7046 print "<div class=\"pre\">" .
7047 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
7048 file_name=>"$file").'#l'.$lno,
7049 -class => "linenr"}, sprintf('%4i', $lno))
7050 . ' ' . $ltext . "</div>\n";
7051 }
7052 }
7053 if ($lastfile) {
7054 print "</td></tr>\n";
7055 if ($matches > 1000) {
7056 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
7057 }
7058 } else {
7059 print "<div class=\"diff nodifferences\">No matches found</div>\n";
7060 }
7061 close $fd;
7062
7063 print "</table>\n";
7064 }
7065 git_footer_html();
7066 }
7067
7068 sub git_search_help {
7069 git_header_html();
7070 git_print_page_nav('','', $hash,$hash,$hash);
7071 print <<EOT;
7072 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7073 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7074 the pattern entered is recognized as the POSIX extended
7075 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7076 insensitive).</p>
7077 <dl>
7078 <dt><b>commit</b></dt>
7079 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7080 EOT
7081 my $have_grep = gitweb_check_feature('grep');
7082 if ($have_grep) {
7083 print <<EOT;
7084 <dt><b>grep</b></dt>
7085 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7086 a different one) are searched for the given pattern. On large trees, this search can take
7087 a while and put some strain on the server, so please use it with some consideration. Note that
7088 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7089 case-sensitive.</dd>
7090 EOT
7091 }
7092 print <<EOT;
7093 <dt><b>author</b></dt>
7094 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7095 <dt><b>committer</b></dt>
7096 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7097 EOT
7098 my $have_pickaxe = gitweb_check_feature('pickaxe');
7099 if ($have_pickaxe) {
7100 print <<EOT;
7101 <dt><b>pickaxe</b></dt>
7102 <dd>All commits that caused the string to appear or disappear from any file (changes that
7103 added, removed or "modified" the string) will be listed. This search can take a while and
7104 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7105 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7106 EOT
7107 }
7108 print "</dl>\n";
7109 git_footer_html();
7110 }
7111
7112 sub git_shortlog {
7113 git_log_generic('shortlog', \&git_shortlog_body,
7114 $hash, $hash_parent);
7115 }
7116
7117 ## ......................................................................
7118 ## feeds (RSS, Atom; OPML)
7119
7120 sub git_feed {
7121 my $format = shift || 'atom';
7122 my $have_blame = gitweb_check_feature('blame');
7123
7124 # Atom: http://www.atomenabled.org/developers/syndication/
7125 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7126 if ($format ne 'rss' && $format ne 'atom') {
7127 die_error(400, "Unknown web feed format");
7128 }
7129
7130 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7131 my $head = $hash || 'HEAD';
7132 my @commitlist = parse_commits($head, 150, 0, $file_name);
7133
7134 my %latest_commit;
7135 my %latest_date;
7136 my $content_type = "application/$format+xml";
7137 if (defined $cgi->http('HTTP_ACCEPT') &&
7138 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7139 # browser (feed reader) prefers text/xml
7140 $content_type = 'text/xml';
7141 }
7142 if (defined($commitlist[0])) {
7143 %latest_commit = %{$commitlist[0]};
7144 my $latest_epoch = $latest_commit{'committer_epoch'};
7145 %latest_date = parse_date($latest_epoch, $latest_commit{'comitter_tz'});
7146 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7147 if (defined $if_modified) {
7148 my $since;
7149 if (eval { require HTTP::Date; 1; }) {
7150 $since = HTTP::Date::str2time($if_modified);
7151 } elsif (eval { require Time::ParseDate; 1; }) {
7152 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7153 }
7154 if (defined $since && $latest_epoch <= $since) {
7155 print $cgi->header(
7156 -type => $content_type,
7157 -charset => 'utf-8',
7158 -last_modified => $latest_date{'rfc2822'},
7159 -status => '304 Not Modified');
7160 return;
7161 }
7162 }
7163 print $cgi->header(
7164 -type => $content_type,
7165 -charset => 'utf-8',
7166 -last_modified => $latest_date{'rfc2822'});
7167 } else {
7168 print $cgi->header(
7169 -type => $content_type,
7170 -charset => 'utf-8');
7171 }
7172
7173 # Optimization: skip generating the body if client asks only
7174 # for Last-Modified date.
7175 return if ($cgi->request_method() eq 'HEAD');
7176
7177 # header variables
7178 my $title = "$site_name - $project/$action";
7179 my $feed_type = 'log';
7180 if (defined $hash) {
7181 $title .= " - '$hash'";
7182 $feed_type = 'branch log';
7183 if (defined $file_name) {
7184 $title .= " :: $file_name";
7185 $feed_type = 'history';
7186 }
7187 } elsif (defined $file_name) {
7188 $title .= " - $file_name";
7189 $feed_type = 'history';
7190 }
7191 $title .= " $feed_type";
7192 my $descr = git_get_project_description($project);
7193 if (defined $descr) {
7194 $descr = esc_html($descr);
7195 } else {
7196 $descr = "$project " .
7197 ($format eq 'rss' ? 'RSS' : 'Atom') .
7198 " feed";
7199 }
7200 my $owner = git_get_project_owner($project);
7201 $owner = esc_html($owner);
7202
7203 #header
7204 my $alt_url;
7205 if (defined $file_name) {
7206 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7207 } elsif (defined $hash) {
7208 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7209 } else {
7210 $alt_url = href(-full=>1, action=>"summary");
7211 }
7212 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7213 if ($format eq 'rss') {
7214 print <<XML;
7215 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7216 <channel>
7217 XML
7218 print "<title>$title</title>\n" .
7219 "<link>$alt_url</link>\n" .
7220 "<description>$descr</description>\n" .
7221 "<language>en</language>\n" .
7222 # project owner is responsible for 'editorial' content
7223 "<managingEditor>$owner</managingEditor>\n";
7224 if (defined $logo || defined $favicon) {
7225 # prefer the logo to the favicon, since RSS
7226 # doesn't allow both
7227 my $img = esc_url($logo || $favicon);
7228 print "<image>\n" .
7229 "<url>$img</url>\n" .
7230 "<title>$title</title>\n" .
7231 "<link>$alt_url</link>\n" .
7232 "</image>\n";
7233 }
7234 if (%latest_date) {
7235 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7236 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7237 }
7238 print "<generator>gitweb v.$version/$git_version</generator>\n";
7239 } elsif ($format eq 'atom') {
7240 print <<XML;
7241 <feed xmlns="http://www.w3.org/2005/Atom">
7242 XML
7243 print "<title>$title</title>\n" .
7244 "<subtitle>$descr</subtitle>\n" .
7245 '<link rel="alternate" type="text/html" href="' .
7246 $alt_url . '" />' . "\n" .
7247 '<link rel="self" type="' . $content_type . '" href="' .
7248 $cgi->self_url() . '" />' . "\n" .
7249 "<id>" . href(-full=>1) . "</id>\n" .
7250 # use project owner for feed author
7251 "<author><name>$owner</name></author>\n";
7252 if (defined $favicon) {
7253 print "<icon>" . esc_url($favicon) . "</icon>\n";
7254 }
7255 if (defined $logo) {
7256 # not twice as wide as tall: 72 x 27 pixels
7257 print "<logo>" . esc_url($logo) . "</logo>\n";
7258 }
7259 if (! %latest_date) {
7260 # dummy date to keep the feed valid until commits trickle in:
7261 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7262 } else {
7263 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7264 }
7265 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7266 }
7267
7268 # contents
7269 for (my $i = 0; $i <= $#commitlist; $i++) {
7270 my %co = %{$commitlist[$i]};
7271 my $commit = $co{'id'};
7272 # we read 150, we always show 30 and the ones more recent than 48 hours
7273 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7274 last;
7275 }
7276 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
7277
7278 # get list of changed files
7279 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7280 $co{'parent'} || "--root",
7281 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7282 or next;
7283 my @difftree = map { chomp; $_ } <$fd>;
7284 close $fd
7285 or next;
7286
7287 # print element (entry, item)
7288 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7289 if ($format eq 'rss') {
7290 print "<item>\n" .
7291 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7292 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7293 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7294 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7295 "<link>$co_url</link>\n" .
7296 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7297 "<content:encoded>" .
7298 "<![CDATA[\n";
7299 } elsif ($format eq 'atom') {
7300 print "<entry>\n" .
7301 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7302 "<updated>$cd{'iso-8601'}</updated>\n" .
7303 "<author>\n" .
7304 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7305 if ($co{'author_email'}) {
7306 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7307 }
7308 print "</author>\n" .
7309 # use committer for contributor
7310 "<contributor>\n" .
7311 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7312 if ($co{'committer_email'}) {
7313 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7314 }
7315 print "</contributor>\n" .
7316 "<published>$cd{'iso-8601'}</published>\n" .
7317 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7318 "<id>$co_url</id>\n" .
7319 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7320 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7321 }
7322 my $comment = $co{'comment'};
7323 print "<pre>\n";
7324 foreach my $line (@$comment) {
7325 $line = esc_html($line);
7326 print "$line\n";
7327 }
7328 print "</pre><ul>\n";
7329 foreach my $difftree_line (@difftree) {
7330 my %difftree = parse_difftree_raw_line($difftree_line);
7331 next if !$difftree{'from_id'};
7332
7333 my $file = $difftree{'file'} || $difftree{'to_file'};
7334
7335 print "<li>" .
7336 "[" .
7337 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7338 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7339 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7340 file_name=>$file, file_parent=>$difftree{'from_file'}),
7341 -title => "diff"}, 'D');
7342 if ($have_blame) {
7343 print $cgi->a({-href => href(-full=>1, action=>"blame",
7344 file_name=>$file, hash_base=>$commit),
7345 -title => "blame"}, 'B');
7346 }
7347 # if this is not a feed of a file history
7348 if (!defined $file_name || $file_name ne $file) {
7349 print $cgi->a({-href => href(-full=>1, action=>"history",
7350 file_name=>$file, hash=>$commit),
7351 -title => "history"}, 'H');
7352 }
7353 $file = esc_path($file);
7354 print "] ".
7355 "$file</li>\n";
7356 }
7357 if ($format eq 'rss') {
7358 print "</ul>]]>\n" .
7359 "</content:encoded>\n" .
7360 "</item>\n";
7361 } elsif ($format eq 'atom') {
7362 print "</ul>\n</div>\n" .
7363 "</content>\n" .
7364 "</entry>\n";
7365 }
7366 }
7367
7368 # end of feed
7369 if ($format eq 'rss') {
7370 print "</channel>\n</rss>\n";
7371 } elsif ($format eq 'atom') {
7372 print "</feed>\n";
7373 }
7374 }
7375
7376 sub git_rss {
7377 git_feed('rss');
7378 }
7379
7380 sub git_atom {
7381 git_feed('atom');
7382 }
7383
7384 sub git_opml {
7385 my @list = git_get_projects_list();
7386
7387 print $cgi->header(
7388 -type => 'text/xml',
7389 -charset => 'utf-8',
7390 -content_disposition => 'inline; filename="opml.xml"');
7391
7392 print <<XML;
7393 <?xml version="1.0" encoding="utf-8"?>
7394 <opml version="1.0">
7395 <head>
7396 <title>$site_name OPML Export</title>
7397 </head>
7398 <body>
7399 <outline text="git RSS feeds">
7400 XML
7401
7402 foreach my $pr (@list) {
7403 my %proj = %$pr;
7404 my $head = git_get_head_hash($proj{'path'});
7405 if (!defined $head) {
7406 next;
7407 }
7408 $git_dir = "$projectroot/$proj{'path'}";
7409 my %co = parse_commit($head);
7410 if (!%co) {
7411 next;
7412 }
7413
7414 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7415 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7416 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7417 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7418 }
7419 print <<XML;
7420 </outline>
7421 </body>
7422 </opml>
7423 XML
7424 }
This page took 6.601043 seconds and 3 git commands to generate.