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