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