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