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