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