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