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