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