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