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