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