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