gitweb: linkify author/committer names with search
[git/git.git] / gitweb / gitweb.perl
CommitLineData
161332a5
KS
1#!/usr/bin/perl
2
c994d620 3# gitweb - simple web interface to track changes in git repositories
22fafb99 4#
00cd0794
KS
5# (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6# (C) 2005, Christian Gierke
823d5dc8 7#
d8f1c5c2 8# This program is licensed under the GPLv2
161332a5
KS
9
10use strict;
11use warnings;
19806691 12use CGI qw(:standard :escapeHTML -nosticky);
7403d50b 13use CGI::Util qw(unescape);
161332a5 14use CGI::Carp qw(fatalsToBrowser);
40c13813 15use Encode;
b87d78d6 16use Fcntl ':mode';
7a13b999 17use File::Find qw();
cb9c6e5b 18use File::Basename qw(basename);
10bb9036 19binmode STDOUT, ':utf8';
161332a5 20
b1f5f64f 21BEGIN {
3be8e720 22 CGI->compile() if $ENV{'MOD_PERL'};
b1f5f64f
JN
23}
24
4a87b43e 25our $cgi = new CGI;
06c084d2 26our $version = "++GIT_VERSION++";
4a87b43e
DS
27our $my_url = $cgi->url();
28our $my_uri = $cgi->url(-absolute => 1);
3e029299 29
81d3fe9f
GB
30# Base URL for relative URLs in gitweb ($logo, $favicon, ...),
31# needed and used only for URLs with nonempty PATH_INFO
32our $base_url = $my_url;
33
34# When the script is used as DirectoryIndex, the URL does not contain the name
35# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
36# have to do it ourselves. We make $path_info global because it's also used
37# later on.
38#
39# Another issue with the script being the DirectoryIndex is that the resulting
40# $my_url data is not the full script URL: this is good, because we want
41# generated links to keep implying the script name if it wasn't explicitly
42# indicated in the URL we're handling, but it means that $my_url cannot be used
43# as base URL.
44# Therefore, if we needed to strip PATH_INFO, then we know that we have
45# to build the base URL ourselves:
dde80d9c 46our $path_info = $ENV{"PATH_INFO"};
1b2d297e 47if ($path_info) {
81d3fe9f
GB
48 if ($my_url =~ s,\Q$path_info\E$,, &&
49 $my_uri =~ s,\Q$path_info\E$,, &&
50 defined $ENV{'SCRIPT_NAME'}) {
51 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
52 }
b65910fe
GB
53}
54
e130ddaa
AT
55# core git executable to use
56# this can just be "git" if your webserver has a sensible PATH
06c084d2 57our $GIT = "++GIT_BINDIR++/git";
3f7f2710 58
b87d78d6 59# absolute fs-path which will be prepended to the project path
4a87b43e 60#our $projectroot = "/pub/scm";
06c084d2 61our $projectroot = "++GITWEB_PROJECTROOT++";
b87d78d6 62
ca5e9495
LL
63# fs traversing limit for getting project list
64# the number is relative to the projectroot
65our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
66
b87d78d6 67# target of the home link on top of all pages
6132b7e4 68our $home_link = $my_uri || "/";
b87d78d6 69
2de21fac
YS
70# string of the home link on top of all pages
71our $home_link_str = "++GITWEB_HOME_LINK_STR++";
72
49da1daf
AT
73# name of your site or organization to appear in page titles
74# replace this with something more descriptive for clearer bookmarks
8be2890c
PB
75our $site_name = "++GITWEB_SITENAME++"
76 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
49da1daf 77
b2d3476e
AC
78# filename of html text to include at top of each page
79our $site_header = "++GITWEB_SITE_HEADER++";
8ab1da2c 80# html text to include at home page
06c084d2 81our $home_text = "++GITWEB_HOMETEXT++";
b2d3476e
AC
82# filename of html text to include at bottom of each page
83our $site_footer = "++GITWEB_SITE_FOOTER++";
84
85# URI of stylesheets
86our @stylesheets = ("++GITWEB_CSS++");
887a612f
PB
87# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
88our $stylesheet = undef;
9a7a62ff 89# URI of GIT logo (72x27 size)
06c084d2 90our $logo = "++GITWEB_LOGO++";
0b5deba1
JN
91# URI of GIT favicon, assumed to be image/png type
92our $favicon = "++GITWEB_FAVICON++";
aedd9425 93
9a7a62ff
JN
94# URI and label (title) of GIT logo link
95#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
96#our $logo_label = "git documentation";
69fb8283 97our $logo_url = "http://git-scm.com/";
9a7a62ff 98our $logo_label = "git homepage";
51a7c66a 99
09bd7898 100# source of projects list
06c084d2 101our $projects_list = "++GITWEB_LIST++";
b87d78d6 102
55feb120
MH
103# the width (in characters) of the projects list "Description" column
104our $projects_list_description_width = 25;
105
b06dcf8c
FL
106# default order of projects list
107# valid values are none, project, descr, owner, and age
108our $default_projects_order = "project";
109
32f4aacc
ML
110# show repository only if this file exists
111# (only effective if this variable evaluates to true)
112our $export_ok = "++GITWEB_EXPORT_OK++";
113
dd7f5f10
AG
114# show repository only if this subroutine returns true
115# when given the path to the project, for example:
116# sub { return -e "$_[0]/git-daemon-export-ok"; }
117our $export_auth_hook = undef;
118
32f4aacc
ML
119# only allow viewing of repositories also shown on the overview page
120our $strict_export = "++GITWEB_STRICT_EXPORT++";
121
19a8721e
JN
122# list of git base URLs used for URL to where fetch project from,
123# i.e. full URL is "$git_base_url/$project"
d6b7e0b9 124our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
19a8721e 125
f5aa79d9 126# default blob_plain mimetype and default charset for text/plain blob
4a87b43e
DS
127our $default_blob_plain_mimetype = 'text/plain';
128our $default_text_plain_charset = undef;
f5aa79d9 129
2d007374
PB
130# file to use for guessing MIME types before trying /etc/mime.types
131# (relative to the current git repository)
4a87b43e 132our $mimetypes_file = undef;
2d007374 133
00f429af
MK
134# assume this charset if line contains non-UTF-8 characters;
135# it should be valid encoding (see Encoding::Supported(3pm) for list),
136# for which encoding all byte sequences are valid, for example
137# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
138# could be even 'utf-8' for the old behavior)
139our $fallback_encoding = 'latin1';
140
69a9b41c
JN
141# rename detection options for git-diff and git-diff-tree
142# - default is '-M', with the cost proportional to
143# (number of removed files) * (number of new files).
144# - more costly is '-C' (which implies '-M'), with the cost proportional to
145# (number of changed files + number of removed files) * (number of new files)
146# - even more costly is '-C', '--find-copies-harder' with cost
147# (number of files in the original tree) * (number of new files)
148# - one might want to include '-B' option, e.g. '-B', '-M'
149our @diff_opts = ('-M'); # taken from git_commit
150
7e1100e9
MM
151# Disables features that would allow repository owners to inject script into
152# the gitweb domain.
153our $prevent_xss = 0;
154
a3c8ab30
MM
155# information about snapshot formats that gitweb is capable of serving
156our %known_snapshot_formats = (
157 # name => {
158 # 'display' => display name,
159 # 'type' => mime type,
160 # 'suffix' => filename suffix,
161 # 'format' => --format for git-archive,
162 # 'compressor' => [compressor command and arguments]
1bfd3631
MR
163 # (array reference, optional)
164 # 'disabled' => boolean (optional)}
a3c8ab30
MM
165 #
166 'tgz' => {
167 'display' => 'tar.gz',
168 'type' => 'application/x-gzip',
169 'suffix' => '.tar.gz',
170 'format' => 'tar',
171 'compressor' => ['gzip']},
172
173 'tbz2' => {
174 'display' => 'tar.bz2',
175 'type' => 'application/x-bzip2',
176 'suffix' => '.tar.bz2',
177 'format' => 'tar',
178 'compressor' => ['bzip2']},
179
cbdefb5a
MR
180 'txz' => {
181 'display' => 'tar.xz',
182 'type' => 'application/x-xz',
183 'suffix' => '.tar.xz',
184 'format' => 'tar',
185 'compressor' => ['xz'],
186 'disabled' => 1},
187
a3c8ab30
MM
188 'zip' => {
189 'display' => 'zip',
190 'type' => 'application/x-zip',
191 'suffix' => '.zip',
192 'format' => 'zip'},
193);
194
195# Aliases so we understand old gitweb.snapshot values in repository
196# configuration.
197our %known_snapshot_format_aliases = (
198 'gzip' => 'tgz',
199 'bzip2' => 'tbz2',
cbdefb5a 200 'xz' => 'txz',
a3c8ab30
MM
201
202 # backward compatibility: legacy gitweb config support
203 'x-gzip' => undef, 'gz' => undef,
204 'x-bzip2' => undef, 'bz2' => undef,
205 'x-zip' => undef, '' => undef,
206);
207
e9fdd74e
GB
208# Pixel sizes for icons and avatars. If the default font sizes or lineheights
209# are changed, it may be appropriate to change these values too via
210# $GITWEB_CONFIG.
211our %avatar_size = (
212 'default' => 16,
213 'double' => 32
214);
215
ddb8d900
AK
216# You define site-wide feature defaults here; override them with
217# $GITWEB_CONFIG as necessary.
952c65fc 218our %feature = (
17848fc6
JN
219 # feature => {
220 # 'sub' => feature-sub (subroutine),
221 # 'override' => allow-override (boolean),
222 # 'default' => [ default options...] (array reference)}
223 #
b4b20b21 224 # if feature is overridable (it means that allow-override has true value),
17848fc6
JN
225 # then feature-sub will be called with default options as parameters;
226 # return value of feature-sub indicates if to enable specified feature
227 #
b4b20b21
JN
228 # if there is no 'sub' key (no feature-sub), then feature cannot be
229 # overriden
230 #
ff3c0ff2
GB
231 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
232 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
233 # is enabled
952c65fc 234
45a3b12c
PB
235 # Enable the 'blame' blob view, showing the last commit that modified
236 # each line in the file. This can be very CPU-intensive.
237
238 # To enable system wide have in $GITWEB_CONFIG
239 # $feature{'blame'}{'default'} = [1];
240 # To have project specific config enable override in $GITWEB_CONFIG
241 # $feature{'blame'}{'override'} = 1;
242 # and in project config gitweb.blame = 0|1;
952c65fc 243 'blame' => {
cdad8170 244 'sub' => sub { feature_bool('blame', @_) },
952c65fc
JN
245 'override' => 0,
246 'default' => [0]},
247
a3c8ab30 248 # Enable the 'snapshot' link, providing a compressed archive of any
45a3b12c
PB
249 # tree. This can potentially generate high traffic if you have large
250 # project.
251
a3c8ab30
MM
252 # Value is a list of formats defined in %known_snapshot_formats that
253 # you wish to offer.
45a3b12c 254 # To disable system wide have in $GITWEB_CONFIG
a3c8ab30 255 # $feature{'snapshot'}{'default'} = [];
45a3b12c 256 # To have project specific config enable override in $GITWEB_CONFIG
bbee1d97 257 # $feature{'snapshot'}{'override'} = 1;
a3c8ab30
MM
258 # and in project config, a comma-separated list of formats or "none"
259 # to disable. Example: gitweb.snapshot = tbz2,zip;
952c65fc
JN
260 'snapshot' => {
261 'sub' => \&feature_snapshot,
262 'override' => 0,
a3c8ab30 263 'default' => ['tgz']},
04f7a94f 264
6be93511
RF
265 # Enable text search, which will list the commits which match author,
266 # committer or commit text to a given string. Enabled by default.
b4b20b21 267 # Project specific override is not supported.
6be93511
RF
268 'search' => {
269 'override' => 0,
270 'default' => [1]},
271
e7738553
PB
272 # Enable grep search, which will list the files in currently selected
273 # tree containing the given string. Enabled by default. This can be
274 # potentially CPU-intensive, of course.
275
276 # To enable system wide have in $GITWEB_CONFIG
277 # $feature{'grep'}{'default'} = [1];
278 # To have project specific config enable override in $GITWEB_CONFIG
279 # $feature{'grep'}{'override'} = 1;
280 # and in project config gitweb.grep = 0|1;
281 'grep' => {
cdad8170 282 'sub' => sub { feature_bool('grep', @_) },
e7738553
PB
283 'override' => 0,
284 'default' => [1]},
285
45a3b12c
PB
286 # Enable the pickaxe search, which will list the commits that modified
287 # a given string in a file. This can be practical and quite faster
288 # alternative to 'blame', but still potentially CPU-intensive.
289
290 # To enable system wide have in $GITWEB_CONFIG
291 # $feature{'pickaxe'}{'default'} = [1];
292 # To have project specific config enable override in $GITWEB_CONFIG
293 # $feature{'pickaxe'}{'override'} = 1;
294 # and in project config gitweb.pickaxe = 0|1;
04f7a94f 295 'pickaxe' => {
cdad8170 296 'sub' => sub { feature_bool('pickaxe', @_) },
04f7a94f
JN
297 'override' => 0,
298 'default' => [1]},
9e756904 299
45a3b12c
PB
300 # Make gitweb use an alternative format of the URLs which can be
301 # more readable and natural-looking: project name is embedded
302 # directly in the path and the query string contains other
303 # auxiliary information. All gitweb installations recognize
304 # URL in either format; this configures in which formats gitweb
305 # generates links.
306
307 # To enable system wide have in $GITWEB_CONFIG
308 # $feature{'pathinfo'}{'default'} = [1];
309 # Project specific override is not supported.
310
311 # Note that you will need to change the default location of CSS,
312 # favicon, logo and possibly other files to an absolute URL. Also,
313 # if gitweb.cgi serves as your indexfile, you will need to force
314 # $my_uri to contain the script name in your $GITWEB_CONFIG.
9e756904
MW
315 'pathinfo' => {
316 'override' => 0,
317 'default' => [0]},
e30496df
PB
318
319 # Make gitweb consider projects in project root subdirectories
320 # to be forks of existing projects. Given project $projname.git,
321 # projects matching $projname/*.git will not be shown in the main
322 # projects list, instead a '+' mark will be added to $projname
323 # there and a 'forks' view will be enabled for the project, listing
c2b8b134
FL
324 # all the forks. If project list is taken from a file, forks have
325 # to be listed after the main project.
e30496df
PB
326
327 # To enable system wide have in $GITWEB_CONFIG
328 # $feature{'forks'}{'default'} = [1];
329 # Project specific override is not supported.
330 'forks' => {
331 'override' => 0,
332 'default' => [0]},
d627f68f
PB
333
334 # Insert custom links to the action bar of all project pages.
335 # This enables you mainly to link to third-party scripts integrating
336 # into gitweb; e.g. git-browser for graphical history representation
337 # or custom web-based repository administration interface.
338
339 # The 'default' value consists of a list of triplets in the form
340 # (label, link, position) where position is the label after which
2b11e059 341 # to insert the link and link is a format string where %n expands
d627f68f
PB
342 # to the project name, %f to the project path within the filesystem,
343 # %h to the current hash (h gitweb parameter) and %b to the current
2b11e059 344 # hash base (hb gitweb parameter); %% expands to %.
d627f68f
PB
345
346 # To enable system wide have in $GITWEB_CONFIG e.g.
347 # $feature{'actions'}{'default'} = [('graphiclog',
348 # '/git-browser/by-commit.html?r=%n', 'summary')];
349 # Project specific override is not supported.
350 'actions' => {
351 'override' => 0,
352 'default' => []},
3e3d4ee7 353
aed93de4
PB
354 # Allow gitweb scan project content tags described in ctags/
355 # of project repository, and display the popular Web 2.0-ish
356 # "tag cloud" near the project list. Note that this is something
357 # COMPLETELY different from the normal Git tags.
358
359 # gitweb by itself can show existing tags, but it does not handle
360 # tagging itself; you need an external application for that.
361 # For an example script, check Girocco's cgi/tagproj.cgi.
362 # You may want to install the HTML::TagCloud Perl module to get
363 # a pretty tag cloud instead of just a list of tags.
364
365 # To enable system wide have in $GITWEB_CONFIG
366 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
367 # Project specific override is not supported.
368 'ctags' => {
369 'override' => 0,
370 'default' => [0]},
9872cd6f
GB
371
372 # The maximum number of patches in a patchset generated in patch
373 # view. Set this to 0 or undef to disable patch view, or to a
374 # negative number to remove any limit.
375
376 # To disable system wide have in $GITWEB_CONFIG
377 # $feature{'patches'}{'default'} = [0];
378 # To have project specific config enable override in $GITWEB_CONFIG
379 # $feature{'patches'}{'override'} = 1;
380 # and in project config gitweb.patches = 0|n;
381 # where n is the maximum number of patches allowed in a patchset.
382 'patches' => {
383 'sub' => \&feature_patches,
384 'override' => 0,
385 'default' => [16]},
e9fdd74e
GB
386
387 # Avatar support. When this feature is enabled, views such as
388 # shortlog or commit will display an avatar associated with
389 # the email of the committer(s) and/or author(s).
390
679a1a1d
GB
391 # Currently available providers are gravatar and picon.
392 # If an unknown provider is specified, the feature is disabled.
393
394 # Gravatar depends on Digest::MD5.
395 # Picon currently relies on the indiana.edu database.
e9fdd74e
GB
396
397 # To enable system wide have in $GITWEB_CONFIG
679a1a1d
GB
398 # $feature{'avatar'}{'default'} = ['<provider>'];
399 # where <provider> is either gravatar or picon.
e9fdd74e
GB
400 # To have project specific config enable override in $GITWEB_CONFIG
401 # $feature{'avatar'}{'override'} = 1;
679a1a1d 402 # and in project config gitweb.avatar = <provider>;
e9fdd74e
GB
403 'avatar' => {
404 'sub' => \&feature_avatar,
405 'override' => 0,
406 'default' => ['']},
ddb8d900
AK
407);
408
a7c5a283 409sub gitweb_get_feature {
ddb8d900 410 my ($name) = @_;
dd1ad5f1 411 return unless exists $feature{$name};
952c65fc
JN
412 my ($sub, $override, @defaults) = (
413 $feature{$name}{'sub'},
414 $feature{$name}{'override'},
415 @{$feature{$name}{'default'}});
ddb8d900 416 if (!$override) { return @defaults; }
a9455919 417 if (!defined $sub) {
93197898 418 warn "feature $name is not overridable";
a9455919
MW
419 return @defaults;
420 }
ddb8d900
AK
421 return $sub->(@defaults);
422}
423
25b2790f
GB
424# A wrapper to check if a given feature is enabled.
425# With this, you can say
426#
427# my $bool_feat = gitweb_check_feature('bool_feat');
428# gitweb_check_feature('bool_feat') or somecode;
429#
430# instead of
431#
432# my ($bool_feat) = gitweb_get_feature('bool_feat');
433# (gitweb_get_feature('bool_feat'))[0] or somecode;
434#
435sub gitweb_check_feature {
436 return (gitweb_get_feature(@_))[0];
437}
438
439
cdad8170
MK
440sub feature_bool {
441 my $key = shift;
442 my ($val) = git_get_project_config($key, '--bool');
ddb8d900 443
df5d10a3
MC
444 if (!defined $val) {
445 return ($_[0]);
446 } elsif ($val eq 'true') {
cdad8170 447 return (1);
ddb8d900 448 } elsif ($val eq 'false') {
cdad8170 449 return (0);
ddb8d900 450 }
ddb8d900
AK
451}
452
ddb8d900 453sub feature_snapshot {
a3c8ab30 454 my (@fmts) = @_;
ddb8d900
AK
455
456 my ($val) = git_get_project_config('snapshot');
457
a3c8ab30
MM
458 if ($val) {
459 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
ddb8d900
AK
460 }
461
a3c8ab30 462 return @fmts;
de9272f4
LT
463}
464
9872cd6f
GB
465sub feature_patches {
466 my @val = (git_get_project_config('patches', '--int'));
467
468 if (@val) {
469 return @val;
470 }
471
472 return ($_[0]);
473}
474
e9fdd74e
GB
475sub feature_avatar {
476 my @val = (git_get_project_config('avatar'));
477
478 return @val ? @val : @_;
479}
480
2172ce4b
JH
481# checking HEAD file with -e is fragile if the repository was
482# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
483# and then pruned.
484sub check_head_link {
485 my ($dir) = @_;
486 my $headfile = "$dir/HEAD";
487 return ((-e $headfile) ||
488 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
489}
490
491sub check_export_ok {
492 my ($dir) = @_;
493 return (check_head_link($dir) &&
dd7f5f10
AG
494 (!$export_ok || -e "$dir/$export_ok") &&
495 (!$export_auth_hook || $export_auth_hook->($dir)));
2172ce4b
JH
496}
497
a781785d
JN
498# process alternate names for backward compatibility
499# filter out unsupported (unknown) snapshot formats
500sub filter_snapshot_fmts {
501 my @fmts = @_;
502
503 @fmts = map {
504 exists $known_snapshot_format_aliases{$_} ?
505 $known_snapshot_format_aliases{$_} : $_} @fmts;
68cedb1f 506 @fmts = grep {
1bfd3631
MR
507 exists $known_snapshot_formats{$_} &&
508 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
a781785d
JN
509}
510
06c084d2 511our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
17a8b250
GP
512if (-e $GITWEB_CONFIG) {
513 do $GITWEB_CONFIG;
514} else {
515 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
516 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
517}
c8d138a8
JK
518
519# version of the core git binary
66115d36 520our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
c8d138a8
JK
521
522$projects_list ||= $projectroot;
c8d138a8 523
154b4d78 524# ======================================================================
09bd7898 525# input validation and dispatch
1b2d297e
GB
526
527# input parameters can be collected from a variety of sources (presently, CGI
528# and PATH_INFO), so we define an %input_params hash that collects them all
529# together during validation: this allows subsequent uses (e.g. href()) to be
530# agnostic of the parameter origin
531
dde80d9c 532our %input_params = ();
1b2d297e
GB
533
534# input parameters are stored with the long parameter name as key. This will
535# also be used in the href subroutine to convert parameters to their CGI
536# equivalent, and since the href() usage is the most frequent one, we store
537# the name -> CGI key mapping here, instead of the reverse.
538#
539# XXX: Warning: If you touch this, check the search form for updating,
540# too.
541
dde80d9c 542our @cgi_param_mapping = (
1b2d297e
GB
543 project => "p",
544 action => "a",
545 file_name => "f",
546 file_parent => "fp",
547 hash => "h",
548 hash_parent => "hp",
549 hash_base => "hb",
550 hash_parent_base => "hpb",
551 page => "pg",
552 order => "o",
553 searchtext => "s",
554 searchtype => "st",
555 snapshot_format => "sf",
556 extra_options => "opt",
557 search_use_regexp => "sr",
558);
dde80d9c 559our %cgi_param_mapping = @cgi_param_mapping;
1b2d297e
GB
560
561# we will also need to know the possible actions, for validation
dde80d9c 562our %actions = (
1b2d297e
GB
563 "blame" => \&git_blame,
564 "blobdiff" => \&git_blobdiff,
565 "blobdiff_plain" => \&git_blobdiff_plain,
566 "blob" => \&git_blob,
567 "blob_plain" => \&git_blob_plain,
568 "commitdiff" => \&git_commitdiff,
569 "commitdiff_plain" => \&git_commitdiff_plain,
570 "commit" => \&git_commit,
571 "forks" => \&git_forks,
572 "heads" => \&git_heads,
573 "history" => \&git_history,
574 "log" => \&git_log,
9872cd6f 575 "patch" => \&git_patch,
a3411f8a 576 "patches" => \&git_patches,
1b2d297e
GB
577 "rss" => \&git_rss,
578 "atom" => \&git_atom,
579 "search" => \&git_search,
580 "search_help" => \&git_search_help,
581 "shortlog" => \&git_shortlog,
582 "summary" => \&git_summary,
583 "tag" => \&git_tag,
584 "tags" => \&git_tags,
585 "tree" => \&git_tree,
586 "snapshot" => \&git_snapshot,
587 "object" => \&git_object,
588 # those below don't need $project
589 "opml" => \&git_opml,
590 "project_list" => \&git_project_list,
591 "project_index" => \&git_project_index,
592);
593
594# finally, we have the hash of allowed extra_options for the commands that
595# allow them
dde80d9c 596our %allowed_options = (
1b2d297e
GB
597 "--no-merges" => [ qw(rss atom log shortlog history) ],
598);
599
600# fill %input_params with the CGI parameters. All values except for 'opt'
601# should be single values, but opt can be an array. We should probably
602# build an array of parameters that can be multi-valued, but since for the time
603# being it's only this one, we just single it out
604while (my ($name, $symbol) = each %cgi_param_mapping) {
605 if ($symbol eq 'opt') {
606 $input_params{$name} = [ $cgi->param($symbol) ];
607 } else {
608 $input_params{$name} = $cgi->param($symbol);
609 }
610}
611
612# now read PATH_INFO and update the parameter list for missing parameters
613sub evaluate_path_info {
614 return if defined $input_params{'project'};
615 return if !$path_info;
616 $path_info =~ s,^/+,,;
617 return if !$path_info;
618
619 # find which part of PATH_INFO is project
620 my $project = $path_info;
621 $project =~ s,/+$,,;
622 while ($project && !check_head_link("$projectroot/$project")) {
623 $project =~ s,/*[^/]*$,,;
624 }
625 return unless $project;
626 $input_params{'project'} = $project;
627
628 # do not change any parameters if an action is given using the query string
629 return if $input_params{'action'};
630 $path_info =~ s,^\Q$project\E/*,,;
631
d8c28822
GB
632 # next, check if we have an action
633 my $action = $path_info;
634 $action =~ s,/.*$,,;
635 if (exists $actions{$action}) {
636 $path_info =~ s,^$action/*,,;
637 $input_params{'action'} = $action;
638 }
639
640 # list of actions that want hash_base instead of hash, but can have no
641 # pathname (f) parameter
642 my @wants_base = (
643 'tree',
644 'history',
645 );
646
b0be3838
GB
647 # we want to catch
648 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
649 my ($parentrefname, $parentpathname, $refname, $pathname) =
650 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
651
652 # first, analyze the 'current' part
1b2d297e 653 if (defined $pathname) {
d8c28822
GB
654 # we got "branch:filename" or "branch:dir/"
655 # we could use git_get_type(branch:pathname), but:
656 # - it needs $git_dir
657 # - it does a git() call
658 # - the convention of terminating directories with a slash
659 # makes it superfluous
660 # - embedding the action in the PATH_INFO would make it even
661 # more superfluous
1b2d297e
GB
662 $pathname =~ s,^/+,,;
663 if (!$pathname || substr($pathname, -1) eq "/") {
d8c28822 664 $input_params{'action'} ||= "tree";
1b2d297e
GB
665 $pathname =~ s,/$,,;
666 } else {
b0be3838
GB
667 # the default action depends on whether we had parent info
668 # or not
669 if ($parentrefname) {
670 $input_params{'action'} ||= "blobdiff_plain";
671 } else {
672 $input_params{'action'} ||= "blob_plain";
673 }
1b2d297e
GB
674 }
675 $input_params{'hash_base'} ||= $refname;
676 $input_params{'file_name'} ||= $pathname;
677 } elsif (defined $refname) {
d8c28822
GB
678 # we got "branch". In this case we have to choose if we have to
679 # set hash or hash_base.
680 #
681 # Most of the actions without a pathname only want hash to be
682 # set, except for the ones specified in @wants_base that want
683 # hash_base instead. It should also be noted that hand-crafted
684 # links having 'history' as an action and no pathname or hash
685 # set will fail, but that happens regardless of PATH_INFO.
686 $input_params{'action'} ||= "shortlog";
687 if (grep { $_ eq $input_params{'action'} } @wants_base) {
688 $input_params{'hash_base'} ||= $refname;
689 } else {
690 $input_params{'hash'} ||= $refname;
691 }
1b2d297e 692 }
b0be3838
GB
693
694 # next, handle the 'parent' part, if present
695 if (defined $parentrefname) {
696 # a missing pathspec defaults to the 'current' filename, allowing e.g.
697 # someproject/blobdiff/oldrev..newrev:/filename
698 if ($parentpathname) {
699 $parentpathname =~ s,^/+,,;
700 $parentpathname =~ s,/$,,;
701 $input_params{'file_parent'} ||= $parentpathname;
702 } else {
703 $input_params{'file_parent'} ||= $input_params{'file_name'};
704 }
705 # we assume that hash_parent_base is wanted if a path was specified,
706 # or if the action wants hash_base instead of hash
707 if (defined $input_params{'file_parent'} ||
708 grep { $_ eq $input_params{'action'} } @wants_base) {
709 $input_params{'hash_parent_base'} ||= $parentrefname;
710 } else {
711 $input_params{'hash_parent'} ||= $parentrefname;
712 }
713 }
1ec2fb5f
GB
714
715 # for the snapshot action, we allow URLs in the form
716 # $project/snapshot/$hash.ext
717 # where .ext determines the snapshot and gets removed from the
718 # passed $refname to provide the $hash.
719 #
720 # To be able to tell that $refname includes the format extension, we
721 # require the following two conditions to be satisfied:
722 # - the hash input parameter MUST have been set from the $refname part
723 # of the URL (i.e. they must be equal)
724 # - the snapshot format MUST NOT have been defined already (e.g. from
725 # CGI parameter sf)
726 # It's also useless to try any matching unless $refname has a dot,
727 # so we check for that too
728 if (defined $input_params{'action'} &&
729 $input_params{'action'} eq 'snapshot' &&
730 defined $refname && index($refname, '.') != -1 &&
731 $refname eq $input_params{'hash'} &&
732 !defined $input_params{'snapshot_format'}) {
733 # We loop over the known snapshot formats, checking for
734 # extensions. Allowed extensions are both the defined suffix
735 # (which includes the initial dot already) and the snapshot
736 # format key itself, with a prepended dot
ccb4b539 737 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1ec2fb5f 738 my $hash = $refname;
095e9142
JN
739 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
740 next;
741 }
742 my $sfx = $1;
1ec2fb5f
GB
743 # a valid suffix was found, so set the snapshot format
744 # and reset the hash parameter
745 $input_params{'snapshot_format'} = $fmt;
746 $input_params{'hash'} = $hash;
747 # we also set the format suffix to the one requested
748 # in the URL: this way a request for e.g. .tgz returns
749 # a .tgz instead of a .tar.gz
750 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
751 last;
752 }
753 }
1b2d297e
GB
754}
755evaluate_path_info();
756
757our $action = $input_params{'action'};
09bd7898 758if (defined $action) {
1b2d297e 759 if (!validate_action($action)) {
074afaa0 760 die_error(400, "Invalid action parameter");
b87d78d6 761 }
b87d78d6 762}
44ad2978 763
24d0693a 764# parameters which are pathnames
1b2d297e 765our $project = $input_params{'project'};
13d02165 766if (defined $project) {
1b2d297e 767 if (!validate_project($project)) {
7939fe44 768 undef $project;
074afaa0 769 die_error(404, "No such project");
9cd3d988 770 }
a59d4afd 771}
6191f8e1 772
1b2d297e 773our $file_name = $input_params{'file_name'};
24d0693a
JN
774if (defined $file_name) {
775 if (!validate_pathname($file_name)) {
074afaa0 776 die_error(400, "Invalid file parameter");
24d0693a
JN
777 }
778}
779
1b2d297e 780our $file_parent = $input_params{'file_parent'};
24d0693a
JN
781if (defined $file_parent) {
782 if (!validate_pathname($file_parent)) {
074afaa0 783 die_error(400, "Invalid file parent parameter");
24d0693a
JN
784 }
785}
5c95fab0 786
24d0693a 787# parameters which are refnames
1b2d297e 788our $hash = $input_params{'hash'};
4fac5294 789if (defined $hash) {
24d0693a 790 if (!validate_refname($hash)) {
074afaa0 791 die_error(400, "Invalid hash parameter");
4fac5294 792 }
a59d4afd 793}
6191f8e1 794
1b2d297e 795our $hash_parent = $input_params{'hash_parent'};
c91da262 796if (defined $hash_parent) {
24d0693a 797 if (!validate_refname($hash_parent)) {
074afaa0 798 die_error(400, "Invalid hash parent parameter");
c91da262 799 }
09bd7898
KS
800}
801
1b2d297e 802our $hash_base = $input_params{'hash_base'};
c91da262 803if (defined $hash_base) {
24d0693a 804 if (!validate_refname($hash_base)) {
074afaa0 805 die_error(400, "Invalid hash base parameter");
c91da262 806 }
a59d4afd 807}
6191f8e1 808
1b2d297e
GB
809our @extra_options = @{$input_params{'extra_options'}};
810# @extra_options is always defined, since it can only be (currently) set from
811# CGI, and $cgi->param() returns the empty array in array context if the param
812# is not set
813foreach my $opt (@extra_options) {
814 if (not exists $allowed_options{$opt}) {
815 die_error(400, "Invalid option parameter");
816 }
817 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
818 die_error(400, "Invalid option parameter for this action");
868bc068
MV
819 }
820}
821
1b2d297e 822our $hash_parent_base = $input_params{'hash_parent_base'};
420e92f2 823if (defined $hash_parent_base) {
24d0693a 824 if (!validate_refname($hash_parent_base)) {
074afaa0 825 die_error(400, "Invalid hash parent base parameter");
420e92f2
JN
826 }
827}
828
24d0693a 829# other parameters
1b2d297e 830our $page = $input_params{'page'};
ea4a6df4 831if (defined $page) {
ac8e3f2b 832 if ($page =~ m/[^0-9]/) {
074afaa0 833 die_error(400, "Invalid page parameter");
b87d78d6 834 }
2ad9331e 835}
823d5dc8 836
1b2d297e 837our $searchtype = $input_params{'searchtype'};
e7738553
PB
838if (defined $searchtype) {
839 if ($searchtype =~ m/[^a-z]/) {
074afaa0 840 die_error(400, "Invalid searchtype parameter");
e7738553
PB
841 }
842}
843
1b2d297e 844our $search_use_regexp = $input_params{'search_use_regexp'};
0e559919 845
1b2d297e 846our $searchtext = $input_params{'searchtext'};
7e431ef9 847our $search_regexp;
19806691 848if (defined $searchtext) {
9d032c72 849 if (length($searchtext) < 2) {
074afaa0 850 die_error(403, "At least two characters are required for search parameter");
9d032c72 851 }
0e559919 852 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
19806691
KS
853}
854
645927ce
ML
855# path to the current git repository
856our $git_dir;
857$git_dir = "$projectroot/$project" if $project;
dd70235f 858
5e166843 859# list of supported snapshot formats
a7c5a283 860our @snapshot_fmts = gitweb_get_feature('snapshot');
5e166843
GB
861@snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
862
e9fdd74e
GB
863# check that the avatar feature is set to a known provider name,
864# and for each provider check if the dependencies are satisfied.
865# if the provider name is invalid or the dependencies are not met,
866# reset $git_avatar to the empty string.
867our ($git_avatar) = gitweb_get_feature('avatar');
868if ($git_avatar eq 'gravatar') {
869 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
679a1a1d
GB
870} elsif ($git_avatar eq 'picon') {
871 # no dependencies
e9fdd74e
GB
872} else {
873 $git_avatar = '';
874}
875
717b8311 876# dispatch
7f9778b1
GP
877if (!defined $action) {
878 if (defined $hash) {
879 $action = git_get_type($hash);
880 } elsif (defined $hash_base && defined $file_name) {
881 $action = git_get_type("$hash_base:$file_name");
882 } elsif (defined $project) {
883 $action = 'summary';
884 } else {
885 $action = 'project_list';
886 }
77a153fd 887}
8e85cdc4 888if (!defined($actions{$action})) {
074afaa0 889 die_error(400, "Unknown action");
09bd7898 890}
e8bb4b38 891if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
d04d3d42 892 !$project) {
074afaa0 893 die_error(400, "Project needed");
d04d3d42 894}
8e85cdc4
ML
895$actions{$action}->();
896exit;
09bd7898 897
06a9d86b
MW
898## ======================================================================
899## action links
900
74fd8728 901sub href {
498fe002 902 my %params = @_;
bd5d1e42
JN
903 # default is to use -absolute url() i.e. $my_uri
904 my $href = $params{-full} ? $my_url : $my_uri;
498fe002 905
afa9b620
JN
906 $params{'project'} = $project unless exists $params{'project'};
907
1cad283a 908 if ($params{-replay}) {
1b2d297e 909 while (my ($name, $symbol) = each %cgi_param_mapping) {
1cad283a 910 if (!exists $params{$name}) {
1b2d297e 911 $params{$name} = $input_params{$name};
1cad283a
JN
912 }
913 }
914 }
915
25b2790f 916 my $use_pathinfo = gitweb_check_feature('pathinfo');
fb098a94 917 if ($use_pathinfo and defined $params{'project'}) {
b02bd7a6
GB
918 # try to put as many parameters as possible in PATH_INFO:
919 # - project name
920 # - action
8db49a7f 921 # - hash_parent or hash_parent_base:/file_parent
3550ea71 922 # - hash or hash_base:/filename
c752a0e0 923 # - the snapshot_format as an appropriate suffix
b02bd7a6
GB
924
925 # When the script is the root DirectoryIndex for the domain,
926 # $href here would be something like http://gitweb.example.com/
927 # Thus, we strip any trailing / from $href, to spare us double
928 # slashes in the final URL
929 $href =~ s,/$,,;
930
931 # Then add the project name, if present
fb098a94 932 $href .= "/".esc_url($params{'project'});
9e756904
MW
933 delete $params{'project'};
934
c752a0e0
GB
935 # since we destructively absorb parameters, we keep this
936 # boolean that remembers if we're handling a snapshot
937 my $is_snapshot = $params{'action'} eq 'snapshot';
938
b02bd7a6
GB
939 # Summary just uses the project path URL, any other action is
940 # added to the URL
941 if (defined $params{'action'}) {
942 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
9e756904
MW
943 delete $params{'action'};
944 }
b02bd7a6 945
8db49a7f
GB
946 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
947 # stripping nonexistent or useless pieces
948 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
949 || $params{'hash_parent'} || $params{'hash'});
b02bd7a6 950 if (defined $params{'hash_base'}) {
8db49a7f
GB
951 if (defined $params{'hash_parent_base'}) {
952 $href .= esc_url($params{'hash_parent_base'});
953 # skip the file_parent if it's the same as the file_name
b7da721f
GB
954 if (defined $params{'file_parent'}) {
955 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
956 delete $params{'file_parent'};
957 } elsif ($params{'file_parent'} !~ /\.\./) {
958 $href .= ":/".esc_url($params{'file_parent'});
959 delete $params{'file_parent'};
960 }
8db49a7f
GB
961 }
962 $href .= "..";
963 delete $params{'hash_parent'};
964 delete $params{'hash_parent_base'};
965 } elsif (defined $params{'hash_parent'}) {
966 $href .= esc_url($params{'hash_parent'}). "..";
967 delete $params{'hash_parent'};
968 }
969
970 $href .= esc_url($params{'hash_base'});
971 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
3550ea71 972 $href .= ":/".esc_url($params{'file_name'});
b02bd7a6
GB
973 delete $params{'file_name'};
974 }
975 delete $params{'hash'};
976 delete $params{'hash_base'};
977 } elsif (defined $params{'hash'}) {
8db49a7f 978 $href .= esc_url($params{'hash'});
b02bd7a6
GB
979 delete $params{'hash'};
980 }
c752a0e0
GB
981
982 # If the action was a snapshot, we can absorb the
983 # snapshot_format parameter too
984 if ($is_snapshot) {
985 my $fmt = $params{'snapshot_format'};
986 # snapshot_format should always be defined when href()
987 # is called, but just in case some code forgets, we
988 # fall back to the default
989 $fmt ||= $snapshot_fmts[0];
990 $href .= $known_snapshot_formats{$fmt}{'suffix'};
991 delete $params{'snapshot_format'};
992 }
9e756904
MW
993 }
994
995 # now encode the parameters explicitly
498fe002 996 my @result = ();
1b2d297e
GB
997 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
998 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
498fe002 999 if (defined $params{$name}) {
f22cca44
JN
1000 if (ref($params{$name}) eq "ARRAY") {
1001 foreach my $par (@{$params{$name}}) {
1002 push @result, $symbol . "=" . esc_param($par);
1003 }
1004 } else {
1005 push @result, $symbol . "=" . esc_param($params{$name});
1006 }
498fe002
JN
1007 }
1008 }
9e756904
MW
1009 $href .= "?" . join(';', @result) if scalar @result;
1010
1011 return $href;
06a9d86b
MW
1012}
1013
1014
717b8311
JN
1015## ======================================================================
1016## validation, quoting/unquoting and escaping
1017
1b2d297e
GB
1018sub validate_action {
1019 my $input = shift || return undef;
1020 return undef unless exists $actions{$input};
1021 return $input;
1022}
1023
1024sub validate_project {
1025 my $input = shift || return undef;
1026 if (!validate_pathname($input) ||
1027 !(-d "$projectroot/$input") ||
ec26f098 1028 !check_export_ok("$projectroot/$input") ||
1b2d297e
GB
1029 ($strict_export && !project_in_list($input))) {
1030 return undef;
1031 } else {
1032 return $input;
1033 }
1034}
1035
24d0693a
JN
1036sub validate_pathname {
1037 my $input = shift || return undef;
717b8311 1038
24d0693a
JN
1039 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1040 # at the beginning, at the end, and between slashes.
1041 # also this catches doubled slashes
1042 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1043 return undef;
717b8311 1044 }
24d0693a
JN
1045 # no null characters
1046 if ($input =~ m!\0!) {
717b8311
JN
1047 return undef;
1048 }
24d0693a
JN
1049 return $input;
1050}
1051
1052sub validate_refname {
1053 my $input = shift || return undef;
1054
1055 # textual hashes are O.K.
1056 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1057 return $input;
1058 }
1059 # it must be correct pathname
1060 $input = validate_pathname($input)
1061 or return undef;
1062 # restrictions on ref name according to git-check-ref-format
1063 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
717b8311
JN
1064 return undef;
1065 }
1066 return $input;
1067}
1068
00f429af
MK
1069# decode sequences of octets in utf8 into Perl's internal form,
1070# which is utf-8 with utf8 flag set if needed. gitweb writes out
1071# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1072sub to_utf8 {
1073 my $str = shift;
e5d3de5c
İD
1074 if (utf8::valid($str)) {
1075 utf8::decode($str);
1076 return $str;
00f429af
MK
1077 } else {
1078 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1079 }
1080}
1081
232ff553
KS
1082# quote unsafe chars, but keep the slash, even when it's not
1083# correct, but quoted slashes look too horrible in bookmarks
1084sub esc_param {
353347b0 1085 my $str = shift;
452e2256 1086 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
a9e60b7d 1087 $str =~ s/ /\+/g;
353347b0
KS
1088 return $str;
1089}
1090
f93bff8d
JN
1091# quote unsafe chars in whole URL, so some charactrs cannot be quoted
1092sub esc_url {
1093 my $str = shift;
1094 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1095 $str =~ s/\+/%2B/g;
1096 $str =~ s/ /\+/g;
1097 return $str;
1098}
1099
232ff553 1100# replace invalid utf8 character with SUBSTITUTION sequence
74fd8728 1101sub esc_html {
40c13813 1102 my $str = shift;
6255ef08
JN
1103 my %opts = @_;
1104
00f429af 1105 $str = to_utf8($str);
c390ae97 1106 $str = $cgi->escapeHTML($str);
6255ef08
JN
1107 if ($opts{'-nbsp'}) {
1108 $str =~ s/ /&nbsp;/g;
1109 }
25ffbb27 1110 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
40c13813
KS
1111 return $str;
1112}
1113
391862e3
JN
1114# quote control characters and escape filename to HTML
1115sub esc_path {
1116 my $str = shift;
1117 my %opts = @_;
1118
00f429af 1119 $str = to_utf8($str);
c390ae97 1120 $str = $cgi->escapeHTML($str);
391862e3
JN
1121 if ($opts{'-nbsp'}) {
1122 $str =~ s/ /&nbsp;/g;
1123 }
1124 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1125 return $str;
1126}
1127
1128# Make control characters "printable", using character escape codes (CEC)
1d3bc0cc
JN
1129sub quot_cec {
1130 my $cntrl = shift;
c84c483f 1131 my %opts = @_;
1d3bc0cc 1132 my %es = ( # character escape codes, aka escape sequences
c84c483f
JN
1133 "\t" => '\t', # tab (HT)
1134 "\n" => '\n', # line feed (LF)
1135 "\r" => '\r', # carrige return (CR)
1136 "\f" => '\f', # form feed (FF)
1137 "\b" => '\b', # backspace (BS)
1138 "\a" => '\a', # alarm (bell) (BEL)
1139 "\e" => '\e', # escape (ESC)
1140 "\013" => '\v', # vertical tab (VT)
1141 "\000" => '\0', # nul character (NUL)
1142 );
1d3bc0cc
JN
1143 my $chr = ( (exists $es{$cntrl})
1144 ? $es{$cntrl}
25dfd171 1145 : sprintf('\%2x', ord($cntrl)) );
c84c483f
JN
1146 if ($opts{-nohtml}) {
1147 return $chr;
1148 } else {
1149 return "<span class=\"cntrl\">$chr</span>";
1150 }
1d3bc0cc
JN
1151}
1152
391862e3
JN
1153# Alternatively use unicode control pictures codepoints,
1154# Unicode "printable representation" (PR)
1d3bc0cc
JN
1155sub quot_upr {
1156 my $cntrl = shift;
c84c483f
JN
1157 my %opts = @_;
1158
1d3bc0cc 1159 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
c84c483f
JN
1160 if ($opts{-nohtml}) {
1161 return $chr;
1162 } else {
1163 return "<span class=\"cntrl\">$chr</span>";
1164 }
1d3bc0cc
JN
1165}
1166
232ff553
KS
1167# git may return quoted and escaped filenames
1168sub unquote {
1169 my $str = shift;
403d0906
JN
1170
1171 sub unq {
1172 my $seq = shift;
1173 my %es = ( # character escape codes, aka escape sequences
1174 't' => "\t", # tab (HT, TAB)
1175 'n' => "\n", # newline (NL)
1176 'r' => "\r", # return (CR)
1177 'f' => "\f", # form feed (FF)
1178 'b' => "\b", # backspace (BS)
1179 'a' => "\a", # alarm (bell) (BEL)
1180 'e' => "\e", # escape (ESC)
1181 'v' => "\013", # vertical tab (VT)
1182 );
1183
1184 if ($seq =~ m/^[0-7]{1,3}$/) {
1185 # octal char sequence
1186 return chr(oct($seq));
1187 } elsif (exists $es{$seq}) {
1188 # C escape sequence, aka character escape code
c84c483f 1189 return $es{$seq};
403d0906
JN
1190 }
1191 # quoted ordinary character
1192 return $seq;
1193 }
1194
232ff553 1195 if ($str =~ m/^"(.*)"$/) {
403d0906 1196 # needs unquoting
232ff553 1197 $str = $1;
403d0906 1198 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
232ff553
KS
1199 }
1200 return $str;
1201}
1202
f16db173
JN
1203# escape tabs (convert tabs to spaces)
1204sub untabify {
1205 my $line = shift;
1206
1207 while ((my $pos = index($line, "\t")) != -1) {
1208 if (my $count = (8 - ($pos % 8))) {
1209 my $spaces = ' ' x $count;
1210 $line =~ s/\t/$spaces/;
1211 }
1212 }
1213
1214 return $line;
1215}
1216
32f4aacc
ML
1217sub project_in_list {
1218 my $project = shift;
1219 my @list = git_get_projects_list();
1220 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1221}
1222
717b8311
JN
1223## ----------------------------------------------------------------------
1224## HTML aware string manipulation
1225
b8d97d07
JN
1226# Try to chop given string on a word boundary between position
1227# $len and $len+$add_len. If there is no word boundary there,
1228# chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1229# (marking chopped part) would be longer than given string.
717b8311
JN
1230sub chop_str {
1231 my $str = shift;
1232 my $len = shift;
1233 my $add_len = shift || 10;
b8d97d07 1234 my $where = shift || 'right'; # 'left' | 'center' | 'right'
717b8311 1235
dee2775a
AW
1236 # Make sure perl knows it is utf8 encoded so we don't
1237 # cut in the middle of a utf8 multibyte char.
1238 $str = to_utf8($str);
1239
717b8311
JN
1240 # allow only $len chars, but don't cut a word if it would fit in $add_len
1241 # if it doesn't fit, cut it if it's still longer than the dots we would add
b8d97d07
JN
1242 # remove chopped character entities entirely
1243
1244 # when chopping in the middle, distribute $len into left and right part
1245 # return early if chopping wouldn't make string shorter
1246 if ($where eq 'center') {
1247 return $str if ($len + 5 >= length($str)); # filler is length 5
1248 $len = int($len/2);
1249 } else {
1250 return $str if ($len + 4 >= length($str)); # filler is length 4
1251 }
1252
1253 # regexps: ending and beginning with word part up to $add_len
1254 my $endre = qr/.{$len}\w{0,$add_len}/;
1255 my $begre = qr/\w{0,$add_len}.{$len}/;
1256
1257 if ($where eq 'left') {
1258 $str =~ m/^(.*?)($begre)$/;
1259 my ($lead, $body) = ($1, $2);
1260 if (length($lead) > 4) {
1261 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1262 $lead = " ...";
1263 }
1264 return "$lead$body";
1265
1266 } elsif ($where eq 'center') {
1267 $str =~ m/^($endre)(.*)$/;
1268 my ($left, $str) = ($1, $2);
1269 $str =~ m/^(.*?)($begre)$/;
1270 my ($mid, $right) = ($1, $2);
1271 if (length($mid) > 5) {
1272 $left =~ s/&[^;]*$//;
1273 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1274 $mid = " ... ";
1275 }
1276 return "$left$mid$right";
1277
1278 } else {
1279 $str =~ m/^($endre)(.*)$/;
1280 my $body = $1;
1281 my $tail = $2;
1282 if (length($tail) > 4) {
1283 $body =~ s/&[^;]*$//;
1284 $tail = "... ";
1285 }
1286 return "$body$tail";
717b8311 1287 }
717b8311
JN
1288}
1289
ce58ec91
DS
1290# takes the same arguments as chop_str, but also wraps a <span> around the
1291# result with a title attribute if it does get chopped. Additionally, the
1292# string is HTML-escaped.
1293sub chop_and_escape_str {
b8d97d07 1294 my ($str) = @_;
ce58ec91 1295
b8d97d07 1296 my $chopped = chop_str(@_);
ce58ec91
DS
1297 if ($chopped eq $str) {
1298 return esc_html($chopped);
1299 } else {
14afe774 1300 $str =~ s/[[:cntrl:]]/?/g;
850b90a5 1301 return $cgi->span({-title=>$str}, esc_html($chopped));
ce58ec91
DS
1302 }
1303}
1304
717b8311
JN
1305## ----------------------------------------------------------------------
1306## functions returning short strings
1307
1f1ab5f0
JN
1308# CSS class for given age value (in seconds)
1309sub age_class {
1310 my $age = shift;
1311
785cdea9
JN
1312 if (!defined $age) {
1313 return "noage";
1314 } elsif ($age < 60*60*2) {
1f1ab5f0
JN
1315 return "age0";
1316 } elsif ($age < 60*60*24*2) {
1317 return "age1";
1318 } else {
1319 return "age2";
1320 }
1321}
1322
717b8311
JN
1323# convert age in seconds to "nn units ago" string
1324sub age_string {
1325 my $age = shift;
1326 my $age_str;
a59d4afd 1327
717b8311
JN
1328 if ($age > 60*60*24*365*2) {
1329 $age_str = (int $age/60/60/24/365);
1330 $age_str .= " years ago";
1331 } elsif ($age > 60*60*24*(365/12)*2) {
1332 $age_str = int $age/60/60/24/(365/12);
1333 $age_str .= " months ago";
1334 } elsif ($age > 60*60*24*7*2) {
1335 $age_str = int $age/60/60/24/7;
1336 $age_str .= " weeks ago";
1337 } elsif ($age > 60*60*24*2) {
1338 $age_str = int $age/60/60/24;
1339 $age_str .= " days ago";
1340 } elsif ($age > 60*60*2) {
1341 $age_str = int $age/60/60;
1342 $age_str .= " hours ago";
1343 } elsif ($age > 60*2) {
1344 $age_str = int $age/60;
1345 $age_str .= " min ago";
1346 } elsif ($age > 2) {
1347 $age_str = int $age;
1348 $age_str .= " sec ago";
f6801d66 1349 } else {
717b8311 1350 $age_str .= " right now";
4c02e3c5 1351 }
717b8311 1352 return $age_str;
161332a5
KS
1353}
1354
01ac1e38
JN
1355use constant {
1356 S_IFINVALID => 0030000,
1357 S_IFGITLINK => 0160000,
1358};
1359
1360# submodule/subproject, a commit object reference
74fd8728 1361sub S_ISGITLINK {
01ac1e38
JN
1362 my $mode = shift;
1363
1364 return (($mode & S_IFMT) == S_IFGITLINK)
1365}
1366
717b8311
JN
1367# convert file mode in octal to symbolic file mode string
1368sub mode_str {
1369 my $mode = oct shift;
1370
01ac1e38
JN
1371 if (S_ISGITLINK($mode)) {
1372 return 'm---------';
1373 } elsif (S_ISDIR($mode & S_IFMT)) {
717b8311
JN
1374 return 'drwxr-xr-x';
1375 } elsif (S_ISLNK($mode)) {
1376 return 'lrwxrwxrwx';
1377 } elsif (S_ISREG($mode)) {
1378 # git cares only about the executable bit
1379 if ($mode & S_IXUSR) {
1380 return '-rwxr-xr-x';
1381 } else {
1382 return '-rw-r--r--';
1383 };
c994d620 1384 } else {
717b8311 1385 return '----------';
ff7669a5 1386 }
161332a5
KS
1387}
1388
717b8311
JN
1389# convert file mode in octal to file type string
1390sub file_type {
7c5e2ebb
JN
1391 my $mode = shift;
1392
1393 if ($mode !~ m/^[0-7]+$/) {
1394 return $mode;
1395 } else {
1396 $mode = oct $mode;
1397 }
664f4cc5 1398
01ac1e38
JN
1399 if (S_ISGITLINK($mode)) {
1400 return "submodule";
1401 } elsif (S_ISDIR($mode & S_IFMT)) {
717b8311
JN
1402 return "directory";
1403 } elsif (S_ISLNK($mode)) {
1404 return "symlink";
1405 } elsif (S_ISREG($mode)) {
1406 return "file";
1407 } else {
1408 return "unknown";
1409 }
a59d4afd
KS
1410}
1411
744d0ac3
JN
1412# convert file mode in octal to file type description string
1413sub file_type_long {
1414 my $mode = shift;
1415
1416 if ($mode !~ m/^[0-7]+$/) {
1417 return $mode;
1418 } else {
1419 $mode = oct $mode;
1420 }
1421
01ac1e38
JN
1422 if (S_ISGITLINK($mode)) {
1423 return "submodule";
1424 } elsif (S_ISDIR($mode & S_IFMT)) {
744d0ac3
JN
1425 return "directory";
1426 } elsif (S_ISLNK($mode)) {
1427 return "symlink";
1428 } elsif (S_ISREG($mode)) {
1429 if ($mode & S_IXUSR) {
1430 return "executable";
1431 } else {
1432 return "file";
1433 };
1434 } else {
1435 return "unknown";
1436 }
1437}
1438
1439
717b8311
JN
1440## ----------------------------------------------------------------------
1441## functions returning short HTML fragments, or transforming HTML fragments
3dff5379 1442## which don't belong to other sections
b18f9bf4 1443
225932ed 1444# format line of commit message.
717b8311
JN
1445sub format_log_line_html {
1446 my $line = shift;
b18f9bf4 1447
225932ed 1448 $line = esc_html($line, -nbsp=>1);
7d233dea
MC
1449 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1450 $cgi->a({-href => href(action=>"object", hash=>$1),
1451 -class => "text"}, $1);
1452 }eg;
1453
717b8311 1454 return $line;
b18f9bf4
JN
1455}
1456
717b8311 1457# format marker of refs pointing to given object
4afbaeff
GB
1458
1459# the destination action is chosen based on object type and current context:
1460# - for annotated tags, we choose the tag view unless it's the current view
1461# already, in which case we go to shortlog view
1462# - for other refs, we keep the current view if we're in history, shortlog or
1463# log view, and select shortlog otherwise
847e01fb 1464sub format_ref_marker {
717b8311 1465 my ($refs, $id) = @_;
d294e1ca 1466 my $markers = '';
27fb8c40 1467
717b8311 1468 if (defined $refs->{$id}) {
d294e1ca 1469 foreach my $ref (@{$refs->{$id}}) {
4afbaeff
GB
1470 # this code exploits the fact that non-lightweight tags are the
1471 # only indirect objects, and that they are the only objects for which
1472 # we want to use tag instead of shortlog as action
d294e1ca 1473 my ($type, $name) = qw();
4afbaeff 1474 my $indirect = ($ref =~ s/\^\{\}$//);
d294e1ca
JN
1475 # e.g. tags/v2.6.11 or heads/next
1476 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1477 $type = $1;
1478 $name = $2;
1479 } else {
1480 $type = "ref";
1481 $name = $ref;
1482 }
1483
4afbaeff
GB
1484 my $class = $type;
1485 $class .= " indirect" if $indirect;
1486
1487 my $dest_action = "shortlog";
1488
1489 if ($indirect) {
1490 $dest_action = "tag" unless $action eq "tag";
1491 } elsif ($action =~ /^(history|(short)?log)$/) {
1492 $dest_action = $action;
1493 }
1494
1495 my $dest = "";
1496 $dest .= "refs/" unless $ref =~ m!^refs/!;
1497 $dest .= $ref;
1498
1499 my $link = $cgi->a({
1500 -href => href(
1501 action=>$dest_action,
1502 hash=>$dest
1503 )}, $name);
1504
1505 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1506 $link . "</span>";
d294e1ca
JN
1507 }
1508 }
1509
1510 if ($markers) {
1511 return ' <span class="refs">'. $markers . '</span>';
717b8311
JN
1512 } else {
1513 return "";
1514 }
27fb8c40
JN
1515}
1516
17d07443
JN
1517# format, perhaps shortened and with markers, title line
1518sub format_subject_html {
1c2a4f5a 1519 my ($long, $short, $href, $extra) = @_;
17d07443
JN
1520 $extra = '' unless defined($extra);
1521
1522 if (length($short) < length($long)) {
14afe774 1523 $long =~ s/[[:cntrl:]]/?/g;
7c278014 1524 return $cgi->a({-href => $href, -class => "list subject",
00f429af 1525 -title => to_utf8($long)},
01b89f0c 1526 esc_html($short)) . $extra;
17d07443 1527 } else {
7c278014 1528 return $cgi->a({-href => $href, -class => "list subject"},
01b89f0c 1529 esc_html($long)) . $extra;
17d07443
JN
1530 }
1531}
1532
5a371b7b
GB
1533# Rather than recomputing the url for an email multiple times, we cache it
1534# after the first hit. This gives a visible benefit in views where the avatar
1535# for the same email is used repeatedly (e.g. shortlog).
1536# The cache is shared by all avatar engines (currently gravatar only), which
1537# are free to use it as preferred. Since only one avatar engine is used for any
1538# given page, there's no risk for cache conflicts.
1539our %avatar_cache = ();
1540
679a1a1d
GB
1541# Compute the picon url for a given email, by using the picon search service over at
1542# http://www.cs.indiana.edu/picons/search.html
1543sub picon_url {
1544 my $email = lc shift;
1545 if (!$avatar_cache{$email}) {
1546 my ($user, $domain) = split('@', $email);
1547 $avatar_cache{$email} =
1548 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1549 "$domain/$user/" .
1550 "users+domains+unknown/up/single";
1551 }
1552 return $avatar_cache{$email};
1553}
1554
5a371b7b
GB
1555# Compute the gravatar url for a given email, if it's not in the cache already.
1556# Gravatar stores only the part of the URL before the size, since that's the
1557# one computationally more expensive. This also allows reuse of the cache for
1558# different sizes (for this particular engine).
1559sub gravatar_url {
1560 my $email = lc shift;
1561 my $size = shift;
1562 $avatar_cache{$email} ||=
1563 "http://www.gravatar.com/avatar/" .
1564 Digest::MD5::md5_hex($email) . "?s=";
1565 return $avatar_cache{$email} . $size;
1566}
1567
e9fdd74e
GB
1568# Insert an avatar for the given $email at the given $size if the feature
1569# is enabled.
1570sub git_get_avatar {
1571 my ($email, %opts) = @_;
1572 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1573 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1574 $opts{-size} ||= 'default';
1575 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1576 my $url = "";
1577 if ($git_avatar eq 'gravatar') {
5a371b7b 1578 $url = gravatar_url($email, $size);
679a1a1d
GB
1579 } elsif ($git_avatar eq 'picon') {
1580 $url = picon_url($email);
e9fdd74e 1581 }
679a1a1d 1582 # Other providers can be added by extending the if chain, defining $url
e9fdd74e
GB
1583 # as needed. If no variant puts something in $url, we assume avatars
1584 # are completely disabled/unavailable.
1585 if ($url) {
1586 return $pre_white .
1587 "<img width=\"$size\" " .
1588 "class=\"avatar\" " .
1589 "src=\"$url\" " .
7d25ef41 1590 "alt=\"\" " .
e9fdd74e
GB
1591 "/>" . $post_white;
1592 } else {
1593 return "";
1594 }
1595}
1596
e133d65c
SB
1597sub format_search_author {
1598 my ($author, $searchtype, $displaytext) = @_;
1599 my $have_search = gitweb_check_feature('search');
1600
1601 if ($have_search) {
1602 my $performed = "";
1603 if ($searchtype eq 'author') {
1604 $performed = "authored";
1605 } elsif ($searchtype eq 'committer') {
1606 $performed = "committed";
1607 }
1608
1609 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1610 searchtext=>$author,
1611 searchtype=>$searchtype), class=>"list",
1612 title=>"Search for commits $performed by $author"},
1613 $displaytext);
1614
1615 } else {
1616 return $displaytext;
1617 }
1618}
1619
1c49a4e1
GB
1620# format the author name of the given commit with the given tag
1621# the author name is chopped and escaped according to the other
1622# optional parameters (see chop_str).
1623sub format_author_html {
1624 my $tag = shift;
1625 my $co = shift;
1626 my $author = chop_and_escape_str($co->{'author_name'}, @_);
e9fdd74e 1627 return "<$tag class=\"author\">" .
e133d65c
SB
1628 format_search_author($co->{'author_name'}, "author",
1629 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1630 $author) .
1631 "</$tag>";
1c49a4e1
GB
1632}
1633
90921740
JN
1634# format git diff header line, i.e. "diff --(git|combined|cc) ..."
1635sub format_git_diff_header_line {
1636 my $line = shift;
1637 my $diffinfo = shift;
1638 my ($from, $to) = @_;
1639
1640 if ($diffinfo->{'nparents'}) {
1641 # combined diff
1642 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1643 if ($to->{'href'}) {
1644 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1645 esc_path($to->{'file'}));
1646 } else { # file was deleted (no href)
1647 $line .= esc_path($to->{'file'});
1648 }
1649 } else {
1650 # "ordinary" diff
1651 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1652 if ($from->{'href'}) {
1653 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1654 'a/' . esc_path($from->{'file'}));
1655 } else { # file was added (no href)
1656 $line .= 'a/' . esc_path($from->{'file'});
1657 }
1658 $line .= ' ';
1659 if ($to->{'href'}) {
1660 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1661 'b/' . esc_path($to->{'file'}));
1662 } else { # file was deleted
1663 $line .= 'b/' . esc_path($to->{'file'});
1664 }
1665 }
1666
1667 return "<div class=\"diff header\">$line</div>\n";
1668}
1669
1670# format extended diff header line, before patch itself
1671sub format_extended_diff_header_line {
1672 my $line = shift;
1673 my $diffinfo = shift;
1674 my ($from, $to) = @_;
1675
1676 # match <path>
1677 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1678 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1679 esc_path($from->{'file'}));
1680 }
1681 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1682 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1683 esc_path($to->{'file'}));
1684 }
1685 # match single <mode>
1686 if ($line =~ m/\s(\d{6})$/) {
1687 $line .= '<span class="info"> (' .
1688 file_type_long($1) .
1689 ')</span>';
1690 }
1691 # match <hash>
1692 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1693 # can match only for combined diff
1694 $line = 'index ';
1695 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1696 if ($from->{'href'}[$i]) {
1697 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1698 -class=>"hash"},
1699 substr($diffinfo->{'from_id'}[$i],0,7));
1700 } else {
1701 $line .= '0' x 7;
1702 }
1703 # separator
1704 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1705 }
1706 $line .= '..';
1707 if ($to->{'href'}) {
1708 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1709 substr($diffinfo->{'to_id'},0,7));
1710 } else {
1711 $line .= '0' x 7;
1712 }
1713
1714 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1715 # can match only for ordinary diff
1716 my ($from_link, $to_link);
1717 if ($from->{'href'}) {
1718 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1719 substr($diffinfo->{'from_id'},0,7));
1720 } else {
1721 $from_link = '0' x 7;
1722 }
1723 if ($to->{'href'}) {
1724 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1725 substr($diffinfo->{'to_id'},0,7));
1726 } else {
1727 $to_link = '0' x 7;
1728 }
1729 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1730 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1731 }
1732
1733 return $line . "<br/>\n";
1734}
1735
1736# format from-file/to-file diff header
1737sub format_diff_from_to_header {
91af4ce4 1738 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
90921740
JN
1739 my $line;
1740 my $result = '';
1741
1742 $line = $from_line;
1743 #assert($line =~ m/^---/) if DEBUG;
deaa01a9
JN
1744 # no extra formatting for "^--- /dev/null"
1745 if (! $diffinfo->{'nparents'}) {
1746 # ordinary (single parent) diff
1747 if ($line =~ m!^--- "?a/!) {
1748 if ($from->{'href'}) {
1749 $line = '--- a/' .
1750 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1751 esc_path($from->{'file'}));
1752 } else {
1753 $line = '--- a/' .
1754 esc_path($from->{'file'});
1755 }
1756 }
1757 $result .= qq!<div class="diff from_file">$line</div>\n!;
1758
1759 } else {
1760 # combined diff (merge commit)
1761 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1762 if ($from->{'href'}[$i]) {
1763 $line = '--- ' .
91af4ce4
JN
1764 $cgi->a({-href=>href(action=>"blobdiff",
1765 hash_parent=>$diffinfo->{'from_id'}[$i],
1766 hash_parent_base=>$parents[$i],
1767 file_parent=>$from->{'file'}[$i],
1768 hash=>$diffinfo->{'to_id'},
1769 hash_base=>$hash,
1770 file_name=>$to->{'file'}),
1771 -class=>"path",
1772 -title=>"diff" . ($i+1)},
1773 $i+1) .
1774 '/' .
deaa01a9
JN
1775 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1776 esc_path($from->{'file'}[$i]));
1777 } else {
1778 $line = '--- /dev/null';
1779 }
1780 $result .= qq!<div class="diff from_file">$line</div>\n!;
90921740
JN
1781 }
1782 }
90921740
JN
1783
1784 $line = $to_line;
1785 #assert($line =~ m/^\+\+\+/) if DEBUG;
1786 # no extra formatting for "^+++ /dev/null"
1787 if ($line =~ m!^\+\+\+ "?b/!) {
1788 if ($to->{'href'}) {
1789 $line = '+++ b/' .
1790 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1791 esc_path($to->{'file'}));
1792 } else {
1793 $line = '+++ b/' .
1794 esc_path($to->{'file'});
1795 }
1796 }
1797 $result .= qq!<div class="diff to_file">$line</div>\n!;
1798
1799 return $result;
1800}
1801
cd030c3a
JN
1802# create note for patch simplified by combined diff
1803sub format_diff_cc_simplified {
1804 my ($diffinfo, @parents) = @_;
1805 my $result = '';
1806
1807 $result .= "<div class=\"diff header\">" .
1808 "diff --cc ";
1809 if (!is_deleted($diffinfo)) {
1810 $result .= $cgi->a({-href => href(action=>"blob",
1811 hash_base=>$hash,
1812 hash=>$diffinfo->{'to_id'},
1813 file_name=>$diffinfo->{'to_file'}),
1814 -class => "path"},
1815 esc_path($diffinfo->{'to_file'}));
1816 } else {
1817 $result .= esc_path($diffinfo->{'to_file'});
1818 }
1819 $result .= "</div>\n" . # class="diff header"
1820 "<div class=\"diff nodifferences\">" .
1821 "Simple merge" .
1822 "</div>\n"; # class="diff nodifferences"
1823
1824 return $result;
1825}
1826
90921740 1827# format patch (diff) line (not to be used for diff headers)
eee08903
JN
1828sub format_diff_line {
1829 my $line = shift;
59e3b14e 1830 my ($from, $to) = @_;
eee08903
JN
1831 my $diff_class = "";
1832
1833 chomp $line;
1834
e72c0eaf
JN
1835 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1836 # combined diff
1837 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1838 if ($line =~ m/^\@{3}/) {
1839 $diff_class = " chunk_header";
1840 } elsif ($line =~ m/^\\/) {
1841 $diff_class = " incomplete";
1842 } elsif ($prefix =~ tr/+/+/) {
1843 $diff_class = " add";
1844 } elsif ($prefix =~ tr/-/-/) {
1845 $diff_class = " rem";
1846 }
1847 } else {
1848 # assume ordinary diff
1849 my $char = substr($line, 0, 1);
1850 if ($char eq '+') {
1851 $diff_class = " add";
1852 } elsif ($char eq '-') {
1853 $diff_class = " rem";
1854 } elsif ($char eq '@') {
1855 $diff_class = " chunk_header";
1856 } elsif ($char eq "\\") {
1857 $diff_class = " incomplete";
1858 }
eee08903
JN
1859 }
1860 $line = untabify($line);
59e3b14e
JN
1861 if ($from && $to && $line =~ m/^\@{2} /) {
1862 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1863 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1864
1865 $from_lines = 0 unless defined $from_lines;
1866 $to_lines = 0 unless defined $to_lines;
1867
1868 if ($from->{'href'}) {
1869 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1870 -class=>"list"}, $from_text);
1871 }
1872 if ($to->{'href'}) {
1873 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1874 -class=>"list"}, $to_text);
1875 }
1876 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1877 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1878 return "<div class=\"diff$diff_class\">$line</div>\n";
e72c0eaf
JN
1879 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1880 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1881 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1882
1883 @from_text = split(' ', $ranges);
1884 for (my $i = 0; $i < @from_text; ++$i) {
1885 ($from_start[$i], $from_nlines[$i]) =
1886 (split(',', substr($from_text[$i], 1)), 0);
1887 }
1888
1889 $to_text = pop @from_text;
1890 $to_start = pop @from_start;
1891 $to_nlines = pop @from_nlines;
1892
1893 $line = "<span class=\"chunk_info\">$prefix ";
1894 for (my $i = 0; $i < @from_text; ++$i) {
1895 if ($from->{'href'}[$i]) {
1896 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1897 -class=>"list"}, $from_text[$i]);
1898 } else {
1899 $line .= $from_text[$i];
1900 }
1901 $line .= " ";
1902 }
1903 if ($to->{'href'}) {
1904 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1905 -class=>"list"}, $to_text);
1906 } else {
1907 $line .= $to_text;
1908 }
1909 $line .= " $prefix</span>" .
1910 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1911 return "<div class=\"diff$diff_class\">$line</div>\n";
59e3b14e 1912 }
6255ef08 1913 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
eee08903
JN
1914}
1915
a3c8ab30
MM
1916# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1917# linked. Pass the hash of the tree/commit to snapshot.
1918sub format_snapshot_links {
1919 my ($hash) = @_;
a3c8ab30
MM
1920 my $num_fmts = @snapshot_fmts;
1921 if ($num_fmts > 1) {
1922 # A parenthesized list of links bearing format names.
a781785d 1923 # e.g. "snapshot (_tar.gz_ _zip_)"
a3c8ab30
MM
1924 return "snapshot (" . join(' ', map
1925 $cgi->a({
1926 -href => href(
1927 action=>"snapshot",
1928 hash=>$hash,
1929 snapshot_format=>$_
1930 )
1931 }, $known_snapshot_formats{$_}{'display'})
1932 , @snapshot_fmts) . ")";
1933 } elsif ($num_fmts == 1) {
1934 # A single "snapshot" link whose tooltip bears the format name.
a781785d 1935 # i.e. "_snapshot_"
a3c8ab30 1936 my ($fmt) = @snapshot_fmts;
a781785d
JN
1937 return
1938 $cgi->a({
a3c8ab30
MM
1939 -href => href(
1940 action=>"snapshot",
1941 hash=>$hash,
1942 snapshot_format=>$fmt
1943 ),
1944 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1945 }, "snapshot");
1946 } else { # $num_fmts == 0
1947 return undef;
1948 }
1949}
1950
3562198b
JN
1951## ......................................................................
1952## functions returning values to be passed, perhaps after some
1953## transformation, to other functions; e.g. returning arguments to href()
1954
1955# returns hash to be passed to href to generate gitweb URL
1956# in -title key it returns description of link
1957sub get_feed_info {
1958 my $format = shift || 'Atom';
1959 my %res = (action => lc($format));
1960
1961 # feed links are possible only for project views
1962 return unless (defined $project);
1963 # some views should link to OPML, or to generic project feed,
1964 # or don't have specific feed yet (so they should use generic)
1965 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1966
1967 my $branch;
1968 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1969 # from tag links; this also makes possible to detect branch links
1970 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1971 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1972 $branch = $1;
1973 }
1974 # find log type for feed description (title)
1975 my $type = 'log';
1976 if (defined $file_name) {
1977 $type = "history of $file_name";
1978 $type .= "/" if ($action eq 'tree');
1979 $type .= " on '$branch'" if (defined $branch);
1980 } else {
1981 $type = "log of $branch" if (defined $branch);
1982 }
1983
1984 $res{-title} = $type;
1985 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1986 $res{'file_name'} = $file_name;
1987
1988 return %res;
1989}
1990
717b8311
JN
1991## ----------------------------------------------------------------------
1992## git utility subroutines, invoking git commands
42f7eb94 1993
25691fbe
DS
1994# returns path to the core git executable and the --git-dir parameter as list
1995sub git_cmd {
1996 return $GIT, '--git-dir='.$git_dir;
1997}
1998
516381d5
LW
1999# quote the given arguments for passing them to the shell
2000# quote_command("command", "arg 1", "arg with ' and ! characters")
2001# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2002# Try to avoid using this function wherever possible.
2003sub quote_command {
2004 return join(' ',
68cedb1f 2005 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
25691fbe
DS
2006}
2007
717b8311 2008# get HEAD ref of given project as hash
847e01fb 2009sub git_get_head_hash {
df2c37a5 2010 my $project = shift;
25691fbe 2011 my $o_git_dir = $git_dir;
df2c37a5 2012 my $retval = undef;
25691fbe
DS
2013 $git_dir = "$projectroot/$project";
2014 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
df2c37a5
JH
2015 my $head = <$fd>;
2016 close $fd;
2c5c008b
KS
2017 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
2018 $retval = $1;
df2c37a5
JH
2019 }
2020 }
25691fbe
DS
2021 if (defined $o_git_dir) {
2022 $git_dir = $o_git_dir;
2c5c008b 2023 }
df2c37a5
JH
2024 return $retval;
2025}
2026
717b8311
JN
2027# get type of given object
2028sub git_get_type {
2029 my $hash = shift;
2030
25691fbe 2031 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
717b8311
JN
2032 my $type = <$fd>;
2033 close $fd or return;
2034 chomp $type;
2035 return $type;
2036}
2037
b201927a
JN
2038# repository configuration
2039our $config_file = '';
2040our %config;
2041
2042# store multiple values for single key as anonymous array reference
2043# single values stored directly in the hash, not as [ <value> ]
2044sub hash_set_multi {
2045 my ($hash, $key, $value) = @_;
2046
2047 if (!exists $hash->{$key}) {
2048 $hash->{$key} = $value;
2049 } elsif (!ref $hash->{$key}) {
2050 $hash->{$key} = [ $hash->{$key}, $value ];
2051 } else {
2052 push @{$hash->{$key}}, $value;
2053 }
2054}
2055
2056# return hash of git project configuration
2057# optionally limited to some section, e.g. 'gitweb'
2058sub git_parse_project_config {
2059 my $section_regexp = shift;
2060 my %config;
2061
2062 local $/ = "\0";
2063
2064 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2065 or return;
2066
2067 while (my $keyval = <$fh>) {
2068 chomp $keyval;
2069 my ($key, $value) = split(/\n/, $keyval, 2);
2070
2071 hash_set_multi(\%config, $key, $value)
2072 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2073 }
2074 close $fh;
2075
2076 return %config;
2077}
2078
df5d10a3 2079# convert config value to boolean: 'true' or 'false'
b201927a
JN
2080# no value, number > 0, 'true' and 'yes' values are true
2081# rest of values are treated as false (never as error)
2082sub config_to_bool {
2083 my $val = shift;
2084
df5d10a3
MC
2085 return 1 if !defined $val; # section.key
2086
b201927a
JN
2087 # strip leading and trailing whitespace
2088 $val =~ s/^\s+//;
2089 $val =~ s/\s+$//;
2090
df5d10a3 2091 return (($val =~ /^\d+$/ && $val) || # section.key = 1
b201927a
JN
2092 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2093}
2094
2095# convert config value to simple decimal number
2096# an optional value suffix of 'k', 'm', or 'g' will cause the value
2097# to be multiplied by 1024, 1048576, or 1073741824
2098sub config_to_int {
2099 my $val = shift;
2100
2101 # strip leading and trailing whitespace
2102 $val =~ s/^\s+//;
2103 $val =~ s/\s+$//;
2104
2105 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2106 $unit = lc($unit);
2107 # unknown unit is treated as 1
2108 return $num * ($unit eq 'g' ? 1073741824 :
2109 $unit eq 'm' ? 1048576 :
2110 $unit eq 'k' ? 1024 : 1);
2111 }
2112 return $val;
2113}
2114
2115# convert config value to array reference, if needed
2116sub config_to_multi {
2117 my $val = shift;
2118
d76a585d 2119 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
b201927a
JN
2120}
2121
717b8311 2122sub git_get_project_config {
ddb8d900 2123 my ($key, $type) = @_;
717b8311 2124
b201927a 2125 # key sanity check
717b8311
JN
2126 return unless ($key);
2127 $key =~ s/^gitweb\.//;
2128 return if ($key =~ m/\W/);
2129
b201927a
JN
2130 # type sanity check
2131 if (defined $type) {
2132 $type =~ s/^--//;
2133 $type = undef
2134 unless ($type eq 'bool' || $type eq 'int');
2135 }
2136
2137 # get config
2138 if (!defined $config_file ||
2139 $config_file ne "$git_dir/config") {
2140 %config = git_parse_project_config('gitweb');
2141 $config_file = "$git_dir/config";
2142 }
2143
df5d10a3
MC
2144 # check if config variable (key) exists
2145 return unless exists $config{"gitweb.$key"};
2146
b201927a
JN
2147 # ensure given type
2148 if (!defined $type) {
2149 return $config{"gitweb.$key"};
2150 } elsif ($type eq 'bool') {
2151 # backward compatibility: 'git config --bool' returns true/false
2152 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2153 } elsif ($type eq 'int') {
2154 return config_to_int($config{"gitweb.$key"});
2155 }
2156 return $config{"gitweb.$key"};
717b8311
JN
2157}
2158
717b8311
JN
2159# get hash of given path at given ref
2160sub git_get_hash_by_path {
2161 my $base = shift;
2162 my $path = shift || return undef;
1d782b03 2163 my $type = shift;
717b8311 2164
4b02f483 2165 $path =~ s,/+$,,;
717b8311 2166
25691fbe 2167 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
074afaa0 2168 or die_error(500, "Open git-ls-tree failed");
717b8311
JN
2169 my $line = <$fd>;
2170 close $fd or return undef;
2171
198a2a8a
JN
2172 if (!defined $line) {
2173 # there is no tree or hash given by $path at $base
2174 return undef;
2175 }
2176
717b8311 2177 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
8b4b94cc 2178 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1d782b03
JN
2179 if (defined $type && $type ne $2) {
2180 # type doesn't match
2181 return undef;
2182 }
717b8311
JN
2183 return $3;
2184}
2185
ed224dea
JN
2186# get path of entry with given hash at given tree-ish (ref)
2187# used to get 'from' filename for combined diff (merge commit) for renames
2188sub git_get_path_by_hash {
2189 my $base = shift || return;
2190 my $hash = shift || return;
2191
2192 local $/ = "\0";
2193
2194 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2195 or return undef;
2196 while (my $line = <$fd>) {
2197 chomp $line;
2198
2199 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2200 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2201 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2202 close $fd;
2203 return $1;
2204 }
2205 }
2206 close $fd;
2207 return undef;
2208}
2209
717b8311
JN
2210## ......................................................................
2211## git utility functions, directly accessing git repository
2212
847e01fb 2213sub git_get_project_description {
b87d78d6 2214 my $path = shift;
09bd7898 2215
0e121a2c 2216 $git_dir = "$projectroot/$path";
dff2b6d4 2217 open my $fd, '<', "$git_dir/description"
0e121a2c 2218 or return git_get_project_config('description');
b87d78d6
KS
2219 my $descr = <$fd>;
2220 close $fd;
2eb54efc
JH
2221 if (defined $descr) {
2222 chomp $descr;
2223 }
b87d78d6 2224 return $descr;
12a88f2f
KS
2225}
2226
aed93de4
PB
2227sub git_get_project_ctags {
2228 my $path = shift;
2229 my $ctags = {};
2230
2231 $git_dir = "$projectroot/$path";
ad87e4f6
JN
2232 opendir my $dh, "$git_dir/ctags"
2233 or return $ctags;
2234 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
dff2b6d4 2235 open my $ct, '<', $_ or next;
ad87e4f6 2236 my $val = <$ct>;
aed93de4 2237 chomp $val;
ad87e4f6 2238 close $ct;
aed93de4
PB
2239 my $ctag = $_; $ctag =~ s#.*/##;
2240 $ctags->{$ctag} = $val;
2241 }
ad87e4f6 2242 closedir $dh;
aed93de4
PB
2243 $ctags;
2244}
2245
2246sub git_populate_project_tagcloud {
2247 my $ctags = shift;
2248
2249 # First, merge different-cased tags; tags vote on casing
2250 my %ctags_lc;
2251 foreach (keys %$ctags) {
2252 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2253 if (not $ctags_lc{lc $_}->{topcount}
2254 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2255 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2256 $ctags_lc{lc $_}->{topname} = $_;
2257 }
2258 }
2259
2260 my $cloud;
2261 if (eval { require HTML::TagCloud; 1; }) {
2262 $cloud = HTML::TagCloud->new;
2263 foreach (sort keys %ctags_lc) {
2264 # Pad the title with spaces so that the cloud looks
2265 # less crammed.
2266 my $title = $ctags_lc{$_}->{topname};
2267 $title =~ s/ /&nbsp;/g;
2268 $title =~ s/^/&nbsp;/g;
2269 $title =~ s/$/&nbsp;/g;
2270 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2271 }
2272 } else {
2273 $cloud = \%ctags_lc;
2274 }
2275 $cloud;
2276}
2277
2278sub git_show_project_tagcloud {
2279 my ($cloud, $count) = @_;
2280 print STDERR ref($cloud)."..\n";
2281 if (ref $cloud eq 'HTML::TagCloud') {
2282 return $cloud->html_and_css($count);
2283 } else {
2284 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2285 return '<p align="center">' . join (', ', map {
2286 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2287 } splice(@tags, 0, $count)) . '</p>';
2288 }
2289}
2290
e79ca7cc
JN
2291sub git_get_project_url_list {
2292 my $path = shift;
2293
0e121a2c 2294 $git_dir = "$projectroot/$path";
dff2b6d4 2295 open my $fd, '<', "$git_dir/cloneurl"
0e121a2c
JN
2296 or return wantarray ?
2297 @{ config_to_multi(git_get_project_config('url')) } :
2298 config_to_multi(git_get_project_config('url'));
e79ca7cc
JN
2299 my @git_project_url_list = map { chomp; $_ } <$fd>;
2300 close $fd;
2301
2302 return wantarray ? @git_project_url_list : \@git_project_url_list;
2303}
2304
847e01fb 2305sub git_get_projects_list {
e30496df 2306 my ($filter) = @_;
717b8311
JN
2307 my @list;
2308
e30496df
PB
2309 $filter ||= '';
2310 $filter =~ s/\.git$//;
2311
25b2790f 2312 my $check_forks = gitweb_check_feature('forks');
c2b8b134 2313
717b8311
JN
2314 if (-d $projects_list) {
2315 # search in directory
e30496df 2316 my $dir = $projects_list . ($filter ? "/$filter" : '');
6768d6b8
AK
2317 # remove the trailing "/"
2318 $dir =~ s!/+$!!;
c0011ff8 2319 my $pfxlen = length("$dir");
ca5e9495 2320 my $pfxdepth = ($dir =~ tr!/!!);
c0011ff8
JN
2321
2322 File::Find::find({
2323 follow_fast => 1, # follow symbolic links
d20602ee 2324 follow_skip => 2, # ignore duplicates
c0011ff8
JN
2325 dangling_symlinks => 0, # ignore dangling symlinks, silently
2326 wanted => sub {
2327 # skip project-list toplevel, if we get it.
2328 return if (m!^[/.]$!);
2329 # only directories can be git repositories
2330 return unless (-d $_);
ca5e9495
LL
2331 # don't traverse too deep (Find is super slow on os x)
2332 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2333 $File::Find::prune = 1;
2334 return;
2335 }
c0011ff8
JN
2336
2337 my $subdir = substr($File::Find::name, $pfxlen + 1);
2338 # we check related file in $projectroot
fb3bb3d1
DD
2339 my $path = ($filter ? "$filter/" : '') . $subdir;
2340 if (check_export_ok("$projectroot/$path")) {
2341 push @list, { path => $path };
c0011ff8
JN
2342 $File::Find::prune = 1;
2343 }
2344 },
2345 }, "$dir");
2346
717b8311
JN
2347 } elsif (-f $projects_list) {
2348 # read from file(url-encoded):
2349 # 'git%2Fgit.git Linus+Torvalds'
2350 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2351 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
c2b8b134 2352 my %paths;
dff2b6d4 2353 open my $fd, '<', $projects_list or return;
c2b8b134 2354 PROJECT:
717b8311
JN
2355 while (my $line = <$fd>) {
2356 chomp $line;
2357 my ($path, $owner) = split ' ', $line;
2358 $path = unescape($path);
2359 $owner = unescape($owner);
2360 if (!defined $path) {
2361 next;
2362 }
83ee94c1
JH
2363 if ($filter ne '') {
2364 # looking for forks;
2365 my $pfx = substr($path, 0, length($filter));
2366 if ($pfx ne $filter) {
c2b8b134 2367 next PROJECT;
83ee94c1
JH
2368 }
2369 my $sfx = substr($path, length($filter));
2370 if ($sfx !~ /^\/.*\.git$/) {
c2b8b134
FL
2371 next PROJECT;
2372 }
2373 } elsif ($check_forks) {
2374 PATH:
2375 foreach my $filter (keys %paths) {
2376 # looking for forks;
2377 my $pfx = substr($path, 0, length($filter));
2378 if ($pfx ne $filter) {
2379 next PATH;
2380 }
2381 my $sfx = substr($path, length($filter));
2382 if ($sfx !~ /^\/.*\.git$/) {
2383 next PATH;
2384 }
2385 # is a fork, don't include it in
2386 # the list
2387 next PROJECT;
83ee94c1
JH
2388 }
2389 }
2172ce4b 2390 if (check_export_ok("$projectroot/$path")) {
717b8311
JN
2391 my $pr = {
2392 path => $path,
00f429af 2393 owner => to_utf8($owner),
717b8311 2394 };
c2b8b134
FL
2395 push @list, $pr;
2396 (my $forks_path = $path) =~ s/\.git$//;
2397 $paths{$forks_path}++;
717b8311
JN
2398 }
2399 }
2400 close $fd;
2401 }
717b8311
JN
2402 return @list;
2403}
2404
47852450
JH
2405our $gitweb_project_owner = undef;
2406sub git_get_project_list_from_file {
1e0cf030 2407
47852450 2408 return if (defined $gitweb_project_owner);
1e0cf030 2409
47852450 2410 $gitweb_project_owner = {};
1e0cf030
JN
2411 # read from file (url-encoded):
2412 # 'git%2Fgit.git Linus+Torvalds'
2413 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2414 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2415 if (-f $projects_list) {
dff2b6d4 2416 open(my $fd, '<', $projects_list);
1e0cf030
JN
2417 while (my $line = <$fd>) {
2418 chomp $line;
2419 my ($pr, $ow) = split ' ', $line;
2420 $pr = unescape($pr);
2421 $ow = unescape($ow);
47852450 2422 $gitweb_project_owner->{$pr} = to_utf8($ow);
1e0cf030
JN
2423 }
2424 close $fd;
2425 }
47852450
JH
2426}
2427
2428sub git_get_project_owner {
2429 my $project = shift;
2430 my $owner;
2431
2432 return undef unless $project;
b59012ef 2433 $git_dir = "$projectroot/$project";
47852450
JH
2434
2435 if (!defined $gitweb_project_owner) {
2436 git_get_project_list_from_file();
2437 }
2438
2439 if (exists $gitweb_project_owner->{$project}) {
2440 $owner = $gitweb_project_owner->{$project};
2441 }
b59012ef
BR
2442 if (!defined $owner){
2443 $owner = git_get_project_config('owner');
2444 }
1e0cf030 2445 if (!defined $owner) {
b59012ef 2446 $owner = get_file_owner("$git_dir");
1e0cf030
JN
2447 }
2448
2449 return $owner;
2450}
2451
c60c56cc
JN
2452sub git_get_last_activity {
2453 my ($path) = @_;
2454 my $fd;
2455
2456 $git_dir = "$projectroot/$path";
2457 open($fd, "-|", git_cmd(), 'for-each-ref',
0ff5ec70 2458 '--format=%(committer)',
c60c56cc 2459 '--sort=-committerdate',
0ff5ec70 2460 '--count=1',
c60c56cc
JN
2461 'refs/heads') or return;
2462 my $most_recent = <$fd>;
2463 close $fd or return;
785cdea9
JN
2464 if (defined $most_recent &&
2465 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
c60c56cc
JN
2466 my $timestamp = $1;
2467 my $age = time - $timestamp;
2468 return ($age, age_string($age));
2469 }
c956395e 2470 return (undef, undef);
c60c56cc
JN
2471}
2472
847e01fb 2473sub git_get_references {
717b8311
JN
2474 my $type = shift || "";
2475 my %refs;
28b9d9f7
JN
2476 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2477 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2478 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2479 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
9704d75d 2480 or return;
d294e1ca 2481
717b8311
JN
2482 while (my $line = <$fd>) {
2483 chomp $line;
4afbaeff 2484 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
717b8311 2485 if (defined $refs{$1}) {
d294e1ca 2486 push @{$refs{$1}}, $2;
717b8311 2487 } else {
d294e1ca 2488 $refs{$1} = [ $2 ];
717b8311
JN
2489 }
2490 }
2491 }
2492 close $fd or return;
2493 return \%refs;
2494}
2495
56a322f1
JN
2496sub git_get_rev_name_tags {
2497 my $hash = shift || return undef;
2498
25691fbe 2499 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
56a322f1
JN
2500 or return;
2501 my $name_rev = <$fd>;
2502 close $fd;
2503
2504 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2505 return $1;
2506 } else {
2507 # catches also '$hash undefined' output
2508 return undef;
2509 }
2510}
2511
717b8311
JN
2512## ----------------------------------------------------------------------
2513## parse to hash functions
2514
847e01fb 2515sub parse_date {
717b8311
JN
2516 my $epoch = shift;
2517 my $tz = shift || "-0000";
2518
2519 my %date;
2520 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2521 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2522 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2523 $date{'hour'} = $hour;
2524 $date{'minute'} = $min;
2525 $date{'mday'} = $mday;
2526 $date{'day'} = $days[$wday];
2527 $date{'month'} = $months[$mon];
af6feeb2
JN
2528 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2529 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
952c65fc
JN
2530 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2531 $mday, $months[$mon], $hour ,$min;
af6feeb2 2532 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
a62d6d84 2533 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
717b8311
JN
2534
2535 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2536 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2537 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2538 $date{'hour_local'} = $hour;
2539 $date{'minute_local'} = $min;
2540 $date{'tz_local'} = $tz;
af6feeb2
JN
2541 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2542 1900+$year, $mon+1, $mday,
2543 $hour, $min, $sec, $tz);
717b8311
JN
2544 return %date;
2545}
2546
847e01fb 2547sub parse_tag {
ede5e100
KS
2548 my $tag_id = shift;
2549 my %tag;
d8a20ba9 2550 my @comment;
ede5e100 2551
25691fbe 2552 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
d8a20ba9 2553 $tag{'id'} = $tag_id;
ede5e100
KS
2554 while (my $line = <$fd>) {
2555 chomp $line;
2556 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2557 $tag{'object'} = $1;
7ab0d2b6 2558 } elsif ($line =~ m/^type (.+)$/) {
ede5e100 2559 $tag{'type'} = $1;
7ab0d2b6 2560 } elsif ($line =~ m/^tag (.+)$/) {
ede5e100 2561 $tag{'name'} = $1;
d8a20ba9
KS
2562 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2563 $tag{'author'} = $1;
ba924733
GB
2564 $tag{'author_epoch'} = $2;
2565 $tag{'author_tz'} = $3;
2566 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2567 $tag{'author_name'} = $1;
2568 $tag{'author_email'} = $2;
2569 } else {
2570 $tag{'author_name'} = $tag{'author'};
2571 }
d8a20ba9
KS
2572 } elsif ($line =~ m/--BEGIN/) {
2573 push @comment, $line;
2574 last;
2575 } elsif ($line eq "") {
2576 last;
ede5e100
KS
2577 }
2578 }
d8a20ba9
KS
2579 push @comment, <$fd>;
2580 $tag{'comment'} = \@comment;
19806691 2581 close $fd or return;
ede5e100
KS
2582 if (!defined $tag{'name'}) {
2583 return
2584 };
2585 return %tag
2586}
2587
756bbf54 2588sub parse_commit_text {
ccdfdea0 2589 my ($commit_text, $withparents) = @_;
756bbf54 2590 my @commit_lines = split '\n', $commit_text;
703ac710 2591 my %co;
703ac710 2592
756bbf54
RF
2593 pop @commit_lines; # Remove '\0'
2594
198a2a8a
JN
2595 if (! @commit_lines) {
2596 return;
2597 }
2598
25f422fb 2599 my $header = shift @commit_lines;
198a2a8a 2600 if ($header !~ m/^[0-9a-fA-F]{40}/) {
25f422fb
KS
2601 return;
2602 }
ccdfdea0 2603 ($co{'id'}, my @parents) = split ' ', $header;
19806691 2604 while (my $line = shift @commit_lines) {
b87d78d6 2605 last if $line eq "\n";
7ab0d2b6 2606 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
703ac710 2607 $co{'tree'} = $1;
ccdfdea0 2608 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
208b2dff 2609 push @parents, $1;
022be3d0 2610 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
5ed5bbc7 2611 $co{'author'} = to_utf8($1);
185f09e5
KS
2612 $co{'author_epoch'} = $2;
2613 $co{'author_tz'} = $3;
ba00b8c1
JN
2614 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2615 $co{'author_name'} = $1;
2616 $co{'author_email'} = $2;
2bf7a52c
KS
2617 } else {
2618 $co{'author_name'} = $co{'author'};
2619 }
86eed32d 2620 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
5ed5bbc7 2621 $co{'committer'} = to_utf8($1);
185f09e5
KS
2622 $co{'committer_epoch'} = $2;
2623 $co{'committer_tz'} = $3;
ba00b8c1
JN
2624 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2625 $co{'committer_name'} = $1;
2626 $co{'committer_email'} = $2;
2627 } else {
2628 $co{'committer_name'} = $co{'committer'};
2629 }
703ac710
KS
2630 }
2631 }
ede5e100 2632 if (!defined $co{'tree'}) {
25f422fb 2633 return;
ede5e100 2634 };
208b2dff
RF
2635 $co{'parents'} = \@parents;
2636 $co{'parent'} = $parents[0];
25f422fb 2637
19806691 2638 foreach my $title (@commit_lines) {
c2488d06 2639 $title =~ s/^ //;
19806691 2640 if ($title ne "") {
48c771f4 2641 $co{'title'} = chop_str($title, 80, 5);
19806691
KS
2642 # remove leading stuff of merges to make the interesting part visible
2643 if (length($title) > 50) {
2644 $title =~ s/^Automatic //;
2645 $title =~ s/^merge (of|with) /Merge ... /i;
2646 if (length($title) > 50) {
2647 $title =~ s/(http|rsync):\/\///;
2648 }
2649 if (length($title) > 50) {
2650 $title =~ s/(master|www|rsync)\.//;
2651 }
2652 if (length($title) > 50) {
2653 $title =~ s/kernel.org:?//;
2654 }
2655 if (length($title) > 50) {
2656 $title =~ s/\/pub\/scm//;
2657 }
2658 }
48c771f4 2659 $co{'title_short'} = chop_str($title, 50, 5);
19806691
KS
2660 last;
2661 }
2662 }
53c39676 2663 if (! defined $co{'title'} || $co{'title'} eq "") {
7e0fe5c9
PB
2664 $co{'title'} = $co{'title_short'} = '(no commit message)';
2665 }
25f422fb
KS
2666 # remove added spaces
2667 foreach my $line (@commit_lines) {
2668 $line =~ s/^ //;
2669 }
2670 $co{'comment'} = \@commit_lines;
2ae100df
KS
2671
2672 my $age = time - $co{'committer_epoch'};
2673 $co{'age'} = $age;
d263a6bd 2674 $co{'age_string'} = age_string($age);
71be1e79
KS
2675 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2676 if ($age > 60*60*24*7*2) {
1b1cd421 2677 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
71be1e79
KS
2678 $co{'age_string_age'} = $co{'age_string'};
2679 } else {
2680 $co{'age_string_date'} = $co{'age_string'};
1b1cd421 2681 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
71be1e79 2682 }
703ac710
KS
2683 return %co;
2684}
2685
756bbf54
RF
2686sub parse_commit {
2687 my ($commit_id) = @_;
2688 my %co;
2689
2690 local $/ = "\0";
2691
2692 open my $fd, "-|", git_cmd(), "rev-list",
ccdfdea0 2693 "--parents",
756bbf54 2694 "--header",
756bbf54
RF
2695 "--max-count=1",
2696 $commit_id,
2697 "--",
074afaa0 2698 or die_error(500, "Open git-rev-list failed");
ccdfdea0 2699 %co = parse_commit_text(<$fd>, 1);
756bbf54
RF
2700 close $fd;
2701
2702 return %co;
2703}
2704
2705sub parse_commits {
311e552e 2706 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
756bbf54
RF
2707 my @cos;
2708
2709 $maxcount ||= 1;
2710 $skip ||= 0;
2711
756bbf54
RF
2712 local $/ = "\0";
2713
2714 open my $fd, "-|", git_cmd(), "rev-list",
2715 "--header",
311e552e 2716 @args,
756bbf54 2717 ("--max-count=" . $maxcount),
f47efbb7 2718 ("--skip=" . $skip),
868bc068 2719 @extra_options,
756bbf54
RF
2720 $commit_id,
2721 "--",
2722 ($filename ? ($filename) : ())
074afaa0 2723 or die_error(500, "Open git-rev-list failed");
756bbf54
RF
2724 while (my $line = <$fd>) {
2725 my %co = parse_commit_text($line);
2726 push @cos, \%co;
2727 }
2728 close $fd;
2729
2730 return wantarray ? @cos : \@cos;
2731}
2732
e8e41a93 2733# parse line of git-diff-tree "raw" output
740e67f9
JN
2734sub parse_difftree_raw_line {
2735 my $line = shift;
2736 my %res;
2737
2738 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2739 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2740 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2741 $res{'from_mode'} = $1;
2742 $res{'to_mode'} = $2;
2743 $res{'from_id'} = $3;
2744 $res{'to_id'} = $4;
4ed4a347 2745 $res{'status'} = $5;
740e67f9
JN
2746 $res{'similarity'} = $6;
2747 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
e8e41a93 2748 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
740e67f9 2749 } else {
9d301456 2750 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
740e67f9
JN
2751 }
2752 }
78bc403a
JN
2753 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2754 # combined diff (for merge commit)
2755 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2756 $res{'nparents'} = length($1);
2757 $res{'from_mode'} = [ split(' ', $2) ];
2758 $res{'to_mode'} = pop @{$res{'from_mode'}};
2759 $res{'from_id'} = [ split(' ', $3) ];
2760 $res{'to_id'} = pop @{$res{'from_id'}};
2761 $res{'status'} = [ split('', $4) ];
2762 $res{'to_file'} = unquote($5);
2763 }
740e67f9 2764 # 'c512b523472485aef4fff9e57b229d9d243c967f'
0edcb37d
JN
2765 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2766 $res{'commit'} = $1;
2767 }
740e67f9
JN
2768
2769 return wantarray ? %res : \%res;
2770}
2771
0cec6db5
JN
2772# wrapper: return parsed line of git-diff-tree "raw" output
2773# (the argument might be raw line, or parsed info)
2774sub parsed_difftree_line {
2775 my $line_or_ref = shift;
2776
2777 if (ref($line_or_ref) eq "HASH") {
2778 # pre-parsed (or generated by hand)
2779 return $line_or_ref;
2780 } else {
2781 return parse_difftree_raw_line($line_or_ref);
2782 }
2783}
2784
cb849b46 2785# parse line of git-ls-tree output
74fd8728 2786sub parse_ls_tree_line {
cb849b46
JN
2787 my $line = shift;
2788 my %opts = @_;
2789 my %res;
2790
2791 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
8b4b94cc 2792 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
cb849b46
JN
2793
2794 $res{'mode'} = $1;
2795 $res{'type'} = $2;
2796 $res{'hash'} = $3;
2797 if ($opts{'-z'}) {
2798 $res{'name'} = $4;
2799 } else {
2800 $res{'name'} = unquote($4);
2801 }
2802
2803 return wantarray ? %res : \%res;
2804}
2805
90921740
JN
2806# generates _two_ hashes, references to which are passed as 2 and 3 argument
2807sub parse_from_to_diffinfo {
2808 my ($diffinfo, $from, $to, @parents) = @_;
2809
2810 if ($diffinfo->{'nparents'}) {
2811 # combined diff
2812 $from->{'file'} = [];
2813 $from->{'href'} = [];
2814 fill_from_file_info($diffinfo, @parents)
2815 unless exists $diffinfo->{'from_file'};
2816 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
9d301456
JN
2817 $from->{'file'}[$i] =
2818 defined $diffinfo->{'from_file'}[$i] ?
2819 $diffinfo->{'from_file'}[$i] :
2820 $diffinfo->{'to_file'};
90921740
JN
2821 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2822 $from->{'href'}[$i] = href(action=>"blob",
2823 hash_base=>$parents[$i],
2824 hash=>$diffinfo->{'from_id'}[$i],
2825 file_name=>$from->{'file'}[$i]);
2826 } else {
2827 $from->{'href'}[$i] = undef;
2828 }
2829 }
2830 } else {
0cec6db5 2831 # ordinary (not combined) diff
9d301456 2832 $from->{'file'} = $diffinfo->{'from_file'};
90921740
JN
2833 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2834 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2835 hash=>$diffinfo->{'from_id'},
2836 file_name=>$from->{'file'});
2837 } else {
2838 delete $from->{'href'};
2839 }
2840 }
2841
9d301456 2842 $to->{'file'} = $diffinfo->{'to_file'};
90921740
JN
2843 if (!is_deleted($diffinfo)) { # file exists in result
2844 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2845 hash=>$diffinfo->{'to_id'},
2846 file_name=>$to->{'file'});
2847 } else {
2848 delete $to->{'href'};
2849 }
2850}
2851
717b8311
JN
2852## ......................................................................
2853## parse to array of hashes functions
4c02e3c5 2854
cd146408
JN
2855sub git_get_heads_list {
2856 my $limit = shift;
2857 my @headslist;
2858
2859 open my $fd, '-|', git_cmd(), 'for-each-ref',
2860 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2861 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2862 'refs/heads'
c83a77e4
JN
2863 or return;
2864 while (my $line = <$fd>) {
cd146408 2865 my %ref_item;
120ddde2 2866
cd146408
JN
2867 chomp $line;
2868 my ($refinfo, $committerinfo) = split(/\0/, $line);
2869 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2870 my ($committer, $epoch, $tz) =
2871 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
bf901f8e 2872 $ref_item{'fullname'} = $name;
cd146408
JN
2873 $name =~ s!^refs/heads/!!;
2874
2875 $ref_item{'name'} = $name;
2876 $ref_item{'id'} = $hash;
2877 $ref_item{'title'} = $title || '(no commit message)';
2878 $ref_item{'epoch'} = $epoch;
2879 if ($epoch) {
2880 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2881 } else {
2882 $ref_item{'age'} = "unknown";
717b8311 2883 }
cd146408
JN
2884
2885 push @headslist, \%ref_item;
c83a77e4
JN
2886 }
2887 close $fd;
2888
cd146408
JN
2889 return wantarray ? @headslist : \@headslist;
2890}
2891
2892sub git_get_tags_list {
2893 my $limit = shift;
2894 my @tagslist;
2895
2896 open my $fd, '-|', git_cmd(), 'for-each-ref',
2897 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2898 '--format=%(objectname) %(objecttype) %(refname) '.
2899 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2900 'refs/tags'
2901 or return;
2902 while (my $line = <$fd>) {
2903 my %ref_item;
7a13b999 2904
cd146408
JN
2905 chomp $line;
2906 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2907 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2908 my ($creator, $epoch, $tz) =
2909 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
bf901f8e 2910 $ref_item{'fullname'} = $name;
cd146408
JN
2911 $name =~ s!^refs/tags/!!;
2912
2913 $ref_item{'type'} = $type;
2914 $ref_item{'id'} = $id;
2915 $ref_item{'name'} = $name;
2916 if ($type eq "tag") {
2917 $ref_item{'subject'} = $title;
2918 $ref_item{'reftype'} = $reftype;
2919 $ref_item{'refid'} = $refid;
2920 } else {
2921 $ref_item{'reftype'} = $type;
2922 $ref_item{'refid'} = $id;
2923 }
2924
2925 if ($type eq "tag" || $type eq "commit") {
2926 $ref_item{'epoch'} = $epoch;
2927 if ($epoch) {
2928 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2929 } else {
2930 $ref_item{'age'} = "unknown";
2931 }
2932 }
991910a9 2933
cd146408 2934 push @tagslist, \%ref_item;
717b8311 2935 }
cd146408
JN
2936 close $fd;
2937
2938 return wantarray ? @tagslist : \@tagslist;
86eed32d
KS
2939}
2940
717b8311
JN
2941## ----------------------------------------------------------------------
2942## filesystem-related functions
022be3d0 2943
c07ad4b9
KS
2944sub get_file_owner {
2945 my $path = shift;
2946
2947 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2948 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2949 if (!defined $gcos) {
2950 return undef;
2951 }
2952 my $owner = $gcos;
2953 $owner =~ s/[,;].*$//;
00f429af 2954 return to_utf8($owner);
c07ad4b9
KS
2955}
2956
2dcb5e1a
JN
2957# assume that file exists
2958sub insert_file {
2959 my $filename = shift;
2960
2961 open my $fd, '<', $filename;
4586864a 2962 print map { to_utf8($_) } <$fd>;
2dcb5e1a
JN
2963 close $fd;
2964}
2965
717b8311
JN
2966## ......................................................................
2967## mimetype related functions
09bd7898 2968
717b8311
JN
2969sub mimetype_guess_file {
2970 my $filename = shift;
2971 my $mimemap = shift;
2972 -r $mimemap or return undef;
2973
2974 my %mimemap;
dff2b6d4 2975 open(my $mh, '<', $mimemap) or return undef;
ad87e4f6 2976 while (<$mh>) {
618918e5 2977 next if m/^#/; # skip comments
ad87e4f6 2978 my ($mimetype, $exts) = split(/\t+/);
46b059d7
JH
2979 if (defined $exts) {
2980 my @exts = split(/\s+/, $exts);
2981 foreach my $ext (@exts) {
ad87e4f6 2982 $mimemap{$ext} = $mimetype;
46b059d7 2983 }
09bd7898 2984 }
09bd7898 2985 }
ad87e4f6 2986 close($mh);
09bd7898 2987
8059319a 2988 $filename =~ /\.([^.]*)$/;
717b8311
JN
2989 return $mimemap{$1};
2990}
5996ca08 2991
717b8311
JN
2992sub mimetype_guess {
2993 my $filename = shift;
2994 my $mime;
2995 $filename =~ /\./ or return undef;
5996ca08 2996
717b8311
JN
2997 if ($mimetypes_file) {
2998 my $file = $mimetypes_file;
d5aa50de
JN
2999 if ($file !~ m!^/!) { # if it is relative path
3000 # it is relative to project
3001 $file = "$projectroot/$project/$file";
3002 }
717b8311
JN
3003 $mime = mimetype_guess_file($filename, $file);
3004 }
3005 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3006 return $mime;
5996ca08
FF
3007}
3008
847e01fb 3009sub blob_mimetype {
717b8311
JN
3010 my $fd = shift;
3011 my $filename = shift;
5996ca08 3012
717b8311
JN
3013 if ($filename) {
3014 my $mime = mimetype_guess($filename);
3015 $mime and return $mime;
d8d17b5d 3016 }
717b8311
JN
3017
3018 # just in case
3019 return $default_blob_plain_mimetype unless $fd;
3020
3021 if (-T $fd) {
7f718e8b 3022 return 'text/plain';
717b8311
JN
3023 } elsif (! $filename) {
3024 return 'application/octet-stream';
3025 } elsif ($filename =~ m/\.png$/i) {
3026 return 'image/png';
3027 } elsif ($filename =~ m/\.gif$/i) {
3028 return 'image/gif';
3029 } elsif ($filename =~ m/\.jpe?g$/i) {
3030 return 'image/jpeg';
d8d17b5d 3031 } else {
717b8311 3032 return 'application/octet-stream';
f7ab660c 3033 }
717b8311
JN
3034}
3035
7f718e8b
JN
3036sub blob_contenttype {
3037 my ($fd, $file_name, $type) = @_;
3038
3039 $type ||= blob_mimetype($fd, $file_name);
3040 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3041 $type .= "; charset=$default_text_plain_charset";
3042 }
3043
3044 return $type;
3045}
3046
717b8311
JN
3047## ======================================================================
3048## functions printing HTML: header, footer, error page
3049
3050sub git_header_html {
3051 my $status = shift || "200 OK";
3052 my $expires = shift;
3053
8be2890c 3054 my $title = "$site_name";
717b8311 3055 if (defined $project) {
00f429af 3056 $title .= " - " . to_utf8($project);
717b8311
JN
3057 if (defined $action) {
3058 $title .= "/$action";
3059 if (defined $file_name) {
403d0906 3060 $title .= " - " . esc_path($file_name);
717b8311
JN
3061 if ($action eq "tree" && $file_name !~ m|/$|) {
3062 $title .= "/";
3063 }
3064 }
3065 }
f7ab660c 3066 }
717b8311
JN
3067 my $content_type;
3068 # require explicit support from the UA if we are to send the page as
3069 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3070 # we have to do this because MSIE sometimes globs '*/*', pretending to
3071 # support xhtml+xml but choking when it gets what it asked for.
952c65fc
JN
3072 if (defined $cgi->http('HTTP_ACCEPT') &&
3073 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3074 $cgi->Accept('application/xhtml+xml') != 0) {
717b8311 3075 $content_type = 'application/xhtml+xml';
f7ab660c 3076 } else {
717b8311 3077 $content_type = 'text/html';
f7ab660c 3078 }
952c65fc
JN
3079 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3080 -status=> $status, -expires => $expires);
45c9a758 3081 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
717b8311
JN
3082 print <<EOF;
3083<?xml version="1.0" encoding="utf-8"?>
3084<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3085<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
d4baf9ea 3086<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
717b8311
JN
3087<!-- git core binaries version $git_version -->
3088<head>
3089<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
45c9a758 3090<meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
717b8311
JN
3091<meta name="robots" content="index, nofollow"/>
3092<title>$title</title>
717b8311 3093EOF
41a4d16e
GB
3094 # the stylesheet, favicon etc urls won't work correctly with path_info
3095 # unless we set the appropriate base URL
c3254aee 3096 if ($ENV{'PATH_INFO'}) {
81d3fe9f 3097 print "<base href=\"".esc_url($base_url)."\" />\n";
c3254aee 3098 }
41a4d16e
GB
3099 # print out each stylesheet that exist, providing backwards capability
3100 # for those people who defined $stylesheet in a config file
b2d3476e 3101 if (defined $stylesheet) {
b2d3476e
AC
3102 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3103 } else {
3104 foreach my $stylesheet (@stylesheets) {
3105 next unless $stylesheet;
3106 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3107 }
3108 }
dd04c428 3109 if (defined $project) {
3562198b
JN
3110 my %href_params = get_feed_info();
3111 if (!exists $href_params{'-title'}) {
3112 $href_params{'-title'} = 'log';
3113 }
3114
3115 foreach my $format qw(RSS Atom) {
3116 my $type = lc($format);
3117 my %link_attr = (
3118 '-rel' => 'alternate',
3119 '-title' => "$project - $href_params{'-title'} - $format feed",
3120 '-type' => "application/$type+xml"
3121 );
3122
3123 $href_params{'action'} = $type;
3124 $link_attr{'-href'} = href(%href_params);
3125 print "<link ".
3126 "rel=\"$link_attr{'-rel'}\" ".
3127 "title=\"$link_attr{'-title'}\" ".
3128 "href=\"$link_attr{'-href'}\" ".
3129 "type=\"$link_attr{'-type'}\" ".
3130 "/>\n";
3131
3132 $href_params{'extra_options'} = '--no-merges';
3133 $link_attr{'-href'} = href(%href_params);
3134 $link_attr{'-title'} .= ' (no merges)';
3135 print "<link ".
3136 "rel=\"$link_attr{'-rel'}\" ".
3137 "title=\"$link_attr{'-title'}\" ".
3138 "href=\"$link_attr{'-href'}\" ".
3139 "type=\"$link_attr{'-type'}\" ".
3140 "/>\n";
3141 }
3142
9d0734ae
JN
3143 } else {
3144 printf('<link rel="alternate" title="%s projects list" '.
3562198b 3145 'href="%s" type="text/plain; charset=utf-8" />'."\n",
9d0734ae 3146 $site_name, href(project=>undef, action=>"project_index"));
af6feeb2 3147 printf('<link rel="alternate" title="%s projects feeds" '.
3562198b 3148 'href="%s" type="text/x-opml" />'."\n",
9d0734ae 3149 $site_name, href(project=>undef, action=>"opml"));
dd04c428 3150 }
0b5deba1 3151 if (defined $favicon) {
3562198b 3152 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
0b5deba1 3153 }
10161355 3154
dd04c428 3155 print "</head>\n" .
b2d3476e
AC
3156 "<body>\n";
3157
3158 if (-f $site_header) {
2dcb5e1a 3159 insert_file($site_header);
b2d3476e
AC
3160 }
3161
3162 print "<div class=\"page_header\">\n" .
9a7a62ff
JN
3163 $cgi->a({-href => esc_url($logo_url),
3164 -title => $logo_label},
3165 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
f93bff8d 3166 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
717b8311 3167 if (defined $project) {
1c2a4f5a 3168 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
717b8311
JN
3169 if (defined $action) {
3170 print " / $action";
3171 }
3172 print "\n";
6be93511 3173 }
d77b5673
PB
3174 print "</div>\n";
3175
25b2790f 3176 my $have_search = gitweb_check_feature('search');
f70dda25 3177 if (defined $project && $have_search) {
717b8311
JN
3178 if (!defined $searchtext) {
3179 $searchtext = "";
3180 }
3181 my $search_hash;
3182 if (defined $hash_base) {
3183 $search_hash = $hash_base;
3184 } elsif (defined $hash) {
3185 $search_hash = $hash;
bddec01d 3186 } else {
717b8311 3187 $search_hash = "HEAD";
bddec01d 3188 }
40375a83 3189 my $action = $my_uri;
25b2790f 3190 my $use_pathinfo = gitweb_check_feature('pathinfo');
40375a83 3191 if ($use_pathinfo) {
85d17a12 3192 $action .= "/".esc_url($project);
40375a83 3193 }
40375a83 3194 print $cgi->startform(-method => "get", -action => $action) .
717b8311 3195 "<div class=\"search\">\n" .
f70dda25
JN
3196 (!$use_pathinfo &&
3197 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3198 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3199 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
88ad729b 3200 $cgi->popup_menu(-name => 'st', -default => 'commit',
e7738553 3201 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
88ad729b
PB
3202 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3203 " search:\n",
717b8311 3204 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
0e559919
PB
3205 "<span title=\"Extended regular expression\">" .
3206 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3207 -checked => $search_use_regexp) .
3208 "</span>" .
717b8311
JN
3209 "</div>" .
3210 $cgi->end_form() . "\n";
b87d78d6 3211 }
717b8311
JN
3212}
3213
3214sub git_footer_html {
3562198b
JN
3215 my $feed_class = 'rss_logo';
3216
717b8311
JN
3217 print "<div class=\"page_footer\">\n";
3218 if (defined $project) {
847e01fb 3219 my $descr = git_get_project_description($project);
717b8311
JN
3220 if (defined $descr) {
3221 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3222 }
3562198b
JN
3223
3224 my %href_params = get_feed_info();
3225 if (!%href_params) {
3226 $feed_class .= ' generic';
3227 }
3228 $href_params{'-title'} ||= 'log';
3229
3230 foreach my $format qw(RSS Atom) {
3231 $href_params{'action'} = lc($format);
3232 print $cgi->a({-href => href(%href_params),
3233 -title => "$href_params{'-title'} $format feed",
3234 -class => $feed_class}, $format)."\n";
3235 }
3236
717b8311 3237 } else {
a1565c44 3238 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3562198b 3239 -class => $feed_class}, "OPML") . " ";
9d0734ae 3240 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3562198b 3241 -class => $feed_class}, "TXT") . "\n";
717b8311 3242 }
3562198b 3243 print "</div>\n"; # class="page_footer"
b2d3476e
AC
3244
3245 if (-f $site_footer) {
2dcb5e1a 3246 insert_file($site_footer);
b2d3476e
AC
3247 }
3248
3249 print "</body>\n" .
717b8311
JN
3250 "</html>";
3251}
3252
074afaa0
LW
3253# die_error(<http_status_code>, <error_message>)
3254# Example: die_error(404, 'Hash not found')
3255# By convention, use the following status codes (as defined in RFC 2616):
3256# 400: Invalid or missing CGI parameters, or
3257# requested object exists but has wrong type.
3258# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3259# this server or project.
3260# 404: Requested object/revision/project doesn't exist.
3261# 500: The server isn't configured properly, or
3262# an internal error occurred (e.g. failed assertions caused by bugs), or
3263# an unknown error occurred (e.g. the git binary died unexpectedly).
717b8311 3264sub die_error {
074afaa0
LW
3265 my $status = shift || 500;
3266 my $error = shift || "Internal server error";
3267
3268 my %http_responses = (400 => '400 Bad Request',
3269 403 => '403 Forbidden',
3270 404 => '404 Not Found',
3271 500 => '500 Internal Server Error');
3272 git_header_html($http_responses{$status});
59b9f61a
JN
3273 print <<EOF;
3274<div class="page_body">
3275<br /><br />
3276$status - $error
3277<br />
3278</div>
3279EOF
b87d78d6 3280 git_footer_html();
717b8311 3281 exit;
161332a5
KS
3282}
3283
717b8311
JN
3284## ----------------------------------------------------------------------
3285## functions printing or outputting HTML: navigation
3286
847e01fb 3287sub git_print_page_nav {
717b8311
JN
3288 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3289 $extra = '' if !defined $extra; # pager or formats
3290
3291 my @navs = qw(summary shortlog log commit commitdiff tree);
3292 if ($suppress) {
3293 @navs = grep { $_ ne $suppress } @navs;
3294 }
3295
1c2a4f5a 3296 my %arg = map { $_ => {action=>$_} } @navs;
717b8311
JN
3297 if (defined $head) {
3298 for (qw(commit commitdiff)) {
3be8e720 3299 $arg{$_}{'hash'} = $head;
717b8311
JN
3300 }
3301 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3302 for (qw(shortlog log)) {
3be8e720 3303 $arg{$_}{'hash'} = $head;
045e531a 3304 }
6a928415
KS
3305 }
3306 }
d627f68f 3307
3be8e720
JN
3308 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3309 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
717b8311 3310
a7c5a283 3311 my @actions = gitweb_get_feature('actions');
2b11e059
JN
3312 my %repl = (
3313 '%' => '%',
3314 'n' => $project, # project name
3315 'f' => $git_dir, # project path within filesystem
3316 'h' => $treehead || '', # current hash ('h' parameter)
3317 'b' => $treebase || '', # hash base ('hb' parameter)
3318 );
d627f68f 3319 while (@actions) {
2b11e059
JN
3320 my ($label, $link, $pos) = splice(@actions,0,3);
3321 # insert
d627f68f
PB
3322 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3323 # munch munch
2b11e059 3324 $link =~ s/%([%nfhb])/$repl{$1}/g;
d627f68f
PB
3325 $arg{$label}{'_href'} = $link;
3326 }
3327
717b8311
JN
3328 print "<div class=\"page_nav\">\n" .
3329 (join " | ",
1c2a4f5a 3330 map { $_ eq $current ?
d627f68f 3331 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
1c2a4f5a 3332 } @navs);
717b8311
JN
3333 print "<br/>\n$extra<br/>\n" .
3334 "</div>\n";
6a928415
KS
3335}
3336
847e01fb 3337sub format_paging_nav {
1f684dc0 3338 my ($action, $hash, $head, $page, $has_next_link) = @_;
717b8311 3339 my $paging_nav;
594e212b 3340
717b8311
JN
3341
3342 if ($hash ne $head || $page) {
1c2a4f5a 3343 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
594e212b 3344 } else {
717b8311
JN
3345 $paging_nav .= "HEAD";
3346 }
3347
3348 if ($page > 0) {
3349 $paging_nav .= " &sdot; " .
7afd77bf 3350 $cgi->a({-href => href(-replay=>1, page=>$page-1),
26298b5f 3351 -accesskey => "p", -title => "Alt-p"}, "prev");
717b8311
JN
3352 } else {
3353 $paging_nav .= " &sdot; prev";
3354 }
3355
1f684dc0 3356 if ($has_next_link) {
717b8311 3357 $paging_nav .= " &sdot; " .
7afd77bf 3358 $cgi->a({-href => href(-replay=>1, page=>$page+1),
26298b5f 3359 -accesskey => "n", -title => "Alt-n"}, "next");
717b8311
JN
3360 } else {
3361 $paging_nav .= " &sdot; next";
594e212b 3362 }
717b8311
JN
3363
3364 return $paging_nav;
594e212b
JN
3365}
3366
717b8311
JN
3367## ......................................................................
3368## functions printing or outputting HTML: div
3369
847e01fb 3370sub git_print_header_div {
717b8311 3371 my ($action, $title, $hash, $hash_base) = @_;
1c2a4f5a 3372 my %args = ();
717b8311 3373
3be8e720
JN
3374 $args{'action'} = $action;
3375 $args{'hash'} = $hash if $hash;
3376 $args{'hash_base'} = $hash_base if $hash_base;
717b8311
JN
3377
3378 print "<div class=\"header\">\n" .
1c2a4f5a
MW
3379 $cgi->a({-href => href(%args), -class => "title"},
3380 $title ? $title : $action) .
3381 "\n</div>\n";
717b8311 3382}
ede5e100 3383
1c49a4e1
GB
3384sub print_local_time {
3385 my %date = @_;
3386 if ($date{'hour_local'} < 6) {
3387 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3388 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3389 } else {
3390 printf(" (%02d:%02d %s)",
3391 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3392 }
3393}
3394
3395# Outputs the author name and date in long form
6fd92a28
JN
3396sub git_print_authorship {
3397 my $co = shift;
1c49a4e1
GB
3398 my %opts = @_;
3399 my $tag = $opts{-tag} || 'div';
e133d65c 3400 my $author = $co->{'author_name'};
6fd92a28 3401
a44465cc 3402 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1c49a4e1 3403 print "<$tag class=\"author_date\">" .
e133d65c 3404 format_search_author($author, "author", esc_html($author)) .
a44465cc 3405 " [$ad{'rfc2822'}";
1c49a4e1 3406 print_local_time(%ad) if ($opts{-localtime});
e9fdd74e
GB
3407 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3408 . "</$tag>\n";
1c49a4e1
GB
3409}
3410
3411# Outputs table rows containing the full author or committer information,
3412# in the format expected for 'commit' view (& similia).
3413# Parameters are a commit hash reference, followed by the list of people
3414# to output information for. If the list is empty it defalts to both
3415# author and committer.
3416sub git_print_authorship_rows {
3417 my $co = shift;
3418 # too bad we can't use @people = @_ || ('author', 'committer')
3419 my @people = @_;
3420 @people = ('author', 'committer') unless @people;
3421 foreach my $who (@people) {
3422 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
e133d65c
SB
3423 print "<tr><td>$who</td><td>" .
3424 format_search_author($co->{"${who}_name"}, $who,
3425 esc_html($co->{"${who}_name"})) . " " .
3426 format_search_author($co->{"${who}_email"}, $who,
3427 esc_html("<" . $co->{"${who}_email"} . ">")) .
3428 "</td><td rowspan=\"2\">" .
e9fdd74e
GB
3429 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3430 "</td></tr>\n" .
1c49a4e1
GB
3431 "<tr>" .
3432 "<td></td><td> $wd{'rfc2822'}";
3433 print_local_time(%wd);
3434 print "</td>" .
3435 "</tr>\n";
a44465cc 3436 }
6fd92a28
JN
3437}
3438
717b8311
JN
3439sub git_print_page_path {
3440 my $name = shift;
3441 my $type = shift;
59fb1c94 3442 my $hb = shift;
ede5e100 3443
4df118ed
JN
3444
3445 print "<div class=\"page_path\">";
3446 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
00f429af 3447 -title => 'tree root'}, to_utf8("[$project]"));
4df118ed
JN
3448 print " / ";
3449 if (defined $name) {
762c7205
JN
3450 my @dirname = split '/', $name;
3451 my $basename = pop @dirname;
3452 my $fullname = '';
3453
762c7205 3454 foreach my $dir (@dirname) {
16fdb488 3455 $fullname .= ($fullname ? '/' : '') . $dir;
762c7205
JN
3456 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3457 hash_base=>$hb),
edc04e90 3458 -title => $fullname}, esc_path($dir));
26d0a976 3459 print " / ";
762c7205
JN
3460 }
3461 if (defined $type && $type eq 'blob') {
952c65fc 3462 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
762c7205 3463 hash_base=>$hb),
edc04e90 3464 -title => $name}, esc_path($basename));
762c7205
JN
3465 } elsif (defined $type && $type eq 'tree') {
3466 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3467 hash_base=>$hb),
edc04e90 3468 -title => $name}, esc_path($basename));
4df118ed 3469 print " / ";
59fb1c94 3470 } else {
403d0906 3471 print esc_path($basename);
59fb1c94 3472 }
ede5e100 3473 }
4df118ed 3474 print "<br/></div>\n";
ede5e100
KS
3475}
3476
74fd8728 3477sub git_print_log {
d16d093c 3478 my $log = shift;
b7f9253d 3479 my %opts = @_;
d16d093c 3480
b7f9253d
JN
3481 if ($opts{'-remove_title'}) {
3482 # remove title, i.e. first line of log
3483 shift @$log;
3484 }
d16d093c
JN
3485 # remove leading empty lines
3486 while (defined $log->[0] && $log->[0] eq "") {
3487 shift @$log;
3488 }
3489
3490 # print log
3491 my $signoff = 0;
3492 my $empty = 0;
3493 foreach my $line (@$log) {
b7f9253d
JN
3494 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3495 $signoff = 1;
fba20b42 3496 $empty = 0;
b7f9253d
JN
3497 if (! $opts{'-remove_signoff'}) {
3498 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3499 next;
3500 } else {
3501 # remove signoff lines
3502 next;
3503 }
3504 } else {
3505 $signoff = 0;
3506 }
3507
d16d093c
JN
3508 # print only one empty line
3509 # do not print empty line after signoff
3510 if ($line eq "") {
3511 next if ($empty || $signoff);
3512 $empty = 1;
3513 } else {
3514 $empty = 0;
3515 }
b7f9253d
JN
3516
3517 print format_log_line_html($line) . "<br/>\n";
3518 }
3519