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