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