Sync with maint
[git.git] / gitweb / gitweb.perl
blob2417057f2bc61a98e68dc6c817e456a21bf6044e
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use 5.008;
11 use strict;
12 use warnings;
13 # handle ACL in file access tests
14 use filetest 'access';
15 use CGI qw(:standard :escapeHTML -nosticky);
16 use CGI::Util qw(unescape);
17 use CGI::Carp qw(fatalsToBrowser set_message);
18 use Encode;
19 use Fcntl ':mode';
20 use File::Find qw();
21 use File::Basename qw(basename);
22 use Time::HiRes qw(gettimeofday tv_interval);
23 binmode STDOUT, ':utf8';
25 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
26 eval 'sub CGI::multi_param { CGI::param(@_) }'
29 our $t0 = [ gettimeofday() ];
30 our $number_of_git_cmds = 0;
32 BEGIN {
33 CGI->compile() if $ENV{'MOD_PERL'};
36 our $version = "++GIT_VERSION++";
38 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
39 sub evaluate_uri {
40 our $cgi;
42 our $my_url = $cgi->url();
43 our $my_uri = $cgi->url(-absolute => 1);
45 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
46 # needed and used only for URLs with nonempty PATH_INFO
47 our $base_url = $my_url;
49 # When the script is used as DirectoryIndex, the URL does not contain the name
50 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
51 # have to do it ourselves. We make $path_info global because it's also used
52 # later on.
54 # Another issue with the script being the DirectoryIndex is that the resulting
55 # $my_url data is not the full script URL: this is good, because we want
56 # generated links to keep implying the script name if it wasn't explicitly
57 # indicated in the URL we're handling, but it means that $my_url cannot be used
58 # as base URL.
59 # Therefore, if we needed to strip PATH_INFO, then we know that we have
60 # to build the base URL ourselves:
61 our $path_info = decode_utf8($ENV{"PATH_INFO"});
62 if ($path_info) {
63 # $path_info has already been URL-decoded by the web server, but
64 # $my_url and $my_uri have not. URL-decode them so we can properly
65 # strip $path_info.
66 $my_url = unescape($my_url);
67 $my_uri = unescape($my_uri);
68 if ($my_url =~ s,\Q$path_info\E$,, &&
69 $my_uri =~ s,\Q$path_info\E$,, &&
70 defined $ENV{'SCRIPT_NAME'}) {
71 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
75 # target of the home link on top of all pages
76 our $home_link = $my_uri || "/";
79 # core git executable to use
80 # this can just be "git" if your webserver has a sensible PATH
81 our $GIT = "++GIT_BINDIR++/git";
83 # absolute fs-path which will be prepended to the project path
84 #our $projectroot = "/pub/scm";
85 our $projectroot = "++GITWEB_PROJECTROOT++";
87 # fs traversing limit for getting project list
88 # the number is relative to the projectroot
89 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
91 # string of the home link on top of all pages
92 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
94 # extra breadcrumbs preceding the home link
95 our @extra_breadcrumbs = ();
97 # name of your site or organization to appear in page titles
98 # replace this with something more descriptive for clearer bookmarks
99 our $site_name = "++GITWEB_SITENAME++"
100 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
102 # html snippet to include in the <head> section of each page
103 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
104 # filename of html text to include at top of each page
105 our $site_header = "++GITWEB_SITE_HEADER++";
106 # html text to include at home page
107 our $home_text = "++GITWEB_HOMETEXT++";
108 # filename of html text to include at bottom of each page
109 our $site_footer = "++GITWEB_SITE_FOOTER++";
111 # URI of stylesheets
112 our @stylesheets = ("++GITWEB_CSS++");
113 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
114 our $stylesheet = undef;
115 # URI of GIT logo (72x27 size)
116 our $logo = "++GITWEB_LOGO++";
117 # URI of GIT favicon, assumed to be image/png type
118 our $favicon = "++GITWEB_FAVICON++";
119 # URI of gitweb.js (JavaScript code for gitweb)
120 our $javascript = "++GITWEB_JS++";
122 # URI and label (title) of GIT logo link
123 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
124 #our $logo_label = "git documentation";
125 our $logo_url = "http://git-scm.com/";
126 our $logo_label = "git homepage";
128 # source of projects list
129 our $projects_list = "++GITWEB_LIST++";
131 # the width (in characters) of the projects list "Description" column
132 our $projects_list_description_width = 25;
134 # group projects by category on the projects list
135 # (enabled if this variable evaluates to true)
136 our $projects_list_group_categories = 0;
138 # default category if none specified
139 # (leave the empty string for no category)
140 our $project_list_default_category = "";
142 # default order of projects list
143 # valid values are none, project, descr, owner, and age
144 our $default_projects_order = "project";
146 # show repository only if this file exists
147 # (only effective if this variable evaluates to true)
148 our $export_ok = "++GITWEB_EXPORT_OK++";
150 # don't generate age column on the projects list page
151 our $omit_age_column = 0;
153 # don't generate information about owners of repositories
154 our $omit_owner=0;
156 # show repository only if this subroutine returns true
157 # when given the path to the project, for example:
158 # sub { return -e "$_[0]/git-daemon-export-ok"; }
159 our $export_auth_hook = undef;
161 # only allow viewing of repositories also shown on the overview page
162 our $strict_export = "++GITWEB_STRICT_EXPORT++";
164 # list of git base URLs used for URL to where fetch project from,
165 # i.e. full URL is "$git_base_url/$project"
166 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
168 # default blob_plain mimetype and default charset for text/plain blob
169 our $default_blob_plain_mimetype = 'text/plain';
170 our $default_text_plain_charset = undef;
172 # file to use for guessing MIME types before trying /etc/mime.types
173 # (relative to the current git repository)
174 our $mimetypes_file = undef;
176 # assume this charset if line contains non-UTF-8 characters;
177 # it should be valid encoding (see Encoding::Supported(3pm) for list),
178 # for which encoding all byte sequences are valid, for example
179 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
180 # could be even 'utf-8' for the old behavior)
181 our $fallback_encoding = 'latin1';
183 # rename detection options for git-diff and git-diff-tree
184 # - default is '-M', with the cost proportional to
185 # (number of removed files) * (number of new files).
186 # - more costly is '-C' (which implies '-M'), with the cost proportional to
187 # (number of changed files + number of removed files) * (number of new files)
188 # - even more costly is '-C', '--find-copies-harder' with cost
189 # (number of files in the original tree) * (number of new files)
190 # - one might want to include '-B' option, e.g. '-B', '-M'
191 our @diff_opts = ('-M'); # taken from git_commit
193 # Disables features that would allow repository owners to inject script into
194 # the gitweb domain.
195 our $prevent_xss = 0;
197 # Path to the highlight executable to use (must be the one from
198 # http://www.andre-simon.de due to assumptions about parameters and output).
199 # Useful if highlight is not installed on your webserver's PATH.
200 # [Default: highlight]
201 our $highlight_bin = "++HIGHLIGHT_BIN++";
203 # information about snapshot formats that gitweb is capable of serving
204 our %known_snapshot_formats = (
205 # name => {
206 # 'display' => display name,
207 # 'type' => mime type,
208 # 'suffix' => filename suffix,
209 # 'format' => --format for git-archive,
210 # 'compressor' => [compressor command and arguments]
211 # (array reference, optional)
212 # 'disabled' => boolean (optional)}
214 'tgz' => {
215 'display' => 'tar.gz',
216 'type' => 'application/x-gzip',
217 'suffix' => '.tar.gz',
218 'format' => 'tar',
219 'compressor' => ['gzip', '-n']},
221 'tbz2' => {
222 'display' => 'tar.bz2',
223 'type' => 'application/x-bzip2',
224 'suffix' => '.tar.bz2',
225 'format' => 'tar',
226 'compressor' => ['bzip2']},
228 'txz' => {
229 'display' => 'tar.xz',
230 'type' => 'application/x-xz',
231 'suffix' => '.tar.xz',
232 'format' => 'tar',
233 'compressor' => ['xz'],
234 'disabled' => 1},
236 'zip' => {
237 'display' => 'zip',
238 'type' => 'application/x-zip',
239 'suffix' => '.zip',
240 'format' => 'zip'},
243 # Aliases so we understand old gitweb.snapshot values in repository
244 # configuration.
245 our %known_snapshot_format_aliases = (
246 'gzip' => 'tgz',
247 'bzip2' => 'tbz2',
248 'xz' => 'txz',
250 # backward compatibility: legacy gitweb config support
251 'x-gzip' => undef, 'gz' => undef,
252 'x-bzip2' => undef, 'bz2' => undef,
253 'x-zip' => undef, '' => undef,
256 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
257 # are changed, it may be appropriate to change these values too via
258 # $GITWEB_CONFIG.
259 our %avatar_size = (
260 'default' => 16,
261 'double' => 32
264 # Used to set the maximum load that we will still respond to gitweb queries.
265 # If server load exceed this value then return "503 server busy" error.
266 # If gitweb cannot determined server load, it is taken to be 0.
267 # Leave it undefined (or set to 'undef') to turn off load checking.
268 our $maxload = 300;
270 # configuration for 'highlight' (http://www.andre-simon.de/)
271 # match by basename
272 our %highlight_basename = (
273 #'Program' => 'py',
274 #'Library' => 'py',
275 'SConstruct' => 'py', # SCons equivalent of Makefile
276 'Makefile' => 'make',
278 # match by extension
279 our %highlight_ext = (
280 # main extensions, defining name of syntax;
281 # see files in /usr/share/highlight/langDefs/ directory
282 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
283 # alternate extensions, see /etc/highlight/filetypes.conf
284 (map { $_ => 'c' } qw(c h)),
285 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
286 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
287 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
288 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
289 (map { $_ => 'make'} qw(make mak mk)),
290 (map { $_ => 'xml' } qw(xml xhtml html htm)),
293 # You define site-wide feature defaults here; override them with
294 # $GITWEB_CONFIG as necessary.
295 our %feature = (
296 # feature => {
297 # 'sub' => feature-sub (subroutine),
298 # 'override' => allow-override (boolean),
299 # 'default' => [ default options...] (array reference)}
301 # if feature is overridable (it means that allow-override has true value),
302 # then feature-sub will be called with default options as parameters;
303 # return value of feature-sub indicates if to enable specified feature
305 # if there is no 'sub' key (no feature-sub), then feature cannot be
306 # overridden
308 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
309 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
310 # is enabled
312 # Enable the 'blame' blob view, showing the last commit that modified
313 # each line in the file. This can be very CPU-intensive.
315 # To enable system wide have in $GITWEB_CONFIG
316 # $feature{'blame'}{'default'} = [1];
317 # To have project specific config enable override in $GITWEB_CONFIG
318 # $feature{'blame'}{'override'} = 1;
319 # and in project config gitweb.blame = 0|1;
320 'blame' => {
321 'sub' => sub { feature_bool('blame', @_) },
322 'override' => 0,
323 'default' => [0]},
325 # Enable the 'snapshot' link, providing a compressed archive of any
326 # tree. This can potentially generate high traffic if you have large
327 # project.
329 # Value is a list of formats defined in %known_snapshot_formats that
330 # you wish to offer.
331 # To disable system wide have in $GITWEB_CONFIG
332 # $feature{'snapshot'}{'default'} = [];
333 # To have project specific config enable override in $GITWEB_CONFIG
334 # $feature{'snapshot'}{'override'} = 1;
335 # and in project config, a comma-separated list of formats or "none"
336 # to disable. Example: gitweb.snapshot = tbz2,zip;
337 'snapshot' => {
338 'sub' => \&feature_snapshot,
339 'override' => 0,
340 'default' => ['tgz']},
342 # Enable text search, which will list the commits which match author,
343 # committer or commit text to a given string. Enabled by default.
344 # Project specific override is not supported.
346 # Note that this controls all search features, which means that if
347 # it is disabled, then 'grep' and 'pickaxe' search would also be
348 # disabled.
349 'search' => {
350 'override' => 0,
351 'default' => [1]},
353 # Enable grep search, which will list the files in currently selected
354 # tree containing the given string. Enabled by default. This can be
355 # potentially CPU-intensive, of course.
356 # Note that you need to have 'search' feature enabled too.
358 # To enable system wide have in $GITWEB_CONFIG
359 # $feature{'grep'}{'default'} = [1];
360 # To have project specific config enable override in $GITWEB_CONFIG
361 # $feature{'grep'}{'override'} = 1;
362 # and in project config gitweb.grep = 0|1;
363 'grep' => {
364 'sub' => sub { feature_bool('grep', @_) },
365 'override' => 0,
366 'default' => [1]},
368 # Enable the pickaxe search, which will list the commits that modified
369 # a given string in a file. This can be practical and quite faster
370 # alternative to 'blame', but still potentially CPU-intensive.
371 # Note that you need to have 'search' feature enabled too.
373 # To enable system wide have in $GITWEB_CONFIG
374 # $feature{'pickaxe'}{'default'} = [1];
375 # To have project specific config enable override in $GITWEB_CONFIG
376 # $feature{'pickaxe'}{'override'} = 1;
377 # and in project config gitweb.pickaxe = 0|1;
378 'pickaxe' => {
379 'sub' => sub { feature_bool('pickaxe', @_) },
380 'override' => 0,
381 'default' => [1]},
383 # Enable showing size of blobs in a 'tree' view, in a separate
384 # column, similar to what 'ls -l' does. This cost a bit of IO.
386 # To disable system wide have in $GITWEB_CONFIG
387 # $feature{'show-sizes'}{'default'} = [0];
388 # To have project specific config enable override in $GITWEB_CONFIG
389 # $feature{'show-sizes'}{'override'} = 1;
390 # and in project config gitweb.showsizes = 0|1;
391 'show-sizes' => {
392 'sub' => sub { feature_bool('showsizes', @_) },
393 'override' => 0,
394 'default' => [1]},
396 # Make gitweb use an alternative format of the URLs which can be
397 # more readable and natural-looking: project name is embedded
398 # directly in the path and the query string contains other
399 # auxiliary information. All gitweb installations recognize
400 # URL in either format; this configures in which formats gitweb
401 # generates links.
403 # To enable system wide have in $GITWEB_CONFIG
404 # $feature{'pathinfo'}{'default'} = [1];
405 # Project specific override is not supported.
407 # Note that you will need to change the default location of CSS,
408 # favicon, logo and possibly other files to an absolute URL. Also,
409 # if gitweb.cgi serves as your indexfile, you will need to force
410 # $my_uri to contain the script name in your $GITWEB_CONFIG.
411 'pathinfo' => {
412 'override' => 0,
413 'default' => [0]},
415 # Make gitweb consider projects in project root subdirectories
416 # to be forks of existing projects. Given project $projname.git,
417 # projects matching $projname/*.git will not be shown in the main
418 # projects list, instead a '+' mark will be added to $projname
419 # there and a 'forks' view will be enabled for the project, listing
420 # all the forks. If project list is taken from a file, forks have
421 # to be listed after the main project.
423 # To enable system wide have in $GITWEB_CONFIG
424 # $feature{'forks'}{'default'} = [1];
425 # Project specific override is not supported.
426 'forks' => {
427 'override' => 0,
428 'default' => [0]},
430 # Insert custom links to the action bar of all project pages.
431 # This enables you mainly to link to third-party scripts integrating
432 # into gitweb; e.g. git-browser for graphical history representation
433 # or custom web-based repository administration interface.
435 # The 'default' value consists of a list of triplets in the form
436 # (label, link, position) where position is the label after which
437 # to insert the link and link is a format string where %n expands
438 # to the project name, %f to the project path within the filesystem,
439 # %h to the current hash (h gitweb parameter) and %b to the current
440 # hash base (hb gitweb parameter); %% expands to %.
442 # To enable system wide have in $GITWEB_CONFIG e.g.
443 # $feature{'actions'}{'default'} = [('graphiclog',
444 # '/git-browser/by-commit.html?r=%n', 'summary')];
445 # Project specific override is not supported.
446 'actions' => {
447 'override' => 0,
448 'default' => []},
450 # Allow gitweb scan project content tags of project repository,
451 # and display the popular Web 2.0-ish "tag cloud" near the projects
452 # list. Note that this is something COMPLETELY different from the
453 # normal Git tags.
455 # gitweb by itself can show existing tags, but it does not handle
456 # tagging itself; you need to do it externally, outside gitweb.
457 # The format is described in git_get_project_ctags() subroutine.
458 # You may want to install the HTML::TagCloud Perl module to get
459 # a pretty tag cloud instead of just a list of tags.
461 # To enable system wide have in $GITWEB_CONFIG
462 # $feature{'ctags'}{'default'} = [1];
463 # Project specific override is not supported.
465 # In the future whether ctags editing is enabled might depend
466 # on the value, but using 1 should always mean no editing of ctags.
467 'ctags' => {
468 'override' => 0,
469 'default' => [0]},
471 # The maximum number of patches in a patchset generated in patch
472 # view. Set this to 0 or undef to disable patch view, or to a
473 # negative number to remove any limit.
475 # To disable system wide have in $GITWEB_CONFIG
476 # $feature{'patches'}{'default'} = [0];
477 # To have project specific config enable override in $GITWEB_CONFIG
478 # $feature{'patches'}{'override'} = 1;
479 # and in project config gitweb.patches = 0|n;
480 # where n is the maximum number of patches allowed in a patchset.
481 'patches' => {
482 'sub' => \&feature_patches,
483 'override' => 0,
484 'default' => [16]},
486 # Avatar support. When this feature is enabled, views such as
487 # shortlog or commit will display an avatar associated with
488 # the email of the committer(s) and/or author(s).
490 # Currently available providers are gravatar and picon.
491 # If an unknown provider is specified, the feature is disabled.
493 # Gravatar depends on Digest::MD5.
494 # Picon currently relies on the indiana.edu database.
496 # To enable system wide have in $GITWEB_CONFIG
497 # $feature{'avatar'}{'default'} = ['<provider>'];
498 # where <provider> is either gravatar or picon.
499 # To have project specific config enable override in $GITWEB_CONFIG
500 # $feature{'avatar'}{'override'} = 1;
501 # and in project config gitweb.avatar = <provider>;
502 'avatar' => {
503 'sub' => \&feature_avatar,
504 'override' => 0,
505 'default' => ['']},
507 # Enable displaying how much time and how many git commands
508 # it took to generate and display page. Disabled by default.
509 # Project specific override is not supported.
510 'timed' => {
511 'override' => 0,
512 'default' => [0]},
514 # Enable turning some links into links to actions which require
515 # JavaScript to run (like 'blame_incremental'). Not enabled by
516 # default. Project specific override is currently not supported.
517 'javascript-actions' => {
518 'override' => 0,
519 'default' => [0]},
521 # Enable and configure ability to change common timezone for dates
522 # in gitweb output via JavaScript. Enabled by default.
523 # Project specific override is not supported.
524 'javascript-timezone' => {
525 'override' => 0,
526 'default' => [
527 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
528 # or undef to turn off this feature
529 'gitweb_tz', # name of cookie where to store selected timezone
530 'datetime', # CSS class used to mark up dates for manipulation
533 # Syntax highlighting support. This is based on Daniel Svensson's
534 # and Sham Chukoury's work in gitweb-xmms2.git.
535 # It requires the 'highlight' program present in $PATH,
536 # and therefore is disabled by default.
538 # To enable system wide have in $GITWEB_CONFIG
539 # $feature{'highlight'}{'default'} = [1];
541 'highlight' => {
542 'sub' => sub { feature_bool('highlight', @_) },
543 'override' => 0,
544 'default' => [0]},
546 # Enable displaying of remote heads in the heads list
548 # To enable system wide have in $GITWEB_CONFIG
549 # $feature{'remote_heads'}{'default'} = [1];
550 # To have project specific config enable override in $GITWEB_CONFIG
551 # $feature{'remote_heads'}{'override'} = 1;
552 # and in project config gitweb.remoteheads = 0|1;
553 'remote_heads' => {
554 'sub' => sub { feature_bool('remote_heads', @_) },
555 'override' => 0,
556 'default' => [0]},
558 # Enable showing branches under other refs in addition to heads
560 # To set system wide extra branch refs have in $GITWEB_CONFIG
561 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
562 # To have project specific config enable override in $GITWEB_CONFIG
563 # $feature{'extra-branch-refs'}{'override'} = 1;
564 # and in project config gitweb.extrabranchrefs = dirs of choice
565 # Every directory is separated with whitespace.
567 'extra-branch-refs' => {
568 'sub' => \&feature_extra_branch_refs,
569 'override' => 0,
570 'default' => []},
573 sub gitweb_get_feature {
574 my ($name) = @_;
575 return unless exists $feature{$name};
576 my ($sub, $override, @defaults) = (
577 $feature{$name}{'sub'},
578 $feature{$name}{'override'},
579 @{$feature{$name}{'default'}});
580 # project specific override is possible only if we have project
581 our $git_dir; # global variable, declared later
582 if (!$override || !defined $git_dir) {
583 return @defaults;
585 if (!defined $sub) {
586 warn "feature $name is not overridable";
587 return @defaults;
589 return $sub->(@defaults);
592 # A wrapper to check if a given feature is enabled.
593 # With this, you can say
595 # my $bool_feat = gitweb_check_feature('bool_feat');
596 # gitweb_check_feature('bool_feat') or somecode;
598 # instead of
600 # my ($bool_feat) = gitweb_get_feature('bool_feat');
601 # (gitweb_get_feature('bool_feat'))[0] or somecode;
603 sub gitweb_check_feature {
604 return (gitweb_get_feature(@_))[0];
608 sub feature_bool {
609 my $key = shift;
610 my ($val) = git_get_project_config($key, '--bool');
612 if (!defined $val) {
613 return ($_[0]);
614 } elsif ($val eq 'true') {
615 return (1);
616 } elsif ($val eq 'false') {
617 return (0);
621 sub feature_snapshot {
622 my (@fmts) = @_;
624 my ($val) = git_get_project_config('snapshot');
626 if ($val) {
627 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
630 return @fmts;
633 sub feature_patches {
634 my @val = (git_get_project_config('patches', '--int'));
636 if (@val) {
637 return @val;
640 return ($_[0]);
643 sub feature_avatar {
644 my @val = (git_get_project_config('avatar'));
646 return @val ? @val : @_;
649 sub feature_extra_branch_refs {
650 my (@branch_refs) = @_;
651 my $values = git_get_project_config('extrabranchrefs');
653 if ($values) {
654 $values = config_to_multi ($values);
655 @branch_refs = ();
656 foreach my $value (@{$values}) {
657 push @branch_refs, split /\s+/, $value;
661 return @branch_refs;
664 # checking HEAD file with -e is fragile if the repository was
665 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
666 # and then pruned.
667 sub check_head_link {
668 my ($dir) = @_;
669 my $headfile = "$dir/HEAD";
670 return ((-e $headfile) ||
671 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
674 sub check_export_ok {
675 my ($dir) = @_;
676 return (check_head_link($dir) &&
677 (!$export_ok || -e "$dir/$export_ok") &&
678 (!$export_auth_hook || $export_auth_hook->($dir)));
681 # process alternate names for backward compatibility
682 # filter out unsupported (unknown) snapshot formats
683 sub filter_snapshot_fmts {
684 my @fmts = @_;
686 @fmts = map {
687 exists $known_snapshot_format_aliases{$_} ?
688 $known_snapshot_format_aliases{$_} : $_} @fmts;
689 @fmts = grep {
690 exists $known_snapshot_formats{$_} &&
691 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
694 sub filter_and_validate_refs {
695 my @refs = @_;
696 my %unique_refs = ();
698 foreach my $ref (@refs) {
699 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
700 # 'heads' are added implicitly in get_branch_refs().
701 $unique_refs{$ref} = 1 if ($ref ne 'heads');
703 return sort keys %unique_refs;
706 # If it is set to code reference, it is code that it is to be run once per
707 # request, allowing updating configurations that change with each request,
708 # while running other code in config file only once.
710 # Otherwise, if it is false then gitweb would process config file only once;
711 # if it is true then gitweb config would be run for each request.
712 our $per_request_config = 1;
714 # read and parse gitweb config file given by its parameter.
715 # returns true on success, false on recoverable error, allowing
716 # to chain this subroutine, using first file that exists.
717 # dies on errors during parsing config file, as it is unrecoverable.
718 sub read_config_file {
719 my $filename = shift;
720 return unless defined $filename;
721 # die if there are errors parsing config file
722 if (-e $filename) {
723 do $filename;
724 die $@ if $@;
725 return 1;
727 return;
730 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
731 sub evaluate_gitweb_config {
732 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
733 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
734 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
736 # Protect against duplications of file names, to not read config twice.
737 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
738 # there possibility of duplication of filename there doesn't matter.
739 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
740 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
742 # Common system-wide settings for convenience.
743 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
744 read_config_file($GITWEB_CONFIG_COMMON);
746 # Use first config file that exists. This means use the per-instance
747 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
748 read_config_file($GITWEB_CONFIG) and return;
749 read_config_file($GITWEB_CONFIG_SYSTEM);
752 # Get loadavg of system, to compare against $maxload.
753 # Currently it requires '/proc/loadavg' present to get loadavg;
754 # if it is not present it returns 0, which means no load checking.
755 sub get_loadavg {
756 if( -e '/proc/loadavg' ){
757 open my $fd, '<', '/proc/loadavg'
758 or return 0;
759 my @load = split(/\s+/, scalar <$fd>);
760 close $fd;
762 # The first three columns measure CPU and IO utilization of the last one,
763 # five, and 10 minute periods. The fourth column shows the number of
764 # currently running processes and the total number of processes in the m/n
765 # format. The last column displays the last process ID used.
766 return $load[0] || 0;
768 # additional checks for load average should go here for things that don't export
769 # /proc/loadavg
771 return 0;
774 # version of the core git binary
775 our $git_version;
776 sub evaluate_git_version {
777 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
778 $number_of_git_cmds++;
781 sub check_loadavg {
782 if (defined $maxload && get_loadavg() > $maxload) {
783 die_error(503, "The load average on the server is too high");
787 # ======================================================================
788 # input validation and dispatch
790 # input parameters can be collected from a variety of sources (presently, CGI
791 # and PATH_INFO), so we define an %input_params hash that collects them all
792 # together during validation: this allows subsequent uses (e.g. href()) to be
793 # agnostic of the parameter origin
795 our %input_params = ();
797 # input parameters are stored with the long parameter name as key. This will
798 # also be used in the href subroutine to convert parameters to their CGI
799 # equivalent, and since the href() usage is the most frequent one, we store
800 # the name -> CGI key mapping here, instead of the reverse.
802 # XXX: Warning: If you touch this, check the search form for updating,
803 # too.
805 our @cgi_param_mapping = (
806 project => "p",
807 action => "a",
808 file_name => "f",
809 file_parent => "fp",
810 hash => "h",
811 hash_parent => "hp",
812 hash_base => "hb",
813 hash_parent_base => "hpb",
814 page => "pg",
815 order => "o",
816 searchtext => "s",
817 searchtype => "st",
818 snapshot_format => "sf",
819 extra_options => "opt",
820 search_use_regexp => "sr",
821 ctag => "by_tag",
822 diff_style => "ds",
823 project_filter => "pf",
824 # this must be last entry (for manipulation from JavaScript)
825 javascript => "js"
827 our %cgi_param_mapping = @cgi_param_mapping;
829 # we will also need to know the possible actions, for validation
830 our %actions = (
831 "blame" => \&git_blame,
832 "blame_incremental" => \&git_blame_incremental,
833 "blame_data" => \&git_blame_data,
834 "blobdiff" => \&git_blobdiff,
835 "blobdiff_plain" => \&git_blobdiff_plain,
836 "blob" => \&git_blob,
837 "blob_plain" => \&git_blob_plain,
838 "commitdiff" => \&git_commitdiff,
839 "commitdiff_plain" => \&git_commitdiff_plain,
840 "commit" => \&git_commit,
841 "forks" => \&git_forks,
842 "heads" => \&git_heads,
843 "history" => \&git_history,
844 "log" => \&git_log,
845 "patch" => \&git_patch,
846 "patches" => \&git_patches,
847 "remotes" => \&git_remotes,
848 "rss" => \&git_rss,
849 "atom" => \&git_atom,
850 "search" => \&git_search,
851 "search_help" => \&git_search_help,
852 "shortlog" => \&git_shortlog,
853 "summary" => \&git_summary,
854 "tag" => \&git_tag,
855 "tags" => \&git_tags,
856 "tree" => \&git_tree,
857 "snapshot" => \&git_snapshot,
858 "object" => \&git_object,
859 # those below don't need $project
860 "opml" => \&git_opml,
861 "project_list" => \&git_project_list,
862 "project_index" => \&git_project_index,
865 # finally, we have the hash of allowed extra_options for the commands that
866 # allow them
867 our %allowed_options = (
868 "--no-merges" => [ qw(rss atom log shortlog history) ],
871 # fill %input_params with the CGI parameters. All values except for 'opt'
872 # should be single values, but opt can be an array. We should probably
873 # build an array of parameters that can be multi-valued, but since for the time
874 # being it's only this one, we just single it out
875 sub evaluate_query_params {
876 our $cgi;
878 while (my ($name, $symbol) = each %cgi_param_mapping) {
879 if ($symbol eq 'opt') {
880 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
881 } else {
882 $input_params{$name} = decode_utf8($cgi->param($symbol));
887 # now read PATH_INFO and update the parameter list for missing parameters
888 sub evaluate_path_info {
889 return if defined $input_params{'project'};
890 return if !$path_info;
891 $path_info =~ s,^/+,,;
892 return if !$path_info;
894 # find which part of PATH_INFO is project
895 my $project = $path_info;
896 $project =~ s,/+$,,;
897 while ($project && !check_head_link("$projectroot/$project")) {
898 $project =~ s,/*[^/]*$,,;
900 return unless $project;
901 $input_params{'project'} = $project;
903 # do not change any parameters if an action is given using the query string
904 return if $input_params{'action'};
905 $path_info =~ s,^\Q$project\E/*,,;
907 # next, check if we have an action
908 my $action = $path_info;
909 $action =~ s,/.*$,,;
910 if (exists $actions{$action}) {
911 $path_info =~ s,^$action/*,,;
912 $input_params{'action'} = $action;
915 # list of actions that want hash_base instead of hash, but can have no
916 # pathname (f) parameter
917 my @wants_base = (
918 'tree',
919 'history',
922 # we want to catch, among others
923 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
924 my ($parentrefname, $parentpathname, $refname, $pathname) =
925 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
927 # first, analyze the 'current' part
928 if (defined $pathname) {
929 # we got "branch:filename" or "branch:dir/"
930 # we could use git_get_type(branch:pathname), but:
931 # - it needs $git_dir
932 # - it does a git() call
933 # - the convention of terminating directories with a slash
934 # makes it superfluous
935 # - embedding the action in the PATH_INFO would make it even
936 # more superfluous
937 $pathname =~ s,^/+,,;
938 if (!$pathname || substr($pathname, -1) eq "/") {
939 $input_params{'action'} ||= "tree";
940 $pathname =~ s,/$,,;
941 } else {
942 # the default action depends on whether we had parent info
943 # or not
944 if ($parentrefname) {
945 $input_params{'action'} ||= "blobdiff_plain";
946 } else {
947 $input_params{'action'} ||= "blob_plain";
950 $input_params{'hash_base'} ||= $refname;
951 $input_params{'file_name'} ||= $pathname;
952 } elsif (defined $refname) {
953 # we got "branch". In this case we have to choose if we have to
954 # set hash or hash_base.
956 # Most of the actions without a pathname only want hash to be
957 # set, except for the ones specified in @wants_base that want
958 # hash_base instead. It should also be noted that hand-crafted
959 # links having 'history' as an action and no pathname or hash
960 # set will fail, but that happens regardless of PATH_INFO.
961 if (defined $parentrefname) {
962 # if there is parent let the default be 'shortlog' action
963 # (for http://git.example.com/repo.git/A..B links); if there
964 # is no parent, dispatch will detect type of object and set
965 # action appropriately if required (if action is not set)
966 $input_params{'action'} ||= "shortlog";
968 if ($input_params{'action'} &&
969 grep { $_ eq $input_params{'action'} } @wants_base) {
970 $input_params{'hash_base'} ||= $refname;
971 } else {
972 $input_params{'hash'} ||= $refname;
976 # next, handle the 'parent' part, if present
977 if (defined $parentrefname) {
978 # a missing pathspec defaults to the 'current' filename, allowing e.g.
979 # someproject/blobdiff/oldrev..newrev:/filename
980 if ($parentpathname) {
981 $parentpathname =~ s,^/+,,;
982 $parentpathname =~ s,/$,,;
983 $input_params{'file_parent'} ||= $parentpathname;
984 } else {
985 $input_params{'file_parent'} ||= $input_params{'file_name'};
987 # we assume that hash_parent_base is wanted if a path was specified,
988 # or if the action wants hash_base instead of hash
989 if (defined $input_params{'file_parent'} ||
990 grep { $_ eq $input_params{'action'} } @wants_base) {
991 $input_params{'hash_parent_base'} ||= $parentrefname;
992 } else {
993 $input_params{'hash_parent'} ||= $parentrefname;
997 # for the snapshot action, we allow URLs in the form
998 # $project/snapshot/$hash.ext
999 # where .ext determines the snapshot and gets removed from the
1000 # passed $refname to provide the $hash.
1002 # To be able to tell that $refname includes the format extension, we
1003 # require the following two conditions to be satisfied:
1004 # - the hash input parameter MUST have been set from the $refname part
1005 # of the URL (i.e. they must be equal)
1006 # - the snapshot format MUST NOT have been defined already (e.g. from
1007 # CGI parameter sf)
1008 # It's also useless to try any matching unless $refname has a dot,
1009 # so we check for that too
1010 if (defined $input_params{'action'} &&
1011 $input_params{'action'} eq 'snapshot' &&
1012 defined $refname && index($refname, '.') != -1 &&
1013 $refname eq $input_params{'hash'} &&
1014 !defined $input_params{'snapshot_format'}) {
1015 # We loop over the known snapshot formats, checking for
1016 # extensions. Allowed extensions are both the defined suffix
1017 # (which includes the initial dot already) and the snapshot
1018 # format key itself, with a prepended dot
1019 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1020 my $hash = $refname;
1021 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1022 next;
1024 my $sfx = $1;
1025 # a valid suffix was found, so set the snapshot format
1026 # and reset the hash parameter
1027 $input_params{'snapshot_format'} = $fmt;
1028 $input_params{'hash'} = $hash;
1029 # we also set the format suffix to the one requested
1030 # in the URL: this way a request for e.g. .tgz returns
1031 # a .tgz instead of a .tar.gz
1032 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1033 last;
1038 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1039 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1040 $searchtext, $search_regexp, $project_filter);
1041 sub evaluate_and_validate_params {
1042 our $action = $input_params{'action'};
1043 if (defined $action) {
1044 if (!is_valid_action($action)) {
1045 die_error(400, "Invalid action parameter");
1049 # parameters which are pathnames
1050 our $project = $input_params{'project'};
1051 if (defined $project) {
1052 if (!is_valid_project($project)) {
1053 undef $project;
1054 die_error(404, "No such project");
1058 our $project_filter = $input_params{'project_filter'};
1059 if (defined $project_filter) {
1060 if (!is_valid_pathname($project_filter)) {
1061 die_error(404, "Invalid project_filter parameter");
1065 our $file_name = $input_params{'file_name'};
1066 if (defined $file_name) {
1067 if (!is_valid_pathname($file_name)) {
1068 die_error(400, "Invalid file parameter");
1072 our $file_parent = $input_params{'file_parent'};
1073 if (defined $file_parent) {
1074 if (!is_valid_pathname($file_parent)) {
1075 die_error(400, "Invalid file parent parameter");
1079 # parameters which are refnames
1080 our $hash = $input_params{'hash'};
1081 if (defined $hash) {
1082 if (!is_valid_refname($hash)) {
1083 die_error(400, "Invalid hash parameter");
1087 our $hash_parent = $input_params{'hash_parent'};
1088 if (defined $hash_parent) {
1089 if (!is_valid_refname($hash_parent)) {
1090 die_error(400, "Invalid hash parent parameter");
1094 our $hash_base = $input_params{'hash_base'};
1095 if (defined $hash_base) {
1096 if (!is_valid_refname($hash_base)) {
1097 die_error(400, "Invalid hash base parameter");
1101 our @extra_options = @{$input_params{'extra_options'}};
1102 # @extra_options is always defined, since it can only be (currently) set from
1103 # CGI, and $cgi->param() returns the empty array in array context if the param
1104 # is not set
1105 foreach my $opt (@extra_options) {
1106 if (not exists $allowed_options{$opt}) {
1107 die_error(400, "Invalid option parameter");
1109 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1110 die_error(400, "Invalid option parameter for this action");
1114 our $hash_parent_base = $input_params{'hash_parent_base'};
1115 if (defined $hash_parent_base) {
1116 if (!is_valid_refname($hash_parent_base)) {
1117 die_error(400, "Invalid hash parent base parameter");
1121 # other parameters
1122 our $page = $input_params{'page'};
1123 if (defined $page) {
1124 if ($page =~ m/[^0-9]/) {
1125 die_error(400, "Invalid page parameter");
1129 our $searchtype = $input_params{'searchtype'};
1130 if (defined $searchtype) {
1131 if ($searchtype =~ m/[^a-z]/) {
1132 die_error(400, "Invalid searchtype parameter");
1136 our $search_use_regexp = $input_params{'search_use_regexp'};
1138 our $searchtext = $input_params{'searchtext'};
1139 our $search_regexp = undef;
1140 if (defined $searchtext) {
1141 if (length($searchtext) < 2) {
1142 die_error(403, "At least two characters are required for search parameter");
1144 if ($search_use_regexp) {
1145 $search_regexp = $searchtext;
1146 if (!eval { qr/$search_regexp/; 1; }) {
1147 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1148 die_error(400, "Invalid search regexp '$search_regexp'",
1149 esc_html($error));
1151 } else {
1152 $search_regexp = quotemeta $searchtext;
1157 # path to the current git repository
1158 our $git_dir;
1159 sub evaluate_git_dir {
1160 our $git_dir = "$projectroot/$project" if $project;
1163 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1164 sub configure_gitweb_features {
1165 # list of supported snapshot formats
1166 our @snapshot_fmts = gitweb_get_feature('snapshot');
1167 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1169 # check that the avatar feature is set to a known provider name,
1170 # and for each provider check if the dependencies are satisfied.
1171 # if the provider name is invalid or the dependencies are not met,
1172 # reset $git_avatar to the empty string.
1173 our ($git_avatar) = gitweb_get_feature('avatar');
1174 if ($git_avatar eq 'gravatar') {
1175 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1176 } elsif ($git_avatar eq 'picon') {
1177 # no dependencies
1178 } else {
1179 $git_avatar = '';
1182 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1183 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1186 sub get_branch_refs {
1187 return ('heads', @extra_branch_refs);
1190 # custom error handler: 'die <message>' is Internal Server Error
1191 sub handle_errors_html {
1192 my $msg = shift; # it is already HTML escaped
1194 # to avoid infinite loop where error occurs in die_error,
1195 # change handler to default handler, disabling handle_errors_html
1196 set_message("Error occurred when inside die_error:\n$msg");
1198 # you cannot jump out of die_error when called as error handler;
1199 # the subroutine set via CGI::Carp::set_message is called _after_
1200 # HTTP headers are already written, so it cannot write them itself
1201 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1203 set_message(\&handle_errors_html);
1205 # dispatch
1206 sub dispatch {
1207 if (!defined $action) {
1208 if (defined $hash) {
1209 $action = git_get_type($hash);
1210 $action or die_error(404, "Object does not exist");
1211 } elsif (defined $hash_base && defined $file_name) {
1212 $action = git_get_type("$hash_base:$file_name");
1213 $action or die_error(404, "File or directory does not exist");
1214 } elsif (defined $project) {
1215 $action = 'summary';
1216 } else {
1217 $action = 'project_list';
1220 if (!defined($actions{$action})) {
1221 die_error(400, "Unknown action");
1223 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1224 !$project) {
1225 die_error(400, "Project needed");
1227 $actions{$action}->();
1230 sub reset_timer {
1231 our $t0 = [ gettimeofday() ]
1232 if defined $t0;
1233 our $number_of_git_cmds = 0;
1236 our $first_request = 1;
1237 sub run_request {
1238 reset_timer();
1240 evaluate_uri();
1241 if ($first_request) {
1242 evaluate_gitweb_config();
1243 evaluate_git_version();
1245 if ($per_request_config) {
1246 if (ref($per_request_config) eq 'CODE') {
1247 $per_request_config->();
1248 } elsif (!$first_request) {
1249 evaluate_gitweb_config();
1252 check_loadavg();
1254 # $projectroot and $projects_list might be set in gitweb config file
1255 $projects_list ||= $projectroot;
1257 evaluate_query_params();
1258 evaluate_path_info();
1259 evaluate_and_validate_params();
1260 evaluate_git_dir();
1262 configure_gitweb_features();
1264 dispatch();
1267 our $is_last_request = sub { 1 };
1268 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1269 our $CGI = 'CGI';
1270 our $cgi;
1271 sub configure_as_fcgi {
1272 require CGI::Fast;
1273 our $CGI = 'CGI::Fast';
1275 my $request_number = 0;
1276 # let each child service 100 requests
1277 our $is_last_request = sub { ++$request_number > 100 };
1279 sub evaluate_argv {
1280 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1281 configure_as_fcgi()
1282 if $script_name =~ /\.fcgi$/;
1284 return unless (@ARGV);
1286 require Getopt::Long;
1287 Getopt::Long::GetOptions(
1288 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1289 'nproc|n=i' => sub {
1290 my ($arg, $val) = @_;
1291 return unless eval { require FCGI::ProcManager; 1; };
1292 my $proc_manager = FCGI::ProcManager->new({
1293 n_processes => $val,
1295 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1296 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1297 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1302 sub run {
1303 evaluate_argv();
1305 $first_request = 1;
1306 $pre_listen_hook->()
1307 if $pre_listen_hook;
1309 REQUEST:
1310 while ($cgi = $CGI->new()) {
1311 $pre_dispatch_hook->()
1312 if $pre_dispatch_hook;
1314 run_request();
1316 $post_dispatch_hook->()
1317 if $post_dispatch_hook;
1318 $first_request = 0;
1320 last REQUEST if ($is_last_request->());
1323 DONE_GITWEB:
1327 run();
1329 if (defined caller) {
1330 # wrapped in a subroutine processing requests,
1331 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1332 return;
1333 } else {
1334 # pure CGI script, serving single request
1335 exit;
1338 ## ======================================================================
1339 ## action links
1341 # possible values of extra options
1342 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1343 # -replay => 1 - start from a current view (replay with modifications)
1344 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1345 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1346 sub href {
1347 my %params = @_;
1348 # default is to use -absolute url() i.e. $my_uri
1349 my $href = $params{-full} ? $my_url : $my_uri;
1351 # implicit -replay, must be first of implicit params
1352 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1354 $params{'project'} = $project unless exists $params{'project'};
1356 if ($params{-replay}) {
1357 while (my ($name, $symbol) = each %cgi_param_mapping) {
1358 if (!exists $params{$name}) {
1359 $params{$name} = $input_params{$name};
1364 my $use_pathinfo = gitweb_check_feature('pathinfo');
1365 if (defined $params{'project'} &&
1366 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1367 # try to put as many parameters as possible in PATH_INFO:
1368 # - project name
1369 # - action
1370 # - hash_parent or hash_parent_base:/file_parent
1371 # - hash or hash_base:/filename
1372 # - the snapshot_format as an appropriate suffix
1374 # When the script is the root DirectoryIndex for the domain,
1375 # $href here would be something like http://gitweb.example.com/
1376 # Thus, we strip any trailing / from $href, to spare us double
1377 # slashes in the final URL
1378 $href =~ s,/$,,;
1380 # Then add the project name, if present
1381 $href .= "/".esc_path_info($params{'project'});
1382 delete $params{'project'};
1384 # since we destructively absorb parameters, we keep this
1385 # boolean that remembers if we're handling a snapshot
1386 my $is_snapshot = $params{'action'} eq 'snapshot';
1388 # Summary just uses the project path URL, any other action is
1389 # added to the URL
1390 if (defined $params{'action'}) {
1391 $href .= "/".esc_path_info($params{'action'})
1392 unless $params{'action'} eq 'summary';
1393 delete $params{'action'};
1396 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1397 # stripping nonexistent or useless pieces
1398 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1399 || $params{'hash_parent'} || $params{'hash'});
1400 if (defined $params{'hash_base'}) {
1401 if (defined $params{'hash_parent_base'}) {
1402 $href .= esc_path_info($params{'hash_parent_base'});
1403 # skip the file_parent if it's the same as the file_name
1404 if (defined $params{'file_parent'}) {
1405 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1406 delete $params{'file_parent'};
1407 } elsif ($params{'file_parent'} !~ /\.\./) {
1408 $href .= ":/".esc_path_info($params{'file_parent'});
1409 delete $params{'file_parent'};
1412 $href .= "..";
1413 delete $params{'hash_parent'};
1414 delete $params{'hash_parent_base'};
1415 } elsif (defined $params{'hash_parent'}) {
1416 $href .= esc_path_info($params{'hash_parent'}). "..";
1417 delete $params{'hash_parent'};
1420 $href .= esc_path_info($params{'hash_base'});
1421 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1422 $href .= ":/".esc_path_info($params{'file_name'});
1423 delete $params{'file_name'};
1425 delete $params{'hash'};
1426 delete $params{'hash_base'};
1427 } elsif (defined $params{'hash'}) {
1428 $href .= esc_path_info($params{'hash'});
1429 delete $params{'hash'};
1432 # If the action was a snapshot, we can absorb the
1433 # snapshot_format parameter too
1434 if ($is_snapshot) {
1435 my $fmt = $params{'snapshot_format'};
1436 # snapshot_format should always be defined when href()
1437 # is called, but just in case some code forgets, we
1438 # fall back to the default
1439 $fmt ||= $snapshot_fmts[0];
1440 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1441 delete $params{'snapshot_format'};
1445 # now encode the parameters explicitly
1446 my @result = ();
1447 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1448 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1449 if (defined $params{$name}) {
1450 if (ref($params{$name}) eq "ARRAY") {
1451 foreach my $par (@{$params{$name}}) {
1452 push @result, $symbol . "=" . esc_param($par);
1454 } else {
1455 push @result, $symbol . "=" . esc_param($params{$name});
1459 $href .= "?" . join(';', @result) if scalar @result;
1461 # final transformation: trailing spaces must be escaped (URI-encoded)
1462 $href =~ s/(\s+)$/CGI::escape($1)/e;
1464 if ($params{-anchor}) {
1465 $href .= "#".esc_param($params{-anchor});
1468 return $href;
1472 ## ======================================================================
1473 ## validation, quoting/unquoting and escaping
1475 sub is_valid_action {
1476 my $input = shift;
1477 return undef unless exists $actions{$input};
1478 return 1;
1481 sub is_valid_project {
1482 my $input = shift;
1484 return unless defined $input;
1485 if (!is_valid_pathname($input) ||
1486 !(-d "$projectroot/$input") ||
1487 !check_export_ok("$projectroot/$input") ||
1488 ($strict_export && !project_in_list($input))) {
1489 return undef;
1490 } else {
1491 return 1;
1495 sub is_valid_pathname {
1496 my $input = shift;
1498 return undef unless defined $input;
1499 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1500 # at the beginning, at the end, and between slashes.
1501 # also this catches doubled slashes
1502 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1503 return undef;
1505 # no null characters
1506 if ($input =~ m!\0!) {
1507 return undef;
1509 return 1;
1512 sub is_valid_ref_format {
1513 my $input = shift;
1515 return undef unless defined $input;
1516 # restrictions on ref name according to git-check-ref-format
1517 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1518 return undef;
1520 return 1;
1523 sub is_valid_refname {
1524 my $input = shift;
1526 return undef unless defined $input;
1527 # textual hashes are O.K.
1528 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1529 return 1;
1531 # it must be correct pathname
1532 is_valid_pathname($input) or return undef;
1533 # check git-check-ref-format restrictions
1534 is_valid_ref_format($input) or return undef;
1535 return 1;
1538 # decode sequences of octets in utf8 into Perl's internal form,
1539 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1540 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1541 sub to_utf8 {
1542 my $str = shift;
1543 return undef unless defined $str;
1545 if (utf8::is_utf8($str) || utf8::decode($str)) {
1546 return $str;
1547 } else {
1548 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1552 # quote unsafe chars, but keep the slash, even when it's not
1553 # correct, but quoted slashes look too horrible in bookmarks
1554 sub esc_param {
1555 my $str = shift;
1556 return undef unless defined $str;
1557 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1558 $str =~ s/ /\+/g;
1559 return $str;
1562 # the quoting rules for path_info fragment are slightly different
1563 sub esc_path_info {
1564 my $str = shift;
1565 return undef unless defined $str;
1567 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1568 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1570 return $str;
1573 # quote unsafe chars in whole URL, so some characters cannot be quoted
1574 sub esc_url {
1575 my $str = shift;
1576 return undef unless defined $str;
1577 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1578 $str =~ s/ /\+/g;
1579 return $str;
1582 # quote unsafe characters in HTML attributes
1583 sub esc_attr {
1585 # for XHTML conformance escaping '"' to '&quot;' is not enough
1586 return esc_html(@_);
1589 # replace invalid utf8 character with SUBSTITUTION sequence
1590 sub esc_html {
1591 my $str = shift;
1592 my %opts = @_;
1594 return undef unless defined $str;
1596 $str = to_utf8($str);
1597 $str = $cgi->escapeHTML($str);
1598 if ($opts{'-nbsp'}) {
1599 $str =~ s/ /&nbsp;/g;
1601 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1602 return $str;
1605 # quote control characters and escape filename to HTML
1606 sub esc_path {
1607 my $str = shift;
1608 my %opts = @_;
1610 return undef unless defined $str;
1612 $str = to_utf8($str);
1613 $str = $cgi->escapeHTML($str);
1614 if ($opts{'-nbsp'}) {
1615 $str =~ s/ /&nbsp;/g;
1617 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1618 return $str;
1621 # Sanitize for use in XHTML + application/xml+xhtml (valid XML 1.0)
1622 sub sanitize {
1623 my $str = shift;
1625 return undef unless defined $str;
1627 $str = to_utf8($str);
1628 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1629 return $str;
1632 # Make control characters "printable", using character escape codes (CEC)
1633 sub quot_cec {
1634 my $cntrl = shift;
1635 my %opts = @_;
1636 my %es = ( # character escape codes, aka escape sequences
1637 "\t" => '\t', # tab (HT)
1638 "\n" => '\n', # line feed (LF)
1639 "\r" => '\r', # carrige return (CR)
1640 "\f" => '\f', # form feed (FF)
1641 "\b" => '\b', # backspace (BS)
1642 "\a" => '\a', # alarm (bell) (BEL)
1643 "\e" => '\e', # escape (ESC)
1644 "\013" => '\v', # vertical tab (VT)
1645 "\000" => '\0', # nul character (NUL)
1647 my $chr = ( (exists $es{$cntrl})
1648 ? $es{$cntrl}
1649 : sprintf('\%2x', ord($cntrl)) );
1650 if ($opts{-nohtml}) {
1651 return $chr;
1652 } else {
1653 return "<span class=\"cntrl\">$chr</span>";
1657 # Alternatively use unicode control pictures codepoints,
1658 # Unicode "printable representation" (PR)
1659 sub quot_upr {
1660 my $cntrl = shift;
1661 my %opts = @_;
1663 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1664 if ($opts{-nohtml}) {
1665 return $chr;
1666 } else {
1667 return "<span class=\"cntrl\">$chr</span>";
1671 # git may return quoted and escaped filenames
1672 sub unquote {
1673 my $str = shift;
1675 sub unq {
1676 my $seq = shift;
1677 my %es = ( # character escape codes, aka escape sequences
1678 't' => "\t", # tab (HT, TAB)
1679 'n' => "\n", # newline (NL)
1680 'r' => "\r", # return (CR)
1681 'f' => "\f", # form feed (FF)
1682 'b' => "\b", # backspace (BS)
1683 'a' => "\a", # alarm (bell) (BEL)
1684 'e' => "\e", # escape (ESC)
1685 'v' => "\013", # vertical tab (VT)
1688 if ($seq =~ m/^[0-7]{1,3}$/) {
1689 # octal char sequence
1690 return chr(oct($seq));
1691 } elsif (exists $es{$seq}) {
1692 # C escape sequence, aka character escape code
1693 return $es{$seq};
1695 # quoted ordinary character
1696 return $seq;
1699 if ($str =~ m/^"(.*)"$/) {
1700 # needs unquoting
1701 $str = $1;
1702 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1704 return $str;
1707 # escape tabs (convert tabs to spaces)
1708 sub untabify {
1709 my $line = shift;
1711 while ((my $pos = index($line, "\t")) != -1) {
1712 if (my $count = (8 - ($pos % 8))) {
1713 my $spaces = ' ' x $count;
1714 $line =~ s/\t/$spaces/;
1718 return $line;
1721 sub project_in_list {
1722 my $project = shift;
1723 my @list = git_get_projects_list();
1724 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1727 ## ----------------------------------------------------------------------
1728 ## HTML aware string manipulation
1730 # Try to chop given string on a word boundary between position
1731 # $len and $len+$add_len. If there is no word boundary there,
1732 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1733 # (marking chopped part) would be longer than given string.
1734 sub chop_str {
1735 my $str = shift;
1736 my $len = shift;
1737 my $add_len = shift || 10;
1738 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1740 # Make sure perl knows it is utf8 encoded so we don't
1741 # cut in the middle of a utf8 multibyte char.
1742 $str = to_utf8($str);
1744 # allow only $len chars, but don't cut a word if it would fit in $add_len
1745 # if it doesn't fit, cut it if it's still longer than the dots we would add
1746 # remove chopped character entities entirely
1748 # when chopping in the middle, distribute $len into left and right part
1749 # return early if chopping wouldn't make string shorter
1750 if ($where eq 'center') {
1751 return $str if ($len + 5 >= length($str)); # filler is length 5
1752 $len = int($len/2);
1753 } else {
1754 return $str if ($len + 4 >= length($str)); # filler is length 4
1757 # regexps: ending and beginning with word part up to $add_len
1758 my $endre = qr/.{$len}\w{0,$add_len}/;
1759 my $begre = qr/\w{0,$add_len}.{$len}/;
1761 if ($where eq 'left') {
1762 $str =~ m/^(.*?)($begre)$/;
1763 my ($lead, $body) = ($1, $2);
1764 if (length($lead) > 4) {
1765 $lead = " ...";
1767 return "$lead$body";
1769 } elsif ($where eq 'center') {
1770 $str =~ m/^($endre)(.*)$/;
1771 my ($left, $str) = ($1, $2);
1772 $str =~ m/^(.*?)($begre)$/;
1773 my ($mid, $right) = ($1, $2);
1774 if (length($mid) > 5) {
1775 $mid = " ... ";
1777 return "$left$mid$right";
1779 } else {
1780 $str =~ m/^($endre)(.*)$/;
1781 my $body = $1;
1782 my $tail = $2;
1783 if (length($tail) > 4) {
1784 $tail = "... ";
1786 return "$body$tail";
1790 # takes the same arguments as chop_str, but also wraps a <span> around the
1791 # result with a title attribute if it does get chopped. Additionally, the
1792 # string is HTML-escaped.
1793 sub chop_and_escape_str {
1794 my ($str) = @_;
1796 my $chopped = chop_str(@_);
1797 $str = to_utf8($str);
1798 if ($chopped eq $str) {
1799 return esc_html($chopped);
1800 } else {
1801 $str =~ s/[[:cntrl:]]/?/g;
1802 return $cgi->span({-title=>$str}, esc_html($chopped));
1806 # Highlight selected fragments of string, using given CSS class,
1807 # and escape HTML. It is assumed that fragments do not overlap.
1808 # Regions are passed as list of pairs (array references).
1810 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1811 # '<span class="mark">foo</span>bar'
1812 sub esc_html_hl_regions {
1813 my ($str, $css_class, @sel) = @_;
1814 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1815 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1816 return esc_html($str, %opts) unless @sel;
1818 my $out = '';
1819 my $pos = 0;
1821 for my $s (@sel) {
1822 my ($begin, $end) = @$s;
1824 # Don't create empty <span> elements.
1825 next if $end <= $begin;
1827 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1828 %opts);
1830 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1831 if ($begin - $pos > 0);
1832 $out .= $cgi->span({-class => $css_class}, $escaped);
1834 $pos = $end;
1836 $out .= esc_html(substr($str, $pos), %opts)
1837 if ($pos < length($str));
1839 return $out;
1842 # return positions of beginning and end of each match
1843 sub matchpos_list {
1844 my ($str, $regexp) = @_;
1845 return unless (defined $str && defined $regexp);
1847 my @matches;
1848 while ($str =~ /$regexp/g) {
1849 push @matches, [$-[0], $+[0]];
1851 return @matches;
1854 # highlight match (if any), and escape HTML
1855 sub esc_html_match_hl {
1856 my ($str, $regexp) = @_;
1857 return esc_html($str) unless defined $regexp;
1859 my @matches = matchpos_list($str, $regexp);
1860 return esc_html($str) unless @matches;
1862 return esc_html_hl_regions($str, 'match', @matches);
1866 # highlight match (if any) of shortened string, and escape HTML
1867 sub esc_html_match_hl_chopped {
1868 my ($str, $chopped, $regexp) = @_;
1869 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1871 my @matches = matchpos_list($str, $regexp);
1872 return esc_html($chopped) unless @matches;
1874 # filter matches so that we mark chopped string
1875 my $tail = "... "; # see chop_str
1876 unless ($chopped =~ s/\Q$tail\E$//) {
1877 $tail = '';
1879 my $chop_len = length($chopped);
1880 my $tail_len = length($tail);
1881 my @filtered;
1883 for my $m (@matches) {
1884 if ($m->[0] > $chop_len) {
1885 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1886 last;
1887 } elsif ($m->[1] > $chop_len) {
1888 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1889 last;
1891 push @filtered, $m;
1894 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1897 ## ----------------------------------------------------------------------
1898 ## functions returning short strings
1900 # CSS class for given age value (in seconds)
1901 sub age_class {
1902 my $age = shift;
1904 if (!defined $age) {
1905 return "noage";
1906 } elsif ($age < 60*60*2) {
1907 return "age0";
1908 } elsif ($age < 60*60*24*2) {
1909 return "age1";
1910 } else {
1911 return "age2";
1915 # convert age in seconds to "nn units ago" string
1916 sub age_string {
1917 my $age = shift;
1918 my $age_str;
1920 if ($age > 60*60*24*365*2) {
1921 $age_str = (int $age/60/60/24/365);
1922 $age_str .= " years ago";
1923 } elsif ($age > 60*60*24*(365/12)*2) {
1924 $age_str = int $age/60/60/24/(365/12);
1925 $age_str .= " months ago";
1926 } elsif ($age > 60*60*24*7*2) {
1927 $age_str = int $age/60/60/24/7;
1928 $age_str .= " weeks ago";
1929 } elsif ($age > 60*60*24*2) {
1930 $age_str = int $age/60/60/24;
1931 $age_str .= " days ago";
1932 } elsif ($age > 60*60*2) {
1933 $age_str = int $age/60/60;
1934 $age_str .= " hours ago";
1935 } elsif ($age > 60*2) {
1936 $age_str = int $age/60;
1937 $age_str .= " min ago";
1938 } elsif ($age > 2) {
1939 $age_str = int $age;
1940 $age_str .= " sec ago";
1941 } else {
1942 $age_str .= " right now";
1944 return $age_str;
1947 use constant {
1948 S_IFINVALID => 0030000,
1949 S_IFGITLINK => 0160000,
1952 # submodule/subproject, a commit object reference
1953 sub S_ISGITLINK {
1954 my $mode = shift;
1956 return (($mode & S_IFMT) == S_IFGITLINK)
1959 # convert file mode in octal to symbolic file mode string
1960 sub mode_str {
1961 my $mode = oct shift;
1963 if (S_ISGITLINK($mode)) {
1964 return 'm---------';
1965 } elsif (S_ISDIR($mode & S_IFMT)) {
1966 return 'drwxr-xr-x';
1967 } elsif (S_ISLNK($mode)) {
1968 return 'lrwxrwxrwx';
1969 } elsif (S_ISREG($mode)) {
1970 # git cares only about the executable bit
1971 if ($mode & S_IXUSR) {
1972 return '-rwxr-xr-x';
1973 } else {
1974 return '-rw-r--r--';
1976 } else {
1977 return '----------';
1981 # convert file mode in octal to file type string
1982 sub file_type {
1983 my $mode = shift;
1985 if ($mode !~ m/^[0-7]+$/) {
1986 return $mode;
1987 } else {
1988 $mode = oct $mode;
1991 if (S_ISGITLINK($mode)) {
1992 return "submodule";
1993 } elsif (S_ISDIR($mode & S_IFMT)) {
1994 return "directory";
1995 } elsif (S_ISLNK($mode)) {
1996 return "symlink";
1997 } elsif (S_ISREG($mode)) {
1998 return "file";
1999 } else {
2000 return "unknown";
2004 # convert file mode in octal to file type description string
2005 sub file_type_long {
2006 my $mode = shift;
2008 if ($mode !~ m/^[0-7]+$/) {
2009 return $mode;
2010 } else {
2011 $mode = oct $mode;
2014 if (S_ISGITLINK($mode)) {
2015 return "submodule";
2016 } elsif (S_ISDIR($mode & S_IFMT)) {
2017 return "directory";
2018 } elsif (S_ISLNK($mode)) {
2019 return "symlink";
2020 } elsif (S_ISREG($mode)) {
2021 if ($mode & S_IXUSR) {
2022 return "executable";
2023 } else {
2024 return "file";
2026 } else {
2027 return "unknown";
2032 ## ----------------------------------------------------------------------
2033 ## functions returning short HTML fragments, or transforming HTML fragments
2034 ## which don't belong to other sections
2036 # format line of commit message.
2037 sub format_log_line_html {
2038 my $line = shift;
2040 $line = esc_html($line, -nbsp=>1);
2041 $line =~ s{
2044 # The output of "git describe", e.g. v2.10.0-297-gf6727b0
2045 # or hadoop-20160921-113441-20-g094fb7d
2046 (?<!-) # see strbuf_check_tag_ref(). Tags can't start with -
2047 [A-Za-z0-9.-]+
2048 (?!\.) # refs can't end with ".", see check_refname_format()
2049 -g[0-9a-fA-F]{7,40}
2051 # Just a normal looking Git SHA1
2052 [0-9a-fA-F]{7,40}
2056 $cgi->a({-href => href(action=>"object", hash=>$1),
2057 -class => "text"}, $1);
2058 }egx;
2060 return $line;
2063 # format marker of refs pointing to given object
2065 # the destination action is chosen based on object type and current context:
2066 # - for annotated tags, we choose the tag view unless it's the current view
2067 # already, in which case we go to shortlog view
2068 # - for other refs, we keep the current view if we're in history, shortlog or
2069 # log view, and select shortlog otherwise
2070 sub format_ref_marker {
2071 my ($refs, $id) = @_;
2072 my $markers = '';
2074 if (defined $refs->{$id}) {
2075 foreach my $ref (@{$refs->{$id}}) {
2076 # this code exploits the fact that non-lightweight tags are the
2077 # only indirect objects, and that they are the only objects for which
2078 # we want to use tag instead of shortlog as action
2079 my ($type, $name) = qw();
2080 my $indirect = ($ref =~ s/\^\{\}$//);
2081 # e.g. tags/v2.6.11 or heads/next
2082 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2083 $type = $1;
2084 $name = $2;
2085 } else {
2086 $type = "ref";
2087 $name = $ref;
2090 my $class = $type;
2091 $class .= " indirect" if $indirect;
2093 my $dest_action = "shortlog";
2095 if ($indirect) {
2096 $dest_action = "tag" unless $action eq "tag";
2097 } elsif ($action =~ /^(history|(short)?log)$/) {
2098 $dest_action = $action;
2101 my $dest = "";
2102 $dest .= "refs/" unless $ref =~ m!^refs/!;
2103 $dest .= $ref;
2105 my $link = $cgi->a({
2106 -href => href(
2107 action=>$dest_action,
2108 hash=>$dest
2109 )}, esc_html($name));
2111 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2112 $link . "</span>";
2116 if ($markers) {
2117 return ' <span class="refs">'. $markers . '</span>';
2118 } else {
2119 return "";
2123 # format, perhaps shortened and with markers, title line
2124 sub format_subject_html {
2125 my ($long, $short, $href, $extra) = @_;
2126 $extra = '' unless defined($extra);
2128 if (length($short) < length($long)) {
2129 $long =~ s/[[:cntrl:]]/?/g;
2130 return $cgi->a({-href => $href, -class => "list subject",
2131 -title => to_utf8($long)},
2132 esc_html($short)) . $extra;
2133 } else {
2134 return $cgi->a({-href => $href, -class => "list subject"},
2135 esc_html($long)) . $extra;
2139 # Rather than recomputing the url for an email multiple times, we cache it
2140 # after the first hit. This gives a visible benefit in views where the avatar
2141 # for the same email is used repeatedly (e.g. shortlog).
2142 # The cache is shared by all avatar engines (currently gravatar only), which
2143 # are free to use it as preferred. Since only one avatar engine is used for any
2144 # given page, there's no risk for cache conflicts.
2145 our %avatar_cache = ();
2147 # Compute the picon url for a given email, by using the picon search service over at
2148 # http://www.cs.indiana.edu/picons/search.html
2149 sub picon_url {
2150 my $email = lc shift;
2151 if (!$avatar_cache{$email}) {
2152 my ($user, $domain) = split('@', $email);
2153 $avatar_cache{$email} =
2154 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2155 "$domain/$user/" .
2156 "users+domains+unknown/up/single";
2158 return $avatar_cache{$email};
2161 # Compute the gravatar url for a given email, if it's not in the cache already.
2162 # Gravatar stores only the part of the URL before the size, since that's the
2163 # one computationally more expensive. This also allows reuse of the cache for
2164 # different sizes (for this particular engine).
2165 sub gravatar_url {
2166 my $email = lc shift;
2167 my $size = shift;
2168 $avatar_cache{$email} ||=
2169 "//www.gravatar.com/avatar/" .
2170 Digest::MD5::md5_hex($email) . "?s=";
2171 return $avatar_cache{$email} . $size;
2174 # Insert an avatar for the given $email at the given $size if the feature
2175 # is enabled.
2176 sub git_get_avatar {
2177 my ($email, %opts) = @_;
2178 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2179 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2180 $opts{-size} ||= 'default';
2181 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2182 my $url = "";
2183 if ($git_avatar eq 'gravatar') {
2184 $url = gravatar_url($email, $size);
2185 } elsif ($git_avatar eq 'picon') {
2186 $url = picon_url($email);
2188 # Other providers can be added by extending the if chain, defining $url
2189 # as needed. If no variant puts something in $url, we assume avatars
2190 # are completely disabled/unavailable.
2191 if ($url) {
2192 return $pre_white .
2193 "<img width=\"$size\" " .
2194 "class=\"avatar\" " .
2195 "src=\"".esc_url($url)."\" " .
2196 "alt=\"\" " .
2197 "/>" . $post_white;
2198 } else {
2199 return "";
2203 sub format_search_author {
2204 my ($author, $searchtype, $displaytext) = @_;
2205 my $have_search = gitweb_check_feature('search');
2207 if ($have_search) {
2208 my $performed = "";
2209 if ($searchtype eq 'author') {
2210 $performed = "authored";
2211 } elsif ($searchtype eq 'committer') {
2212 $performed = "committed";
2215 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2216 searchtext=>$author,
2217 searchtype=>$searchtype), class=>"list",
2218 title=>"Search for commits $performed by $author"},
2219 $displaytext);
2221 } else {
2222 return $displaytext;
2226 # format the author name of the given commit with the given tag
2227 # the author name is chopped and escaped according to the other
2228 # optional parameters (see chop_str).
2229 sub format_author_html {
2230 my $tag = shift;
2231 my $co = shift;
2232 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2233 return "<$tag class=\"author\">" .
2234 format_search_author($co->{'author_name'}, "author",
2235 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2236 $author) .
2237 "</$tag>";
2240 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2241 sub format_git_diff_header_line {
2242 my $line = shift;
2243 my $diffinfo = shift;
2244 my ($from, $to) = @_;
2246 if ($diffinfo->{'nparents'}) {
2247 # combined diff
2248 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2249 if ($to->{'href'}) {
2250 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2251 esc_path($to->{'file'}));
2252 } else { # file was deleted (no href)
2253 $line .= esc_path($to->{'file'});
2255 } else {
2256 # "ordinary" diff
2257 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2258 if ($from->{'href'}) {
2259 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2260 'a/' . esc_path($from->{'file'}));
2261 } else { # file was added (no href)
2262 $line .= 'a/' . esc_path($from->{'file'});
2264 $line .= ' ';
2265 if ($to->{'href'}) {
2266 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2267 'b/' . esc_path($to->{'file'}));
2268 } else { # file was deleted
2269 $line .= 'b/' . esc_path($to->{'file'});
2273 return "<div class=\"diff header\">$line</div>\n";
2276 # format extended diff header line, before patch itself
2277 sub format_extended_diff_header_line {
2278 my $line = shift;
2279 my $diffinfo = shift;
2280 my ($from, $to) = @_;
2282 # match <path>
2283 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2284 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2285 esc_path($from->{'file'}));
2287 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2288 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2289 esc_path($to->{'file'}));
2291 # match single <mode>
2292 if ($line =~ m/\s(\d{6})$/) {
2293 $line .= '<span class="info"> (' .
2294 file_type_long($1) .
2295 ')</span>';
2297 # match <hash>
2298 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2299 # can match only for combined diff
2300 $line = 'index ';
2301 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2302 if ($from->{'href'}[$i]) {
2303 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2304 -class=>"hash"},
2305 substr($diffinfo->{'from_id'}[$i],0,7));
2306 } else {
2307 $line .= '0' x 7;
2309 # separator
2310 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2312 $line .= '..';
2313 if ($to->{'href'}) {
2314 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2315 substr($diffinfo->{'to_id'},0,7));
2316 } else {
2317 $line .= '0' x 7;
2320 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2321 # can match only for ordinary diff
2322 my ($from_link, $to_link);
2323 if ($from->{'href'}) {
2324 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2325 substr($diffinfo->{'from_id'},0,7));
2326 } else {
2327 $from_link = '0' x 7;
2329 if ($to->{'href'}) {
2330 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2331 substr($diffinfo->{'to_id'},0,7));
2332 } else {
2333 $to_link = '0' x 7;
2335 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2336 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2339 return $line . "<br/>\n";
2342 # format from-file/to-file diff header
2343 sub format_diff_from_to_header {
2344 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2345 my $line;
2346 my $result = '';
2348 $line = $from_line;
2349 #assert($line =~ m/^---/) if DEBUG;
2350 # no extra formatting for "^--- /dev/null"
2351 if (! $diffinfo->{'nparents'}) {
2352 # ordinary (single parent) diff
2353 if ($line =~ m!^--- "?a/!) {
2354 if ($from->{'href'}) {
2355 $line = '--- a/' .
2356 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2357 esc_path($from->{'file'}));
2358 } else {
2359 $line = '--- a/' .
2360 esc_path($from->{'file'});
2363 $result .= qq!<div class="diff from_file">$line</div>\n!;
2365 } else {
2366 # combined diff (merge commit)
2367 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2368 if ($from->{'href'}[$i]) {
2369 $line = '--- ' .
2370 $cgi->a({-href=>href(action=>"blobdiff",
2371 hash_parent=>$diffinfo->{'from_id'}[$i],
2372 hash_parent_base=>$parents[$i],
2373 file_parent=>$from->{'file'}[$i],
2374 hash=>$diffinfo->{'to_id'},
2375 hash_base=>$hash,
2376 file_name=>$to->{'file'}),
2377 -class=>"path",
2378 -title=>"diff" . ($i+1)},
2379 $i+1) .
2380 '/' .
2381 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2382 esc_path($from->{'file'}[$i]));
2383 } else {
2384 $line = '--- /dev/null';
2386 $result .= qq!<div class="diff from_file">$line</div>\n!;
2390 $line = $to_line;
2391 #assert($line =~ m/^\+\+\+/) if DEBUG;
2392 # no extra formatting for "^+++ /dev/null"
2393 if ($line =~ m!^\+\+\+ "?b/!) {
2394 if ($to->{'href'}) {
2395 $line = '+++ b/' .
2396 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2397 esc_path($to->{'file'}));
2398 } else {
2399 $line = '+++ b/' .
2400 esc_path($to->{'file'});
2403 $result .= qq!<div class="diff to_file">$line</div>\n!;
2405 return $result;
2408 # create note for patch simplified by combined diff
2409 sub format_diff_cc_simplified {
2410 my ($diffinfo, @parents) = @_;
2411 my $result = '';
2413 $result .= "<div class=\"diff header\">" .
2414 "diff --cc ";
2415 if (!is_deleted($diffinfo)) {
2416 $result .= $cgi->a({-href => href(action=>"blob",
2417 hash_base=>$hash,
2418 hash=>$diffinfo->{'to_id'},
2419 file_name=>$diffinfo->{'to_file'}),
2420 -class => "path"},
2421 esc_path($diffinfo->{'to_file'}));
2422 } else {
2423 $result .= esc_path($diffinfo->{'to_file'});
2425 $result .= "</div>\n" . # class="diff header"
2426 "<div class=\"diff nodifferences\">" .
2427 "Simple merge" .
2428 "</div>\n"; # class="diff nodifferences"
2430 return $result;
2433 sub diff_line_class {
2434 my ($line, $from, $to) = @_;
2436 # ordinary diff
2437 my $num_sign = 1;
2438 # combined diff
2439 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2440 $num_sign = scalar @{$from->{'href'}};
2443 my @diff_line_classifier = (
2444 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2445 { regexp => qr/^\\/, class => "incomplete" },
2446 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2447 # classifier for context must come before classifier add/rem,
2448 # or we would have to use more complicated regexp, for example
2449 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2450 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2451 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2453 for my $clsfy (@diff_line_classifier) {
2454 return $clsfy->{'class'}
2455 if ($line =~ $clsfy->{'regexp'});
2458 # fallback
2459 return "";
2462 # assumes that $from and $to are defined and correctly filled,
2463 # and that $line holds a line of chunk header for unified diff
2464 sub format_unidiff_chunk_header {
2465 my ($line, $from, $to) = @_;
2467 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2468 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2470 $from_lines = 0 unless defined $from_lines;
2471 $to_lines = 0 unless defined $to_lines;
2473 if ($from->{'href'}) {
2474 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2475 -class=>"list"}, $from_text);
2477 if ($to->{'href'}) {
2478 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2479 -class=>"list"}, $to_text);
2481 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2482 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2483 return $line;
2486 # assumes that $from and $to are defined and correctly filled,
2487 # and that $line holds a line of chunk header for combined diff
2488 sub format_cc_diff_chunk_header {
2489 my ($line, $from, $to) = @_;
2491 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2492 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2494 @from_text = split(' ', $ranges);
2495 for (my $i = 0; $i < @from_text; ++$i) {
2496 ($from_start[$i], $from_nlines[$i]) =
2497 (split(',', substr($from_text[$i], 1)), 0);
2500 $to_text = pop @from_text;
2501 $to_start = pop @from_start;
2502 $to_nlines = pop @from_nlines;
2504 $line = "<span class=\"chunk_info\">$prefix ";
2505 for (my $i = 0; $i < @from_text; ++$i) {
2506 if ($from->{'href'}[$i]) {
2507 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2508 -class=>"list"}, $from_text[$i]);
2509 } else {
2510 $line .= $from_text[$i];
2512 $line .= " ";
2514 if ($to->{'href'}) {
2515 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2516 -class=>"list"}, $to_text);
2517 } else {
2518 $line .= $to_text;
2520 $line .= " $prefix</span>" .
2521 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2522 return $line;
2525 # process patch (diff) line (not to be used for diff headers),
2526 # returning HTML-formatted (but not wrapped) line.
2527 # If the line is passed as a reference, it is treated as HTML and not
2528 # esc_html()'ed.
2529 sub format_diff_line {
2530 my ($line, $diff_class, $from, $to) = @_;
2532 if (ref($line)) {
2533 $line = $$line;
2534 } else {
2535 chomp $line;
2536 $line = untabify($line);
2538 if ($from && $to && $line =~ m/^\@{2} /) {
2539 $line = format_unidiff_chunk_header($line, $from, $to);
2540 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2541 $line = format_cc_diff_chunk_header($line, $from, $to);
2542 } else {
2543 $line = esc_html($line, -nbsp=>1);
2547 my $diff_classes = "diff";
2548 $diff_classes .= " $diff_class" if ($diff_class);
2549 $line = "<div class=\"$diff_classes\">$line</div>\n";
2551 return $line;
2554 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2555 # linked. Pass the hash of the tree/commit to snapshot.
2556 sub format_snapshot_links {
2557 my ($hash) = @_;
2558 my $num_fmts = @snapshot_fmts;
2559 if ($num_fmts > 1) {
2560 # A parenthesized list of links bearing format names.
2561 # e.g. "snapshot (_tar.gz_ _zip_)"
2562 return "snapshot (" . join(' ', map
2563 $cgi->a({
2564 -href => href(
2565 action=>"snapshot",
2566 hash=>$hash,
2567 snapshot_format=>$_
2569 }, $known_snapshot_formats{$_}{'display'})
2570 , @snapshot_fmts) . ")";
2571 } elsif ($num_fmts == 1) {
2572 # A single "snapshot" link whose tooltip bears the format name.
2573 # i.e. "_snapshot_"
2574 my ($fmt) = @snapshot_fmts;
2575 return
2576 $cgi->a({
2577 -href => href(
2578 action=>"snapshot",
2579 hash=>$hash,
2580 snapshot_format=>$fmt
2582 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2583 }, "snapshot");
2584 } else { # $num_fmts == 0
2585 return undef;
2589 ## ......................................................................
2590 ## functions returning values to be passed, perhaps after some
2591 ## transformation, to other functions; e.g. returning arguments to href()
2593 # returns hash to be passed to href to generate gitweb URL
2594 # in -title key it returns description of link
2595 sub get_feed_info {
2596 my $format = shift || 'Atom';
2597 my %res = (action => lc($format));
2598 my $matched_ref = 0;
2600 # feed links are possible only for project views
2601 return unless (defined $project);
2602 # some views should link to OPML, or to generic project feed,
2603 # or don't have specific feed yet (so they should use generic)
2604 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2606 my $branch = undef;
2607 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2608 # (fullname) to differentiate from tag links; this also makes
2609 # possible to detect branch links
2610 for my $ref (get_branch_refs()) {
2611 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2612 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2613 $branch = $1;
2614 $matched_ref = $ref;
2615 last;
2618 # find log type for feed description (title)
2619 my $type = 'log';
2620 if (defined $file_name) {
2621 $type = "history of $file_name";
2622 $type .= "/" if ($action eq 'tree');
2623 $type .= " on '$branch'" if (defined $branch);
2624 } else {
2625 $type = "log of $branch" if (defined $branch);
2628 $res{-title} = $type;
2629 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2630 $res{'file_name'} = $file_name;
2632 return %res;
2635 ## ----------------------------------------------------------------------
2636 ## git utility subroutines, invoking git commands
2638 # returns path to the core git executable and the --git-dir parameter as list
2639 sub git_cmd {
2640 $number_of_git_cmds++;
2641 return $GIT, '--git-dir='.$git_dir;
2644 # quote the given arguments for passing them to the shell
2645 # quote_command("command", "arg 1", "arg with ' and ! characters")
2646 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2647 # Try to avoid using this function wherever possible.
2648 sub quote_command {
2649 return join(' ',
2650 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2653 # get HEAD ref of given project as hash
2654 sub git_get_head_hash {
2655 return git_get_full_hash(shift, 'HEAD');
2658 sub git_get_full_hash {
2659 return git_get_hash(@_);
2662 sub git_get_short_hash {
2663 return git_get_hash(@_, '--short=7');
2666 sub git_get_hash {
2667 my ($project, $hash, @options) = @_;
2668 my $o_git_dir = $git_dir;
2669 my $retval = undef;
2670 $git_dir = "$projectroot/$project";
2671 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2672 '--verify', '-q', @options, $hash) {
2673 $retval = <$fd>;
2674 chomp $retval if defined $retval;
2675 close $fd;
2677 if (defined $o_git_dir) {
2678 $git_dir = $o_git_dir;
2680 return $retval;
2683 # get type of given object
2684 sub git_get_type {
2685 my $hash = shift;
2687 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2688 my $type = <$fd>;
2689 close $fd or return;
2690 chomp $type;
2691 return $type;
2694 # repository configuration
2695 our $config_file = '';
2696 our %config;
2698 # store multiple values for single key as anonymous array reference
2699 # single values stored directly in the hash, not as [ <value> ]
2700 sub hash_set_multi {
2701 my ($hash, $key, $value) = @_;
2703 if (!exists $hash->{$key}) {
2704 $hash->{$key} = $value;
2705 } elsif (!ref $hash->{$key}) {
2706 $hash->{$key} = [ $hash->{$key}, $value ];
2707 } else {
2708 push @{$hash->{$key}}, $value;
2712 # return hash of git project configuration
2713 # optionally limited to some section, e.g. 'gitweb'
2714 sub git_parse_project_config {
2715 my $section_regexp = shift;
2716 my %config;
2718 local $/ = "\0";
2720 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2721 or return;
2723 while (my $keyval = <$fh>) {
2724 chomp $keyval;
2725 my ($key, $value) = split(/\n/, $keyval, 2);
2727 hash_set_multi(\%config, $key, $value)
2728 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2730 close $fh;
2732 return %config;
2735 # convert config value to boolean: 'true' or 'false'
2736 # no value, number > 0, 'true' and 'yes' values are true
2737 # rest of values are treated as false (never as error)
2738 sub config_to_bool {
2739 my $val = shift;
2741 return 1 if !defined $val; # section.key
2743 # strip leading and trailing whitespace
2744 $val =~ s/^\s+//;
2745 $val =~ s/\s+$//;
2747 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2748 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2751 # convert config value to simple decimal number
2752 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2753 # to be multiplied by 1024, 1048576, or 1073741824
2754 sub config_to_int {
2755 my $val = shift;
2757 # strip leading and trailing whitespace
2758 $val =~ s/^\s+//;
2759 $val =~ s/\s+$//;
2761 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2762 $unit = lc($unit);
2763 # unknown unit is treated as 1
2764 return $num * ($unit eq 'g' ? 1073741824 :
2765 $unit eq 'm' ? 1048576 :
2766 $unit eq 'k' ? 1024 : 1);
2768 return $val;
2771 # convert config value to array reference, if needed
2772 sub config_to_multi {
2773 my $val = shift;
2775 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2778 sub git_get_project_config {
2779 my ($key, $type) = @_;
2781 return unless defined $git_dir;
2783 # key sanity check
2784 return unless ($key);
2785 # only subsection, if exists, is case sensitive,
2786 # and not lowercased by 'git config -z -l'
2787 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2788 $lo =~ s/_//g;
2789 $key = join(".", lc($hi), $mi, lc($lo));
2790 return if ($lo =~ /\W/ || $hi =~ /\W/);
2791 } else {
2792 $key = lc($key);
2793 $key =~ s/_//g;
2794 return if ($key =~ /\W/);
2796 $key =~ s/^gitweb\.//;
2798 # type sanity check
2799 if (defined $type) {
2800 $type =~ s/^--//;
2801 $type = undef
2802 unless ($type eq 'bool' || $type eq 'int');
2805 # get config
2806 if (!defined $config_file ||
2807 $config_file ne "$git_dir/config") {
2808 %config = git_parse_project_config('gitweb');
2809 $config_file = "$git_dir/config";
2812 # check if config variable (key) exists
2813 return unless exists $config{"gitweb.$key"};
2815 # ensure given type
2816 if (!defined $type) {
2817 return $config{"gitweb.$key"};
2818 } elsif ($type eq 'bool') {
2819 # backward compatibility: 'git config --bool' returns true/false
2820 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2821 } elsif ($type eq 'int') {
2822 return config_to_int($config{"gitweb.$key"});
2824 return $config{"gitweb.$key"};
2827 # get hash of given path at given ref
2828 sub git_get_hash_by_path {
2829 my $base = shift;
2830 my $path = shift || return undef;
2831 my $type = shift;
2833 $path =~ s,/+$,,;
2835 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2836 or die_error(500, "Open git-ls-tree failed");
2837 my $line = <$fd>;
2838 close $fd or return undef;
2840 if (!defined $line) {
2841 # there is no tree or hash given by $path at $base
2842 return undef;
2845 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2846 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2847 if (defined $type && $type ne $2) {
2848 # type doesn't match
2849 return undef;
2851 return $3;
2854 # get path of entry with given hash at given tree-ish (ref)
2855 # used to get 'from' filename for combined diff (merge commit) for renames
2856 sub git_get_path_by_hash {
2857 my $base = shift || return;
2858 my $hash = shift || return;
2860 local $/ = "\0";
2862 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2863 or return undef;
2864 while (my $line = <$fd>) {
2865 chomp $line;
2867 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2868 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2869 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2870 close $fd;
2871 return $1;
2874 close $fd;
2875 return undef;
2878 ## ......................................................................
2879 ## git utility functions, directly accessing git repository
2881 # get the value of config variable either from file named as the variable
2882 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2883 # configuration variable in the repository config file.
2884 sub git_get_file_or_project_config {
2885 my ($path, $name) = @_;
2887 $git_dir = "$projectroot/$path";
2888 open my $fd, '<', "$git_dir/$name"
2889 or return git_get_project_config($name);
2890 my $conf = <$fd>;
2891 close $fd;
2892 if (defined $conf) {
2893 chomp $conf;
2895 return $conf;
2898 sub git_get_project_description {
2899 my $path = shift;
2900 return git_get_file_or_project_config($path, 'description');
2903 sub git_get_project_category {
2904 my $path = shift;
2905 return git_get_file_or_project_config($path, 'category');
2909 # supported formats:
2910 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2911 # - if its contents is a number, use it as tag weight,
2912 # - otherwise add a tag with weight 1
2913 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2914 # the same value multiple times increases tag weight
2915 # * `gitweb.ctag' multi-valued repo config variable
2916 sub git_get_project_ctags {
2917 my $project = shift;
2918 my $ctags = {};
2920 $git_dir = "$projectroot/$project";
2921 if (opendir my $dh, "$git_dir/ctags") {
2922 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2923 foreach my $tagfile (@files) {
2924 open my $ct, '<', $tagfile
2925 or next;
2926 my $val = <$ct>;
2927 chomp $val if $val;
2928 close $ct;
2930 (my $ctag = $tagfile) =~ s#.*/##;
2931 if ($val =~ /^\d+$/) {
2932 $ctags->{$ctag} = $val;
2933 } else {
2934 $ctags->{$ctag} = 1;
2937 closedir $dh;
2939 } elsif (open my $fh, '<', "$git_dir/ctags") {
2940 while (my $line = <$fh>) {
2941 chomp $line;
2942 $ctags->{$line}++ if $line;
2944 close $fh;
2946 } else {
2947 my $taglist = config_to_multi(git_get_project_config('ctag'));
2948 foreach my $tag (@$taglist) {
2949 $ctags->{$tag}++;
2953 return $ctags;
2956 # return hash, where keys are content tags ('ctags'),
2957 # and values are sum of weights of given tag in every project
2958 sub git_gather_all_ctags {
2959 my $projects = shift;
2960 my $ctags = {};
2962 foreach my $p (@$projects) {
2963 foreach my $ct (keys %{$p->{'ctags'}}) {
2964 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2968 return $ctags;
2971 sub git_populate_project_tagcloud {
2972 my $ctags = shift;
2974 # First, merge different-cased tags; tags vote on casing
2975 my %ctags_lc;
2976 foreach (keys %$ctags) {
2977 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2978 if (not $ctags_lc{lc $_}->{topcount}
2979 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2980 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2981 $ctags_lc{lc $_}->{topname} = $_;
2985 my $cloud;
2986 my $matched = $input_params{'ctag'};
2987 if (eval { require HTML::TagCloud; 1; }) {
2988 $cloud = HTML::TagCloud->new;
2989 foreach my $ctag (sort keys %ctags_lc) {
2990 # Pad the title with spaces so that the cloud looks
2991 # less crammed.
2992 my $title = esc_html($ctags_lc{$ctag}->{topname});
2993 $title =~ s/ /&nbsp;/g;
2994 $title =~ s/^/&nbsp;/g;
2995 $title =~ s/$/&nbsp;/g;
2996 if (defined $matched && $matched eq $ctag) {
2997 $title = qq(<span class="match">$title</span>);
2999 $cloud->add($title, href(project=>undef, ctag=>$ctag),
3000 $ctags_lc{$ctag}->{count});
3002 } else {
3003 $cloud = {};
3004 foreach my $ctag (keys %ctags_lc) {
3005 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3006 if (defined $matched && $matched eq $ctag) {
3007 $title = qq(<span class="match">$title</span>);
3009 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3010 $cloud->{$ctag}{ctag} =
3011 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3014 return $cloud;
3017 sub git_show_project_tagcloud {
3018 my ($cloud, $count) = @_;
3019 if (ref $cloud eq 'HTML::TagCloud') {
3020 return $cloud->html_and_css($count);
3021 } else {
3022 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3023 return
3024 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3025 join (', ', map {
3026 $cloud->{$_}->{'ctag'}
3027 } splice(@tags, 0, $count)) .
3028 '</div>';
3032 sub git_get_project_url_list {
3033 my $path = shift;
3035 $git_dir = "$projectroot/$path";
3036 open my $fd, '<', "$git_dir/cloneurl"
3037 or return wantarray ?
3038 @{ config_to_multi(git_get_project_config('url')) } :
3039 config_to_multi(git_get_project_config('url'));
3040 my @git_project_url_list = map { chomp; $_ } <$fd>;
3041 close $fd;
3043 return wantarray ? @git_project_url_list : \@git_project_url_list;
3046 sub git_get_projects_list {
3047 my $filter = shift || '';
3048 my $paranoid = shift;
3049 my @list;
3051 if (-d $projects_list) {
3052 # search in directory
3053 my $dir = $projects_list;
3054 # remove the trailing "/"
3055 $dir =~ s!/+$!!;
3056 my $pfxlen = length("$dir");
3057 my $pfxdepth = ($dir =~ tr!/!!);
3058 # when filtering, search only given subdirectory
3059 if ($filter && !$paranoid) {
3060 $dir .= "/$filter";
3061 $dir =~ s!/+$!!;
3064 File::Find::find({
3065 follow_fast => 1, # follow symbolic links
3066 follow_skip => 2, # ignore duplicates
3067 dangling_symlinks => 0, # ignore dangling symlinks, silently
3068 wanted => sub {
3069 # global variables
3070 our $project_maxdepth;
3071 our $projectroot;
3072 # skip project-list toplevel, if we get it.
3073 return if (m!^[/.]$!);
3074 # only directories can be git repositories
3075 return unless (-d $_);
3076 # need search permission
3077 return unless (-x $_);
3078 # don't traverse too deep (Find is super slow on os x)
3079 # $project_maxdepth excludes depth of $projectroot
3080 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3081 $File::Find::prune = 1;
3082 return;
3085 my $path = substr($File::Find::name, $pfxlen + 1);
3086 # paranoidly only filter here
3087 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3088 next;
3090 # we check related file in $projectroot
3091 if (check_export_ok("$projectroot/$path")) {
3092 push @list, { path => $path };
3093 $File::Find::prune = 1;
3096 }, "$dir");
3098 } elsif (-f $projects_list) {
3099 # read from file(url-encoded):
3100 # 'git%2Fgit.git Linus+Torvalds'
3101 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3102 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3103 open my $fd, '<', $projects_list or return;
3104 PROJECT:
3105 while (my $line = <$fd>) {
3106 chomp $line;
3107 my ($path, $owner) = split ' ', $line;
3108 $path = unescape($path);
3109 $owner = unescape($owner);
3110 if (!defined $path) {
3111 next;
3113 # if $filter is rpovided, check if $path begins with $filter
3114 if ($filter && $path !~ m!^\Q$filter\E/!) {
3115 next;
3117 if (check_export_ok("$projectroot/$path")) {
3118 my $pr = {
3119 path => $path
3121 if ($owner) {
3122 $pr->{'owner'} = to_utf8($owner);
3124 push @list, $pr;
3127 close $fd;
3129 return @list;
3132 # written with help of Tree::Trie module (Perl Artistic License, GPL compatible)
3133 # as side effects it sets 'forks' field to list of forks for forked projects
3134 sub filter_forks_from_projects_list {
3135 my $projects = shift;
3137 my %trie; # prefix tree of directories (path components)
3138 # generate trie out of those directories that might contain forks
3139 foreach my $pr (@$projects) {
3140 my $path = $pr->{'path'};
3141 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3142 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3143 next unless ($path); # skip '.git' repository: tests, git-instaweb
3144 next unless (-d "$projectroot/$path"); # containing directory exists
3145 $pr->{'forks'} = []; # there can be 0 or more forks of project
3147 # add to trie
3148 my @dirs = split('/', $path);
3149 # walk the trie, until either runs out of components or out of trie
3150 my $ref = \%trie;
3151 while (scalar @dirs &&
3152 exists($ref->{$dirs[0]})) {
3153 $ref = $ref->{shift @dirs};
3155 # create rest of trie structure from rest of components
3156 foreach my $dir (@dirs) {
3157 $ref = $ref->{$dir} = {};
3159 # create end marker, store $pr as a data
3160 $ref->{''} = $pr if (!exists $ref->{''});
3163 # filter out forks, by finding shortest prefix match for paths
3164 my @filtered;
3165 PROJECT:
3166 foreach my $pr (@$projects) {
3167 # trie lookup
3168 my $ref = \%trie;
3169 DIR:
3170 foreach my $dir (split('/', $pr->{'path'})) {
3171 if (exists $ref->{''}) {
3172 # found [shortest] prefix, is a fork - skip it
3173 push @{$ref->{''}{'forks'}}, $pr;
3174 next PROJECT;
3176 if (!exists $ref->{$dir}) {
3177 # not in trie, cannot have prefix, not a fork
3178 push @filtered, $pr;
3179 next PROJECT;
3181 # If the dir is there, we just walk one step down the trie.
3182 $ref = $ref->{$dir};
3184 # we ran out of trie
3185 # (shouldn't happen: it's either no match, or end marker)
3186 push @filtered, $pr;
3189 return @filtered;
3192 # note: fill_project_list_info must be run first,
3193 # for 'descr_long' and 'ctags' to be filled
3194 sub search_projects_list {
3195 my ($projlist, %opts) = @_;
3196 my $tagfilter = $opts{'tagfilter'};
3197 my $search_re = $opts{'search_regexp'};
3199 return @$projlist
3200 unless ($tagfilter || $search_re);
3202 # searching projects require filling to be run before it;
3203 fill_project_list_info($projlist,
3204 $tagfilter ? 'ctags' : (),
3205 $search_re ? ('path', 'descr') : ());
3206 my @projects;
3207 PROJECT:
3208 foreach my $pr (@$projlist) {
3210 if ($tagfilter) {
3211 next unless ref($pr->{'ctags'}) eq 'HASH';
3212 next unless
3213 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3216 if ($search_re) {
3217 next unless
3218 $pr->{'path'} =~ /$search_re/ ||
3219 $pr->{'descr_long'} =~ /$search_re/;
3222 push @projects, $pr;
3225 return @projects;
3228 our $gitweb_project_owner = undef;
3229 sub git_get_project_list_from_file {
3231 return if (defined $gitweb_project_owner);
3233 $gitweb_project_owner = {};
3234 # read from file (url-encoded):
3235 # 'git%2Fgit.git Linus+Torvalds'
3236 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3237 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3238 if (-f $projects_list) {
3239 open(my $fd, '<', $projects_list);
3240 while (my $line = <$fd>) {
3241 chomp $line;
3242 my ($pr, $ow) = split ' ', $line;
3243 $pr = unescape($pr);
3244 $ow = unescape($ow);
3245 $gitweb_project_owner->{$pr} = to_utf8($ow);
3247 close $fd;
3251 sub git_get_project_owner {
3252 my $project = shift;
3253 my $owner;
3255 return undef unless $project;
3256 $git_dir = "$projectroot/$project";
3258 if (!defined $gitweb_project_owner) {
3259 git_get_project_list_from_file();
3262 if (exists $gitweb_project_owner->{$project}) {
3263 $owner = $gitweb_project_owner->{$project};
3265 if (!defined $owner){
3266 $owner = git_get_project_config('owner');
3268 if (!defined $owner) {
3269 $owner = get_file_owner("$git_dir");
3272 return $owner;
3275 sub git_get_last_activity {
3276 my ($path) = @_;
3277 my $fd;
3279 $git_dir = "$projectroot/$path";
3280 open($fd, "-|", git_cmd(), 'for-each-ref',
3281 '--format=%(committer)',
3282 '--sort=-committerdate',
3283 '--count=1',
3284 map { "refs/$_" } get_branch_refs ()) or return;
3285 my $most_recent = <$fd>;
3286 close $fd or return;
3287 if (defined $most_recent &&
3288 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3289 my $timestamp = $1;
3290 my $age = time - $timestamp;
3291 return ($age, age_string($age));
3293 return (undef, undef);
3296 # Implementation note: when a single remote is wanted, we cannot use 'git
3297 # remote show -n' because that command always work (assuming it's a remote URL
3298 # if it's not defined), and we cannot use 'git remote show' because that would
3299 # try to make a network roundtrip. So the only way to find if that particular
3300 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3301 # and when we find what we want.
3302 sub git_get_remotes_list {
3303 my $wanted = shift;
3304 my %remotes = ();
3306 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3307 return unless $fd;
3308 while (my $remote = <$fd>) {
3309 chomp $remote;
3310 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3311 next if $wanted and not $remote eq $wanted;
3312 my ($url, $key) = ($1, $2);
3314 $remotes{$remote} ||= { 'heads' => () };
3315 $remotes{$remote}{$key} = $url;
3317 close $fd or return;
3318 return wantarray ? %remotes : \%remotes;
3321 # Takes a hash of remotes as first parameter and fills it by adding the
3322 # available remote heads for each of the indicated remotes.
3323 sub fill_remote_heads {
3324 my $remotes = shift;
3325 my @heads = map { "remotes/$_" } keys %$remotes;
3326 my @remoteheads = git_get_heads_list(undef, @heads);
3327 foreach my $remote (keys %$remotes) {
3328 $remotes->{$remote}{'heads'} = [ grep {
3329 $_->{'name'} =~ s!^$remote/!!
3330 } @remoteheads ];
3334 sub git_get_references {
3335 my $type = shift || "";
3336 my %refs;
3337 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3338 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3339 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3340 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3341 or return;
3343 while (my $line = <$fd>) {
3344 chomp $line;
3345 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3346 if (defined $refs{$1}) {
3347 push @{$refs{$1}}, $2;
3348 } else {
3349 $refs{$1} = [ $2 ];
3353 close $fd or return;
3354 return \%refs;
3357 sub git_get_rev_name_tags {
3358 my $hash = shift || return undef;
3360 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3361 or return;
3362 my $name_rev = <$fd>;
3363 close $fd;
3365 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3366 return $1;
3367 } else {
3368 # catches also '$hash undefined' output
3369 return undef;
3373 ## ----------------------------------------------------------------------
3374 ## parse to hash functions
3376 sub parse_date {
3377 my $epoch = shift;
3378 my $tz = shift || "-0000";
3380 my %date;
3381 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3382 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3383 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3384 $date{'hour'} = $hour;
3385 $date{'minute'} = $min;
3386 $date{'mday'} = $mday;
3387 $date{'day'} = $days[$wday];
3388 $date{'month'} = $months[$mon];
3389 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3390 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3391 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3392 $mday, $months[$mon], $hour ,$min;
3393 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3394 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3396 my ($tz_sign, $tz_hour, $tz_min) =
3397 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3398 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3399 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3400 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3401 $date{'hour_local'} = $hour;
3402 $date{'minute_local'} = $min;
3403 $date{'tz_local'} = $tz;
3404 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3405 1900+$year, $mon+1, $mday,
3406 $hour, $min, $sec, $tz);
3407 return %date;
3410 sub parse_tag {
3411 my $tag_id = shift;
3412 my %tag;
3413 my @comment;
3415 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3416 $tag{'id'} = $tag_id;
3417 while (my $line = <$fd>) {
3418 chomp $line;
3419 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3420 $tag{'object'} = $1;
3421 } elsif ($line =~ m/^type (.+)$/) {
3422 $tag{'type'} = $1;
3423 } elsif ($line =~ m/^tag (.+)$/) {
3424 $tag{'name'} = $1;
3425 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3426 $tag{'author'} = $1;
3427 $tag{'author_epoch'} = $2;
3428 $tag{'author_tz'} = $3;
3429 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3430 $tag{'author_name'} = $1;
3431 $tag{'author_email'} = $2;
3432 } else {
3433 $tag{'author_name'} = $tag{'author'};
3435 } elsif ($line =~ m/--BEGIN/) {
3436 push @comment, $line;
3437 last;
3438 } elsif ($line eq "") {
3439 last;
3442 push @comment, <$fd>;
3443 $tag{'comment'} = \@comment;
3444 close $fd or return;
3445 if (!defined $tag{'name'}) {
3446 return
3448 return %tag
3451 sub parse_commit_text {
3452 my ($commit_text, $withparents) = @_;
3453 my @commit_lines = split '\n', $commit_text;
3454 my %co;
3456 pop @commit_lines; # Remove '\0'
3458 if (! @commit_lines) {
3459 return;
3462 my $header = shift @commit_lines;
3463 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3464 return;
3466 ($co{'id'}, my @parents) = split ' ', $header;
3467 while (my $line = shift @commit_lines) {
3468 last if $line eq "\n";
3469 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3470 $co{'tree'} = $1;
3471 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3472 push @parents, $1;
3473 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3474 $co{'author'} = to_utf8($1);
3475 $co{'author_epoch'} = $2;
3476 $co{'author_tz'} = $3;
3477 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3478 $co{'author_name'} = $1;
3479 $co{'author_email'} = $2;
3480 } else {
3481 $co{'author_name'} = $co{'author'};
3483 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3484 $co{'committer'} = to_utf8($1);
3485 $co{'committer_epoch'} = $2;
3486 $co{'committer_tz'} = $3;
3487 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3488 $co{'committer_name'} = $1;
3489 $co{'committer_email'} = $2;
3490 } else {
3491 $co{'committer_name'} = $co{'committer'};
3495 if (!defined $co{'tree'}) {
3496 return;
3498 $co{'parents'} = \@parents;
3499 $co{'parent'} = $parents[0];
3501 foreach my $title (@commit_lines) {
3502 $title =~ s/^ //;
3503 if ($title ne "") {
3504 $co{'title'} = chop_str($title, 80, 5);
3505 # remove leading stuff of merges to make the interesting part visible
3506 if (length($title) > 50) {
3507 $title =~ s/^Automatic //;
3508 $title =~ s/^merge (of|with) /Merge ... /i;
3509 if (length($title) > 50) {
3510 $title =~ s/(http|rsync):\/\///;
3512 if (length($title) > 50) {
3513 $title =~ s/(master|www|rsync)\.//;
3515 if (length($title) > 50) {
3516 $title =~ s/kernel.org:?//;
3518 if (length($title) > 50) {
3519 $title =~ s/\/pub\/scm//;
3522 $co{'title_short'} = chop_str($title, 50, 5);
3523 last;
3526 if (! defined $co{'title'} || $co{'title'} eq "") {
3527 $co{'title'} = $co{'title_short'} = '(no commit message)';
3529 # remove added spaces
3530 foreach my $line (@commit_lines) {
3531 $line =~ s/^ //;
3533 $co{'comment'} = \@commit_lines;
3535 my $age = time - $co{'committer_epoch'};
3536 $co{'age'} = $age;
3537 $co{'age_string'} = age_string($age);
3538 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3539 if ($age > 60*60*24*7*2) {
3540 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3541 $co{'age_string_age'} = $co{'age_string'};
3542 } else {
3543 $co{'age_string_date'} = $co{'age_string'};
3544 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3546 return %co;
3549 sub parse_commit {
3550 my ($commit_id) = @_;
3551 my %co;
3553 local $/ = "\0";
3555 open my $fd, "-|", git_cmd(), "rev-list",
3556 "--parents",
3557 "--header",
3558 "--max-count=1",
3559 $commit_id,
3560 "--",
3561 or die_error(500, "Open git-rev-list failed");
3562 %co = parse_commit_text(<$fd>, 1);
3563 close $fd;
3565 return %co;
3568 sub parse_commits {
3569 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3570 my @cos;
3572 $maxcount ||= 1;
3573 $skip ||= 0;
3575 local $/ = "\0";
3577 open my $fd, "-|", git_cmd(), "rev-list",
3578 "--header",
3579 @args,
3580 ("--max-count=" . $maxcount),
3581 ("--skip=" . $skip),
3582 @extra_options,
3583 $commit_id,
3584 "--",
3585 ($filename ? ($filename) : ())
3586 or die_error(500, "Open git-rev-list failed");
3587 while (my $line = <$fd>) {
3588 my %co = parse_commit_text($line);
3589 push @cos, \%co;
3591 close $fd;
3593 return wantarray ? @cos : \@cos;
3596 # parse line of git-diff-tree "raw" output
3597 sub parse_difftree_raw_line {
3598 my $line = shift;
3599 my %res;
3601 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3602 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3603 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3604 $res{'from_mode'} = $1;
3605 $res{'to_mode'} = $2;
3606 $res{'from_id'} = $3;
3607 $res{'to_id'} = $4;
3608 $res{'status'} = $5;
3609 $res{'similarity'} = $6;
3610 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3611 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3612 } else {
3613 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3616 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3617 # combined diff (for merge commit)
3618 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3619 $res{'nparents'} = length($1);
3620 $res{'from_mode'} = [ split(' ', $2) ];
3621 $res{'to_mode'} = pop @{$res{'from_mode'}};
3622 $res{'from_id'} = [ split(' ', $3) ];
3623 $res{'to_id'} = pop @{$res{'from_id'}};
3624 $res{'status'} = [ split('', $4) ];
3625 $res{'to_file'} = unquote($5);
3627 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3628 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3629 $res{'commit'} = $1;
3632 return wantarray ? %res : \%res;
3635 # wrapper: return parsed line of git-diff-tree "raw" output
3636 # (the argument might be raw line, or parsed info)
3637 sub parsed_difftree_line {
3638 my $line_or_ref = shift;
3640 if (ref($line_or_ref) eq "HASH") {
3641 # pre-parsed (or generated by hand)
3642 return $line_or_ref;
3643 } else {
3644 return parse_difftree_raw_line($line_or_ref);
3648 # parse line of git-ls-tree output
3649 sub parse_ls_tree_line {
3650 my $line = shift;
3651 my %opts = @_;
3652 my %res;
3654 if ($opts{'-l'}) {
3655 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3656 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3658 $res{'mode'} = $1;
3659 $res{'type'} = $2;
3660 $res{'hash'} = $3;
3661 $res{'size'} = $4;
3662 if ($opts{'-z'}) {
3663 $res{'name'} = $5;
3664 } else {
3665 $res{'name'} = unquote($5);
3667 } else {
3668 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3669 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3671 $res{'mode'} = $1;
3672 $res{'type'} = $2;
3673 $res{'hash'} = $3;
3674 if ($opts{'-z'}) {
3675 $res{'name'} = $4;
3676 } else {
3677 $res{'name'} = unquote($4);
3681 return wantarray ? %res : \%res;
3684 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3685 sub parse_from_to_diffinfo {
3686 my ($diffinfo, $from, $to, @parents) = @_;
3688 if ($diffinfo->{'nparents'}) {
3689 # combined diff
3690 $from->{'file'} = [];
3691 $from->{'href'} = [];
3692 fill_from_file_info($diffinfo, @parents)
3693 unless exists $diffinfo->{'from_file'};
3694 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3695 $from->{'file'}[$i] =
3696 defined $diffinfo->{'from_file'}[$i] ?
3697 $diffinfo->{'from_file'}[$i] :
3698 $diffinfo->{'to_file'};
3699 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3700 $from->{'href'}[$i] = href(action=>"blob",
3701 hash_base=>$parents[$i],
3702 hash=>$diffinfo->{'from_id'}[$i],
3703 file_name=>$from->{'file'}[$i]);
3704 } else {
3705 $from->{'href'}[$i] = undef;
3708 } else {
3709 # ordinary (not combined) diff
3710 $from->{'file'} = $diffinfo->{'from_file'};
3711 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3712 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3713 hash=>$diffinfo->{'from_id'},
3714 file_name=>$from->{'file'});
3715 } else {
3716 delete $from->{'href'};
3720 $to->{'file'} = $diffinfo->{'to_file'};
3721 if (!is_deleted($diffinfo)) { # file exists in result
3722 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3723 hash=>$diffinfo->{'to_id'},
3724 file_name=>$to->{'file'});
3725 } else {
3726 delete $to->{'href'};
3730 ## ......................................................................
3731 ## parse to array of hashes functions
3733 sub git_get_heads_list {
3734 my ($limit, @classes) = @_;
3735 @classes = get_branch_refs() unless @classes;
3736 my @patterns = map { "refs/$_" } @classes;
3737 my @headslist;
3739 open my $fd, '-|', git_cmd(), 'for-each-ref',
3740 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3741 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3742 @patterns
3743 or return;
3744 while (my $line = <$fd>) {
3745 my %ref_item;
3747 chomp $line;
3748 my ($refinfo, $committerinfo) = split(/\0/, $line);
3749 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3750 my ($committer, $epoch, $tz) =
3751 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3752 $ref_item{'fullname'} = $name;
3753 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3754 $name =~ s!^refs/($strip_refs|remotes)/!!;
3755 $ref_item{'name'} = $name;
3756 # for refs neither in 'heads' nor 'remotes' we want to
3757 # show their ref dir
3758 my $ref_dir = (defined $1) ? $1 : '';
3759 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3760 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3763 $ref_item{'id'} = $hash;
3764 $ref_item{'title'} = $title || '(no commit message)';
3765 $ref_item{'epoch'} = $epoch;
3766 if ($epoch) {
3767 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3768 } else {
3769 $ref_item{'age'} = "unknown";
3772 push @headslist, \%ref_item;
3774 close $fd;
3776 return wantarray ? @headslist : \@headslist;
3779 sub git_get_tags_list {
3780 my $limit = shift;
3781 my @tagslist;
3783 open my $fd, '-|', git_cmd(), 'for-each-ref',
3784 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3785 '--format=%(objectname) %(objecttype) %(refname) '.
3786 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3787 'refs/tags'
3788 or return;
3789 while (my $line = <$fd>) {
3790 my %ref_item;
3792 chomp $line;
3793 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3794 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3795 my ($creator, $epoch, $tz) =
3796 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3797 $ref_item{'fullname'} = $name;
3798 $name =~ s!^refs/tags/!!;
3800 $ref_item{'type'} = $type;
3801 $ref_item{'id'} = $id;
3802 $ref_item{'name'} = $name;
3803 if ($type eq "tag") {
3804 $ref_item{'subject'} = $title;
3805 $ref_item{'reftype'} = $reftype;
3806 $ref_item{'refid'} = $refid;
3807 } else {
3808 $ref_item{'reftype'} = $type;
3809 $ref_item{'refid'} = $id;
3812 if ($type eq "tag" || $type eq "commit") {
3813 $ref_item{'epoch'} = $epoch;
3814 if ($epoch) {
3815 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3816 } else {
3817 $ref_item{'age'} = "unknown";
3821 push @tagslist, \%ref_item;
3823 close $fd;
3825 return wantarray ? @tagslist : \@tagslist;
3828 ## ----------------------------------------------------------------------
3829 ## filesystem-related functions
3831 sub get_file_owner {
3832 my $path = shift;
3834 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3835 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3836 if (!defined $gcos) {
3837 return undef;
3839 my $owner = $gcos;
3840 $owner =~ s/[,;].*$//;
3841 return to_utf8($owner);
3844 # assume that file exists
3845 sub insert_file {
3846 my $filename = shift;
3848 open my $fd, '<', $filename;
3849 print map { to_utf8($_) } <$fd>;
3850 close $fd;
3853 ## ......................................................................
3854 ## mimetype related functions
3856 sub mimetype_guess_file {
3857 my $filename = shift;
3858 my $mimemap = shift;
3859 -r $mimemap or return undef;
3861 my %mimemap;
3862 open(my $mh, '<', $mimemap) or return undef;
3863 while (<$mh>) {
3864 next if m/^#/; # skip comments
3865 my ($mimetype, @exts) = split(/\s+/);
3866 foreach my $ext (@exts) {
3867 $mimemap{$ext} = $mimetype;
3870 close($mh);
3872 $filename =~ /\.([^.]*)$/;
3873 return $mimemap{$1};
3876 sub mimetype_guess {
3877 my $filename = shift;
3878 my $mime;
3879 $filename =~ /\./ or return undef;
3881 if ($mimetypes_file) {
3882 my $file = $mimetypes_file;
3883 if ($file !~ m!^/!) { # if it is relative path
3884 # it is relative to project
3885 $file = "$projectroot/$project/$file";
3887 $mime = mimetype_guess_file($filename, $file);
3889 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3890 return $mime;
3893 sub blob_mimetype {
3894 my $fd = shift;
3895 my $filename = shift;
3897 if ($filename) {
3898 my $mime = mimetype_guess($filename);
3899 $mime and return $mime;
3902 # just in case
3903 return $default_blob_plain_mimetype unless $fd;
3905 if (-T $fd) {
3906 return 'text/plain';
3907 } elsif (! $filename) {
3908 return 'application/octet-stream';
3909 } elsif ($filename =~ m/\.png$/i) {
3910 return 'image/png';
3911 } elsif ($filename =~ m/\.gif$/i) {
3912 return 'image/gif';
3913 } elsif ($filename =~ m/\.jpe?g$/i) {
3914 return 'image/jpeg';
3915 } else {
3916 return 'application/octet-stream';
3920 sub blob_contenttype {
3921 my ($fd, $file_name, $type) = @_;
3923 $type ||= blob_mimetype($fd, $file_name);
3924 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3925 $type .= "; charset=$default_text_plain_charset";
3928 return $type;
3931 # guess file syntax for syntax highlighting; return undef if no highlighting
3932 # the name of syntax can (in the future) depend on syntax highlighter used
3933 sub guess_file_syntax {
3934 my ($highlight, $file_name) = @_;
3935 return undef unless ($highlight && defined $file_name);
3936 my $basename = basename($file_name, '.in');
3937 return $highlight_basename{$basename}
3938 if exists $highlight_basename{$basename};
3940 $basename =~ /\.([^.]*)$/;
3941 my $ext = $1 or return undef;
3942 return $highlight_ext{$ext}
3943 if exists $highlight_ext{$ext};
3945 return undef;
3948 # run highlighter and return FD of its output,
3949 # or return original FD if no highlighting
3950 sub run_highlighter {
3951 my ($fd, $highlight, $syntax) = @_;
3952 return $fd unless ($highlight);
3954 close $fd;
3955 my $syntax_arg = (defined $syntax) ? "--syntax $syntax" : "--force";
3956 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3957 quote_command($^X, '-CO', '-MEncode=decode,FB_DEFAULT', '-pse',
3958 '$_ = decode($fe, $_, FB_DEFAULT) if !utf8::decode($_);',
3959 '--', "-fe=$fallback_encoding")." | ".
3960 quote_command($highlight_bin).
3961 " --replace-tabs=8 --fragment $syntax_arg |"
3962 or die_error(500, "Couldn't open file or run syntax highlighter");
3963 return $fd;
3966 ## ======================================================================
3967 ## functions printing HTML: header, footer, error page
3969 sub get_page_title {
3970 my $title = to_utf8($site_name);
3972 unless (defined $project) {
3973 if (defined $project_filter) {
3974 $title .= " - projects in '" . esc_path($project_filter) . "'";
3976 return $title;
3978 $title .= " - " . to_utf8($project);
3980 return $title unless (defined $action);
3981 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3983 return $title unless (defined $file_name);
3984 $title .= " - " . esc_path($file_name);
3985 if ($action eq "tree" && $file_name !~ m|/$|) {
3986 $title .= "/";
3989 return $title;
3992 sub get_content_type_html {
3993 # require explicit support from the UA if we are to send the page as
3994 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3995 # we have to do this because MSIE sometimes globs '*/*', pretending to
3996 # support xhtml+xml but choking when it gets what it asked for.
3997 if (defined $cgi->http('HTTP_ACCEPT') &&
3998 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3999 $cgi->Accept('application/xhtml+xml') != 0) {
4000 return 'application/xhtml+xml';
4001 } else {
4002 return 'text/html';
4006 sub print_feed_meta {
4007 if (defined $project) {
4008 my %href_params = get_feed_info();
4009 if (!exists $href_params{'-title'}) {
4010 $href_params{'-title'} = 'log';
4013 foreach my $format (qw(RSS Atom)) {
4014 my $type = lc($format);
4015 my %link_attr = (
4016 '-rel' => 'alternate',
4017 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4018 '-type' => "application/$type+xml"
4021 $href_params{'extra_options'} = undef;
4022 $href_params{'action'} = $type;
4023 $link_attr{'-href'} = href(%href_params);
4024 print "<link ".
4025 "rel=\"$link_attr{'-rel'}\" ".
4026 "title=\"$link_attr{'-title'}\" ".
4027 "href=\"$link_attr{'-href'}\" ".
4028 "type=\"$link_attr{'-type'}\" ".
4029 "/>\n";
4031 $href_params{'extra_options'} = '--no-merges';
4032 $link_attr{'-href'} = href(%href_params);
4033 $link_attr{'-title'} .= ' (no merges)';
4034 print "<link ".
4035 "rel=\"$link_attr{'-rel'}\" ".
4036 "title=\"$link_attr{'-title'}\" ".
4037 "href=\"$link_attr{'-href'}\" ".
4038 "type=\"$link_attr{'-type'}\" ".
4039 "/>\n";
4042 } else {
4043 printf('<link rel="alternate" title="%s projects list" '.
4044 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4045 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4046 printf('<link rel="alternate" title="%s projects feeds" '.
4047 'href="%s" type="text/x-opml" />'."\n",
4048 esc_attr($site_name), href(project=>undef, action=>"opml"));
4052 sub print_header_links {
4053 my $status = shift;
4055 # print out each stylesheet that exist, providing backwards capability
4056 # for those people who defined $stylesheet in a config file
4057 if (defined $stylesheet) {
4058 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4059 } else {
4060 foreach my $stylesheet (@stylesheets) {
4061 next unless $stylesheet;
4062 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4065 print_feed_meta()
4066 if ($status eq '200 OK');
4067 if (defined $favicon) {
4068 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4072 sub print_nav_breadcrumbs_path {
4073 my $dirprefix = undef;
4074 while (my $part = shift) {
4075 $dirprefix .= "/" if defined $dirprefix;
4076 $dirprefix .= $part;
4077 print $cgi->a({-href => href(project => undef,
4078 project_filter => $dirprefix,
4079 action => "project_list")},
4080 esc_html($part)) . " / ";
4084 sub print_nav_breadcrumbs {
4085 my %opts = @_;
4087 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4088 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4090 if (defined $project) {
4091 my @dirname = split '/', $project;
4092 my $projectbasename = pop @dirname;
4093 print_nav_breadcrumbs_path(@dirname);
4094 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4095 if (defined $action) {
4096 my $action_print = $action ;
4097 if (defined $opts{-action_extra}) {
4098 $action_print = $cgi->a({-href => href(action=>$action)},
4099 $action);
4101 print " / $action_print";
4103 if (defined $opts{-action_extra}) {
4104 print " / $opts{-action_extra}";
4106 print "\n";
4107 } elsif (defined $project_filter) {
4108 print_nav_breadcrumbs_path(split '/', $project_filter);
4112 sub print_search_form {
4113 if (!defined $searchtext) {
4114 $searchtext = "";
4116 my $search_hash;
4117 if (defined $hash_base) {
4118 $search_hash = $hash_base;
4119 } elsif (defined $hash) {
4120 $search_hash = $hash;
4121 } else {
4122 $search_hash = "HEAD";
4124 my $action = $my_uri;
4125 my $use_pathinfo = gitweb_check_feature('pathinfo');
4126 if ($use_pathinfo) {
4127 $action .= "/".esc_url($project);
4129 print $cgi->start_form(-method => "get", -action => $action) .
4130 "<div class=\"search\">\n" .
4131 (!$use_pathinfo &&
4132 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4133 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4134 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4135 $cgi->popup_menu(-name => 'st', -default => 'commit',
4136 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4137 " " . $cgi->a({-href => href(action=>"search_help"),
4138 -title => "search help" }, "?") . " search:\n",
4139 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4140 "<span title=\"Extended regular expression\">" .
4141 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4142 -checked => $search_use_regexp) .
4143 "</span>" .
4144 "</div>" .
4145 $cgi->end_form() . "\n";
4148 sub git_header_html {
4149 my $status = shift || "200 OK";
4150 my $expires = shift;
4151 my %opts = @_;
4153 my $title = get_page_title();
4154 my $content_type = get_content_type_html();
4155 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4156 -status=> $status, -expires => $expires)
4157 unless ($opts{'-no_http_header'});
4158 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4159 print <<EOF;
4160 <?xml version="1.0" encoding="utf-8"?>
4161 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4162 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4163 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4164 <!-- git core binaries version $git_version -->
4165 <head>
4166 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4167 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4168 <meta name="robots" content="index, nofollow"/>
4169 <title>$title</title>
4171 # the stylesheet, favicon etc urls won't work correctly with path_info
4172 # unless we set the appropriate base URL
4173 if ($ENV{'PATH_INFO'}) {
4174 print "<base href=\"".esc_url($base_url)."\" />\n";
4176 print_header_links($status);
4178 if (defined $site_html_head_string) {
4179 print to_utf8($site_html_head_string);
4182 print "</head>\n" .
4183 "<body>\n";
4185 if (defined $site_header && -f $site_header) {
4186 insert_file($site_header);
4189 print "<div class=\"page_header\">\n";
4190 if (defined $logo) {
4191 print $cgi->a({-href => esc_url($logo_url),
4192 -title => $logo_label},
4193 $cgi->img({-src => esc_url($logo),
4194 -width => 72, -height => 27,
4195 -alt => "git",
4196 -class => "logo"}));
4198 print_nav_breadcrumbs(%opts);
4199 print "</div>\n";
4201 my $have_search = gitweb_check_feature('search');
4202 if (defined $project && $have_search) {
4203 print_search_form();
4207 sub git_footer_html {
4208 my $feed_class = 'rss_logo';
4210 print "<div class=\"page_footer\">\n";
4211 if (defined $project) {
4212 my $descr = git_get_project_description($project);
4213 if (defined $descr) {
4214 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4217 my %href_params = get_feed_info();
4218 if (!%href_params) {
4219 $feed_class .= ' generic';
4221 $href_params{'-title'} ||= 'log';
4223 foreach my $format (qw(RSS Atom)) {
4224 $href_params{'action'} = lc($format);
4225 print $cgi->a({-href => href(%href_params),
4226 -title => "$href_params{'-title'} $format feed",
4227 -class => $feed_class}, $format)."\n";
4230 } else {
4231 print $cgi->a({-href => href(project=>undef, action=>"opml",
4232 project_filter => $project_filter),
4233 -class => $feed_class}, "OPML") . " ";
4234 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4235 project_filter => $project_filter),
4236 -class => $feed_class}, "TXT") . "\n";
4238 print "</div>\n"; # class="page_footer"
4240 if (defined $t0 && gitweb_check_feature('timed')) {
4241 print "<div id=\"generating_info\">\n";
4242 print 'This page took '.
4243 '<span id="generating_time" class="time_span">'.
4244 tv_interval($t0, [ gettimeofday() ]).
4245 ' seconds </span>'.
4246 ' and '.
4247 '<span id="generating_cmd">'.
4248 $number_of_git_cmds.
4249 '</span> git commands '.
4250 " to generate.\n";
4251 print "</div>\n"; # class="page_footer"
4254 if (defined $site_footer && -f $site_footer) {
4255 insert_file($site_footer);
4258 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4259 if (defined $action &&
4260 $action eq 'blame_incremental') {
4261 print qq!<script type="text/javascript">\n!.
4262 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4263 qq! "!. href() .qq!");\n!.
4264 qq!</script>\n!;
4265 } else {
4266 my ($jstimezone, $tz_cookie, $datetime_class) =
4267 gitweb_get_feature('javascript-timezone');
4269 print qq!<script type="text/javascript">\n!.
4270 qq!window.onload = function () {\n!;
4271 if (gitweb_check_feature('javascript-actions')) {
4272 print qq! fixLinks();\n!;
4274 if ($jstimezone && $tz_cookie && $datetime_class) {
4275 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4276 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4278 print qq!};\n!.
4279 qq!</script>\n!;
4282 print "</body>\n" .
4283 "</html>";
4286 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4287 # Example: die_error(404, 'Hash not found')
4288 # By convention, use the following status codes (as defined in RFC 2616):
4289 # 400: Invalid or missing CGI parameters, or
4290 # requested object exists but has wrong type.
4291 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4292 # this server or project.
4293 # 404: Requested object/revision/project doesn't exist.
4294 # 500: The server isn't configured properly, or
4295 # an internal error occurred (e.g. failed assertions caused by bugs), or
4296 # an unknown error occurred (e.g. the git binary died unexpectedly).
4297 # 503: The server is currently unavailable (because it is overloaded,
4298 # or down for maintenance). Generally, this is a temporary state.
4299 sub die_error {
4300 my $status = shift || 500;
4301 my $error = esc_html(shift) || "Internal Server Error";
4302 my $extra = shift;
4303 my %opts = @_;
4305 my %http_responses = (
4306 400 => '400 Bad Request',
4307 403 => '403 Forbidden',
4308 404 => '404 Not Found',