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