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