Only switch on the line number toggle when highlighting is activated
[git/dscho.git] / gitweb / gitweb.perl
blob2991d3e00aa05606bf2dd3a058bc11ed76295ad9
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 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
19 use File::Basename qw(basename);
20 use Time::HiRes qw(gettimeofday tv_interval);
21 binmode STDOUT, ':utf8';
23 our $t0 = [ gettimeofday() ];
24 our $number_of_git_cmds = 0;
26 BEGIN {
27 CGI->compile() if $ENV{'MOD_PERL'};
30 our $version = "++GIT_VERSION++";
32 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
33 sub evaluate_uri {
34 our $cgi;
36 our $my_url = $cgi->url();
37 our $my_uri = $cgi->url(-absolute => 1);
39 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
40 # needed and used only for URLs with nonempty PATH_INFO
41 our $base_url = $my_url;
43 # When the script is used as DirectoryIndex, the URL does not contain the name
44 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
45 # have to do it ourselves. We make $path_info global because it's also used
46 # later on.
48 # Another issue with the script being the DirectoryIndex is that the resulting
49 # $my_url data is not the full script URL: this is good, because we want
50 # generated links to keep implying the script name if it wasn't explicitly
51 # indicated in the URL we're handling, but it means that $my_url cannot be used
52 # as base URL.
53 # Therefore, if we needed to strip PATH_INFO, then we know that we have
54 # to build the base URL ourselves:
55 our $path_info = decode_utf8($ENV{"PATH_INFO"});
56 if ($path_info) {
57 # $path_info has already been URL-decoded by the web server, but
58 # $my_url and $my_uri have not. URL-decode them so we can properly
59 # strip $path_info.
60 $my_url = unescape($my_url);
61 $my_uri = unescape($my_uri);
62 if ($my_url =~ s,\Q$path_info\E$,, &&
63 $my_uri =~ s,\Q$path_info\E$,, &&
64 defined $ENV{'SCRIPT_NAME'}) {
65 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
69 # target of the home link on top of all pages
70 our $home_link = $my_uri || "/";
73 # core git executable to use
74 # this can just be "git" if your webserver has a sensible PATH
75 our $GIT = "++GIT_BINDIR++/git";
77 # absolute fs-path which will be prepended to the project path
78 #our $projectroot = "/pub/scm";
79 our $projectroot = "++GITWEB_PROJECTROOT++";
81 # fs traversing limit for getting project list
82 # the number is relative to the projectroot
83 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
85 # string of the home link on top of all pages
86 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
88 # name of your site or organization to appear in page titles
89 # replace this with something more descriptive for clearer bookmarks
90 our $site_name = "++GITWEB_SITENAME++"
91 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
93 # html snippet to include in the <head> section of each page
94 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
95 # filename of html text to include at top of each page
96 our $site_header = "++GITWEB_SITE_HEADER++";
97 # html text to include at home page
98 our $home_text = "++GITWEB_HOMETEXT++";
99 # filename of html text to include at bottom of each page
100 our $site_footer = "++GITWEB_SITE_FOOTER++";
102 # URI of stylesheets
103 our @stylesheets = ("++GITWEB_CSS++");
104 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
105 our $stylesheet = undef;
106 # URI of GIT logo (72x27 size)
107 our $logo = "++GITWEB_LOGO++";
108 # URI of GIT favicon, assumed to be image/png type
109 our $favicon = "++GITWEB_FAVICON++";
110 # URI of gitweb.js (JavaScript code for gitweb)
111 our $javascript = "++GITWEB_JS++";
113 # URI and label (title) of GIT logo link
114 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
115 #our $logo_label = "git documentation";
116 our $logo_url = "http://git-scm.com/";
117 our $logo_label = "git homepage";
119 # source of projects list
120 our $projects_list = "++GITWEB_LIST++";
122 # the width (in characters) of the projects list "Description" column
123 our $projects_list_description_width = 25;
125 # group projects by category on the projects list
126 # (enabled if this variable evaluates to true)
127 our $projects_list_group_categories = 0;
129 # default category if none specified
130 # (leave the empty string for no category)
131 our $project_list_default_category = "";
133 # default order of projects list
134 # valid values are none, project, descr, owner, and age
135 our $default_projects_order = "project";
137 # show repository only if this file exists
138 # (only effective if this variable evaluates to true)
139 our $export_ok = "++GITWEB_EXPORT_OK++";
141 # don't generate age column on the projects list page
142 our $omit_age_column = 0;
144 # don't generate information about owners of repositories
145 our $omit_owner=0;
147 # show repository only if this subroutine returns true
148 # when given the path to the project, for example:
149 # sub { return -e "$_[0]/git-daemon-export-ok"; }
150 our $export_auth_hook = undef;
152 # only allow viewing of repositories also shown on the overview page
153 our $strict_export = "++GITWEB_STRICT_EXPORT++";
155 # list of git base URLs used for URL to where fetch project from,
156 # i.e. full URL is "$git_base_url/$project"
157 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
159 # default blob_plain mimetype and default charset for text/plain blob
160 our $default_blob_plain_mimetype = 'text/plain';
161 our $default_text_plain_charset = undef;
163 # file to use for guessing MIME types before trying /etc/mime.types
164 # (relative to the current git repository)
165 our $mimetypes_file = undef;
167 # assume this charset if line contains non-UTF-8 characters;
168 # it should be valid encoding (see Encoding::Supported(3pm) for list),
169 # for which encoding all byte sequences are valid, for example
170 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
171 # could be even 'utf-8' for the old behavior)
172 our $fallback_encoding = 'latin1';
174 # rename detection options for git-diff and git-diff-tree
175 # - default is '-M', with the cost proportional to
176 # (number of removed files) * (number of new files).
177 # - more costly is '-C' (which implies '-M'), with the cost proportional to
178 # (number of changed files + number of removed files) * (number of new files)
179 # - even more costly is '-C', '--find-copies-harder' with cost
180 # (number of files in the original tree) * (number of new files)
181 # - one might want to include '-B' option, e.g. '-B', '-M'
182 our @diff_opts = ('-M'); # taken from git_commit
184 # Disables features that would allow repository owners to inject script into
185 # the gitweb domain.
186 our $prevent_xss = 0;
188 # Path to the highlight executable to use (must be the one from
189 # http://www.andre-simon.de due to assumptions about parameters and output).
190 # Useful if highlight is not installed on your webserver's PATH.
191 # [Default: highlight]
192 our $highlight_bin = "++HIGHLIGHT_BIN++";
194 # information about snapshot formats that gitweb is capable of serving
195 our %known_snapshot_formats = (
196 # name => {
197 # 'display' => display name,
198 # 'type' => mime type,
199 # 'suffix' => filename suffix,
200 # 'format' => --format for git-archive,
201 # 'compressor' => [compressor command and arguments]
202 # (array reference, optional)
203 # 'disabled' => boolean (optional)}
205 'tgz' => {
206 'display' => 'tar.gz',
207 'type' => 'application/x-gzip',
208 'suffix' => '.tar.gz',
209 'format' => 'tar',
210 'compressor' => ['gzip', '-n']},
212 'tbz2' => {
213 'display' => 'tar.bz2',
214 'type' => 'application/x-bzip2',
215 'suffix' => '.tar.bz2',
216 'format' => 'tar',
217 'compressor' => ['bzip2']},
219 'txz' => {
220 'display' => 'tar.xz',
221 'type' => 'application/x-xz',
222 'suffix' => '.tar.xz',
223 'format' => 'tar',
224 'compressor' => ['xz'],
225 'disabled' => 1},
227 'zip' => {
228 'display' => 'zip',
229 'type' => 'application/x-zip',
230 'suffix' => '.zip',
231 'format' => 'zip'},
234 # Aliases so we understand old gitweb.snapshot values in repository
235 # configuration.
236 our %known_snapshot_format_aliases = (
237 'gzip' => 'tgz',
238 'bzip2' => 'tbz2',
239 'xz' => 'txz',
241 # backward compatibility: legacy gitweb config support
242 'x-gzip' => undef, 'gz' => undef,
243 'x-bzip2' => undef, 'bz2' => undef,
244 'x-zip' => undef, '' => undef,
247 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
248 # are changed, it may be appropriate to change these values too via
249 # $GITWEB_CONFIG.
250 our %avatar_size = (
251 'default' => 16,
252 'double' => 32
255 # Used to set the maximum load that we will still respond to gitweb queries.
256 # If server load exceed this value then return "503 server busy" error.
257 # If gitweb cannot determined server load, it is taken to be 0.
258 # Leave it undefined (or set to 'undef') to turn off load checking.
259 our $maxload = 300;
261 # configuration for 'highlight' (http://www.andre-simon.de/)
262 # match by basename
263 our %highlight_basename = (
264 #'Program' => 'py',
265 #'Library' => 'py',
266 'SConstruct' => 'py', # SCons equivalent of Makefile
267 'Makefile' => 'make',
269 # match by extension
270 our %highlight_ext = (
271 # main extensions, defining name of syntax;
272 # see files in /usr/share/highlight/langDefs/ directory
273 map { $_ => $_ }
274 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make),
275 # alternate extensions, see /etc/highlight/filetypes.conf
276 'h' => 'c',
277 map { $_ => 'sh' } qw(bash zsh ksh),
278 map { $_ => 'cpp' } qw(cxx c++ cc),
279 map { $_ => 'php' } qw(php3 php4 php5 phps),
280 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
281 map { $_ => 'make'} qw(mak mk),
282 map { $_ => 'xml' } qw(xhtml html htm),
285 # You define site-wide feature defaults here; override them with
286 # $GITWEB_CONFIG as necessary.
287 our %feature = (
288 # feature => {
289 # 'sub' => feature-sub (subroutine),
290 # 'override' => allow-override (boolean),
291 # 'default' => [ default options...] (array reference)}
293 # if feature is overridable (it means that allow-override has true value),
294 # then feature-sub will be called with default options as parameters;
295 # return value of feature-sub indicates if to enable specified feature
297 # if there is no 'sub' key (no feature-sub), then feature cannot be
298 # overridden
300 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
301 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
302 # is enabled
304 # Enable the 'blame' blob view, showing the last commit that modified
305 # each line in the file. This can be very CPU-intensive.
307 # To enable system wide have in $GITWEB_CONFIG
308 # $feature{'blame'}{'default'} = [1];
309 # To have project specific config enable override in $GITWEB_CONFIG
310 # $feature{'blame'}{'override'} = 1;
311 # and in project config gitweb.blame = 0|1;
312 'blame' => {
313 'sub' => sub { feature_bool('blame', @_) },
314 'override' => 0,
315 'default' => [0]},
317 # Enable the 'snapshot' link, providing a compressed archive of any
318 # tree. This can potentially generate high traffic if you have large
319 # project.
321 # Value is a list of formats defined in %known_snapshot_formats that
322 # you wish to offer.
323 # To disable system wide have in $GITWEB_CONFIG
324 # $feature{'snapshot'}{'default'} = [];
325 # To have project specific config enable override in $GITWEB_CONFIG
326 # $feature{'snapshot'}{'override'} = 1;
327 # and in project config, a comma-separated list of formats or "none"
328 # to disable. Example: gitweb.snapshot = tbz2,zip;
329 'snapshot' => {
330 'sub' => \&feature_snapshot,
331 'override' => 0,
332 'default' => ['tgz']},
334 # Enable text search, which will list the commits which match author,
335 # committer or commit text to a given string. Enabled by default.
336 # Project specific override is not supported.
338 # Note that this controls all search features, which means that if
339 # it is disabled, then 'grep' and 'pickaxe' search would also be
340 # disabled.
341 'search' => {
342 'override' => 0,
343 'default' => [1]},
345 # Enable grep search, which will list the files in currently selected
346 # tree containing the given string. Enabled by default. This can be
347 # potentially CPU-intensive, of course.
348 # Note that you need to have 'search' feature enabled too.
350 # To enable system wide have in $GITWEB_CONFIG
351 # $feature{'grep'}{'default'} = [1];
352 # To have project specific config enable override in $GITWEB_CONFIG
353 # $feature{'grep'}{'override'} = 1;
354 # and in project config gitweb.grep = 0|1;
355 'grep' => {
356 'sub' => sub { feature_bool('grep', @_) },
357 'override' => 0,
358 'default' => [1]},
360 # Enable the pickaxe search, which will list the commits that modified
361 # a given string in a file. This can be practical and quite faster
362 # alternative to 'blame', but still potentially CPU-intensive.
363 # Note that you need to have 'search' feature enabled too.
365 # To enable system wide have in $GITWEB_CONFIG
366 # $feature{'pickaxe'}{'default'} = [1];
367 # To have project specific config enable override in $GITWEB_CONFIG
368 # $feature{'pickaxe'}{'override'} = 1;
369 # and in project config gitweb.pickaxe = 0|1;
370 'pickaxe' => {
371 'sub' => sub { feature_bool('pickaxe', @_) },
372 'override' => 0,
373 'default' => [1]},
375 # Enable showing size of blobs in a 'tree' view, in a separate
376 # column, similar to what 'ls -l' does. This cost a bit of IO.
378 # To disable system wide have in $GITWEB_CONFIG
379 # $feature{'show-sizes'}{'default'} = [0];
380 # To have project specific config enable override in $GITWEB_CONFIG
381 # $feature{'show-sizes'}{'override'} = 1;
382 # and in project config gitweb.showsizes = 0|1;
383 'show-sizes' => {
384 'sub' => sub { feature_bool('showsizes', @_) },
385 'override' => 0,
386 'default' => [1]},
388 # Make gitweb use an alternative format of the URLs which can be
389 # more readable and natural-looking: project name is embedded
390 # directly in the path and the query string contains other
391 # auxiliary information. All gitweb installations recognize
392 # URL in either format; this configures in which formats gitweb
393 # generates links.
395 # To enable system wide have in $GITWEB_CONFIG
396 # $feature{'pathinfo'}{'default'} = [1];
397 # Project specific override is not supported.
399 # Note that you will need to change the default location of CSS,
400 # favicon, logo and possibly other files to an absolute URL. Also,
401 # if gitweb.cgi serves as your indexfile, you will need to force
402 # $my_uri to contain the script name in your $GITWEB_CONFIG.
403 'pathinfo' => {
404 'override' => 0,
405 'default' => [0]},
407 # Make gitweb consider projects in project root subdirectories
408 # to be forks of existing projects. Given project $projname.git,
409 # projects matching $projname/*.git will not be shown in the main
410 # projects list, instead a '+' mark will be added to $projname
411 # there and a 'forks' view will be enabled for the project, listing
412 # all the forks. If project list is taken from a file, forks have
413 # to be listed after the main project.
415 # To enable system wide have in $GITWEB_CONFIG
416 # $feature{'forks'}{'default'} = [1];
417 # Project specific override is not supported.
418 'forks' => {
419 'override' => 0,
420 'default' => [0]},
422 # Insert custom links to the action bar of all project pages.
423 # This enables you mainly to link to third-party scripts integrating
424 # into gitweb; e.g. git-browser for graphical history representation
425 # or custom web-based repository administration interface.
427 # The 'default' value consists of a list of triplets in the form
428 # (label, link, position) where position is the label after which
429 # to insert the link and link is a format string where %n expands
430 # to the project name, %f to the project path within the filesystem,
431 # %h to the current hash (h gitweb parameter) and %b to the current
432 # hash base (hb gitweb parameter); %% expands to %.
434 # To enable system wide have in $GITWEB_CONFIG e.g.
435 # $feature{'actions'}{'default'} = [('graphiclog',
436 # '/git-browser/by-commit.html?r=%n', 'summary')];
437 # Project specific override is not supported.
438 'actions' => {
439 'override' => 0,
440 'default' => []},
442 # Allow gitweb scan project content tags of project repository,
443 # and display the popular Web 2.0-ish "tag cloud" near the projects
444 # list. Note that this is something COMPLETELY different from the
445 # normal Git tags.
447 # gitweb by itself can show existing tags, but it does not handle
448 # tagging itself; you need to do it externally, outside gitweb.
449 # The format is described in git_get_project_ctags() subroutine.
450 # You may want to install the HTML::TagCloud Perl module to get
451 # a pretty tag cloud instead of just a list of tags.
453 # To enable system wide have in $GITWEB_CONFIG
454 # $feature{'ctags'}{'default'} = [1];
455 # Project specific override is not supported.
457 # In the future whether ctags editing is enabled might depend
458 # on the value, but using 1 should always mean no editing of ctags.
459 'ctags' => {
460 'override' => 0,
461 'default' => [0]},
463 # The maximum number of patches in a patchset generated in patch
464 # view. Set this to 0 or undef to disable patch view, or to a
465 # negative number to remove any limit.
467 # To disable system wide have in $GITWEB_CONFIG
468 # $feature{'patches'}{'default'} = [0];
469 # To have project specific config enable override in $GITWEB_CONFIG
470 # $feature{'patches'}{'override'} = 1;
471 # and in project config gitweb.patches = 0|n;
472 # where n is the maximum number of patches allowed in a patchset.
473 'patches' => {
474 'sub' => \&feature_patches,
475 'override' => 0,
476 'default' => [16]},
478 # Avatar support. When this feature is enabled, views such as
479 # shortlog or commit will display an avatar associated with
480 # the email of the committer(s) and/or author(s).
482 # Currently available providers are gravatar and picon.
483 # If an unknown provider is specified, the feature is disabled.
485 # Gravatar depends on Digest::MD5.
486 # Picon currently relies on the indiana.edu database.
488 # To enable system wide have in $GITWEB_CONFIG
489 # $feature{'avatar'}{'default'} = ['<provider>'];
490 # where <provider> is either gravatar or picon.
491 # To have project specific config enable override in $GITWEB_CONFIG
492 # $feature{'avatar'}{'override'} = 1;
493 # and in project config gitweb.avatar = <provider>;
494 'avatar' => {
495 'sub' => \&feature_avatar,
496 'override' => 0,
497 'default' => ['']},
499 # Enable displaying how much time and how many git commands
500 # it took to generate and display page. Disabled by default.
501 # Project specific override is not supported.
502 'timed' => {
503 'override' => 0,
504 'default' => [0]},
506 # Enable turning some links into links to actions which require
507 # JavaScript to run (like 'blame_incremental'). Not enabled by
508 # default. Project specific override is currently not supported.
509 'javascript-actions' => {
510 'override' => 0,
511 'default' => [0]},
513 # Enable and configure ability to change common timezone for dates
514 # in gitweb output via JavaScript. Enabled by default.
515 # Project specific override is not supported.
516 'javascript-timezone' => {
517 'override' => 0,
518 'default' => [
519 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
520 # or undef to turn off this feature
521 'gitweb_tz', # name of cookie where to store selected timezone
522 'datetime', # CSS class used to mark up dates for manipulation
525 # Syntax highlighting support. This is based on Daniel Svensson's
526 # and Sham Chukoury's work in gitweb-xmms2.git.
527 # It requires the 'highlight' program present in $PATH,
528 # and therefore is disabled by default.
530 # To enable system wide have in $GITWEB_CONFIG
531 # $feature{'highlight'}{'default'} = [1];
533 'highlight' => {
534 'sub' => sub { feature_bool('highlight', @_) },
535 'override' => 0,
536 'default' => [0]},
538 # Enable displaying of remote heads in the heads list
540 # To enable system wide have in $GITWEB_CONFIG
541 # $feature{'remote_heads'}{'default'} = [1];
542 # To have project specific config enable override in $GITWEB_CONFIG
543 # $feature{'remote_heads'}{'override'} = 1;
544 # and in project config gitweb.remote_heads = 0|1;
545 'remote_heads' => {
546 'sub' => sub { feature_bool('remote_heads', @_) },
547 'override' => 0,
548 'default' => [0]},
551 sub gitweb_get_feature {
552 my ($name) = @_;
553 return unless exists $feature{$name};
554 my ($sub, $override, @defaults) = (
555 $feature{$name}{'sub'},
556 $feature{$name}{'override'},
557 @{$feature{$name}{'default'}});
558 # project specific override is possible only if we have project
559 our $git_dir; # global variable, declared later
560 if (!$override || !defined $git_dir) {
561 return @defaults;
563 if (!defined $sub) {
564 warn "feature $name is not overridable";
565 return @defaults;
567 return $sub->(@defaults);
570 # A wrapper to check if a given feature is enabled.
571 # With this, you can say
573 # my $bool_feat = gitweb_check_feature('bool_feat');
574 # gitweb_check_feature('bool_feat') or somecode;
576 # instead of
578 # my ($bool_feat) = gitweb_get_feature('bool_feat');
579 # (gitweb_get_feature('bool_feat'))[0] or somecode;
581 sub gitweb_check_feature {
582 return (gitweb_get_feature(@_))[0];
586 sub feature_bool {
587 my $key = shift;
588 my ($val) = git_get_project_config($key, '--bool');
590 if (!defined $val) {
591 return ($_[0]);
592 } elsif ($val eq 'true') {
593 return (1);
594 } elsif ($val eq 'false') {
595 return (0);
599 sub feature_snapshot {
600 my (@fmts) = @_;
602 my ($val) = git_get_project_config('snapshot');
604 if ($val) {
605 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
608 return @fmts;
611 sub feature_patches {
612 my @val = (git_get_project_config('patches', '--int'));
614 if (@val) {
615 return @val;
618 return ($_[0]);
621 sub feature_avatar {
622 my @val = (git_get_project_config('avatar'));
624 return @val ? @val : @_;
627 # checking HEAD file with -e is fragile if the repository was
628 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
629 # and then pruned.
630 sub check_head_link {
631 my ($dir) = @_;
632 my $headfile = "$dir/HEAD";
633 return ((-e $headfile) ||
634 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
637 sub check_export_ok {
638 my ($dir) = @_;
639 return (check_head_link($dir) &&
640 (!$export_ok || -e "$dir/$export_ok") &&
641 (!$export_auth_hook || $export_auth_hook->($dir)));
644 # process alternate names for backward compatibility
645 # filter out unsupported (unknown) snapshot formats
646 sub filter_snapshot_fmts {
647 my @fmts = @_;
649 @fmts = map {
650 exists $known_snapshot_format_aliases{$_} ?
651 $known_snapshot_format_aliases{$_} : $_} @fmts;
652 @fmts = grep {
653 exists $known_snapshot_formats{$_} &&
654 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
657 # If it is set to code reference, it is code that it is to be run once per
658 # request, allowing updating configurations that change with each request,
659 # while running other code in config file only once.
661 # Otherwise, if it is false then gitweb would process config file only once;
662 # if it is true then gitweb config would be run for each request.
663 our $per_request_config = 1;
665 # read and parse gitweb config file given by its parameter.
666 # returns true on success, false on recoverable error, allowing
667 # to chain this subroutine, using first file that exists.
668 # dies on errors during parsing config file, as it is unrecoverable.
669 sub read_config_file {
670 my $filename = shift;
671 return unless defined $filename;
672 # die if there are errors parsing config file
673 if (-e $filename) {
674 do $filename;
675 die $@ if $@;
676 return 1;
678 return;
681 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
682 sub evaluate_gitweb_config {
683 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
684 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
685 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
687 # Protect agains duplications of file names, to not read config twice.
688 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
689 # there possibility of duplication of filename there doesn't matter.
690 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
691 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
693 # Common system-wide settings for convenience.
694 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
695 read_config_file($GITWEB_CONFIG_COMMON);
697 # Use first config file that exists. This means use the per-instance
698 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
699 read_config_file($GITWEB_CONFIG) and return;
700 read_config_file($GITWEB_CONFIG_SYSTEM);
703 # Get loadavg of system, to compare against $maxload.
704 # Currently it requires '/proc/loadavg' present to get loadavg;
705 # if it is not present it returns 0, which means no load checking.
706 sub get_loadavg {
707 if( -e '/proc/loadavg' ){
708 open my $fd, '<', '/proc/loadavg'
709 or return 0;
710 my @load = split(/\s+/, scalar <$fd>);
711 close $fd;
713 # The first three columns measure CPU and IO utilization of the last one,
714 # five, and 10 minute periods. The fourth column shows the number of
715 # currently running processes and the total number of processes in the m/n
716 # format. The last column displays the last process ID used.
717 return $load[0] || 0;
719 # additional checks for load average should go here for things that don't export
720 # /proc/loadavg
722 return 0;
725 # version of the core git binary
726 our $git_version;
727 sub evaluate_git_version {
728 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
729 $number_of_git_cmds++;
732 sub check_loadavg {
733 if (defined $maxload && get_loadavg() > $maxload) {
734 die_error(503, "The load average on the server is too high");
738 # ======================================================================
739 # input validation and dispatch
741 # input parameters can be collected from a variety of sources (presently, CGI
742 # and PATH_INFO), so we define an %input_params hash that collects them all
743 # together during validation: this allows subsequent uses (e.g. href()) to be
744 # agnostic of the parameter origin
746 our %input_params = ();
748 # input parameters are stored with the long parameter name as key. This will
749 # also be used in the href subroutine to convert parameters to their CGI
750 # equivalent, and since the href() usage is the most frequent one, we store
751 # the name -> CGI key mapping here, instead of the reverse.
753 # XXX: Warning: If you touch this, check the search form for updating,
754 # too.
756 our @cgi_param_mapping = (
757 project => "p",
758 action => "a",
759 file_name => "f",
760 file_parent => "fp",
761 hash => "h",
762 hash_parent => "hp",
763 hash_base => "hb",
764 hash_parent_base => "hpb",
765 page => "pg",
766 order => "o",
767 searchtext => "s",
768 searchtype => "st",
769 snapshot_format => "sf",
770 extra_options => "opt",
771 search_use_regexp => "sr",
772 ctag => "by_tag",
773 diff_style => "ds",
774 project_filter => "pf",
775 # this must be last entry (for manipulation from JavaScript)
776 javascript => "js"
778 our %cgi_param_mapping = @cgi_param_mapping;
780 # we will also need to know the possible actions, for validation
781 our %actions = (
782 "blame" => \&git_blame,
783 "blame_incremental" => \&git_blame_incremental,
784 "blame_data" => \&git_blame_data,
785 "blobdiff" => \&git_blobdiff,
786 "blobdiff_plain" => \&git_blobdiff_plain,
787 "blob" => \&git_blob,
788 "blob_plain" => \&git_blob_plain,
789 "commitdiff" => \&git_commitdiff,
790 "commitdiff_plain" => \&git_commitdiff_plain,
791 "commit" => \&git_commit,
792 "forks" => \&git_forks,
793 "heads" => \&git_heads,
794 "history" => \&git_history,
795 "log" => \&git_log,
796 "patch" => \&git_patch,
797 "patches" => \&git_patches,
798 "remotes" => \&git_remotes,
799 "rss" => \&git_rss,
800 "atom" => \&git_atom,
801 "search" => \&git_search,
802 "search_help" => \&git_search_help,
803 "shortlog" => \&git_shortlog,
804 "summary" => \&git_summary,
805 "tag" => \&git_tag,
806 "tags" => \&git_tags,
807 "tree" => \&git_tree,
808 "snapshot" => \&git_snapshot,
809 "object" => \&git_object,
810 # those below don't need $project
811 "opml" => \&git_opml,
812 "project_list" => \&git_project_list,
813 "project_index" => \&git_project_index,
816 # finally, we have the hash of allowed extra_options for the commands that
817 # allow them
818 our %allowed_options = (
819 "--no-merges" => [ qw(rss atom log shortlog history) ],
822 # fill %input_params with the CGI parameters. All values except for 'opt'
823 # should be single values, but opt can be an array. We should probably
824 # build an array of parameters that can be multi-valued, but since for the time
825 # being it's only this one, we just single it out
826 sub evaluate_query_params {
827 our $cgi;
829 while (my ($name, $symbol) = each %cgi_param_mapping) {
830 if ($symbol eq 'opt') {
831 $input_params{$name} = [ map { decode_utf8($_) } $cgi->param($symbol) ];
832 } else {
833 $input_params{$name} = decode_utf8($cgi->param($symbol));
838 # now read PATH_INFO and update the parameter list for missing parameters
839 sub evaluate_path_info {
840 return if defined $input_params{'project'};
841 return if !$path_info;
842 $path_info =~ s,^/+,,;
843 return if !$path_info;
845 # find which part of PATH_INFO is project
846 my $project = $path_info;
847 $project =~ s,/+$,,;
848 while ($project && !check_head_link("$projectroot/$project")) {
849 $project =~ s,/*[^/]*$,,;
851 return unless $project;
852 $input_params{'project'} = $project;
854 # do not change any parameters if an action is given using the query string
855 return if $input_params{'action'};
856 $path_info =~ s,^\Q$project\E/*,,;
858 # next, check if we have an action
859 my $action = $path_info;
860 $action =~ s,/.*$,,;
861 if (exists $actions{$action}) {
862 $path_info =~ s,^$action/*,,;
863 $input_params{'action'} = $action;
866 # list of actions that want hash_base instead of hash, but can have no
867 # pathname (f) parameter
868 my @wants_base = (
869 'tree',
870 'history',
873 # we want to catch, among others
874 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
875 my ($parentrefname, $parentpathname, $refname, $pathname) =
876 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
878 # first, analyze the 'current' part
879 if (defined $pathname) {
880 # we got "branch:filename" or "branch:dir/"
881 # we could use git_get_type(branch:pathname), but:
882 # - it needs $git_dir
883 # - it does a git() call
884 # - the convention of terminating directories with a slash
885 # makes it superfluous
886 # - embedding the action in the PATH_INFO would make it even
887 # more superfluous
888 $pathname =~ s,^/+,,;
889 if (!$pathname || substr($pathname, -1) eq "/") {
890 $input_params{'action'} ||= "tree";
891 $pathname =~ s,/$,,;
892 } else {
893 # the default action depends on whether we had parent info
894 # or not
895 if ($parentrefname) {
896 $input_params{'action'} ||= "blobdiff_plain";
897 } else {
898 $input_params{'action'} ||= "blob_plain";
901 $input_params{'hash_base'} ||= $refname;
902 $input_params{'file_name'} ||= $pathname;
903 } elsif (defined $refname) {
904 # we got "branch". In this case we have to choose if we have to
905 # set hash or hash_base.
907 # Most of the actions without a pathname only want hash to be
908 # set, except for the ones specified in @wants_base that want
909 # hash_base instead. It should also be noted that hand-crafted
910 # links having 'history' as an action and no pathname or hash
911 # set will fail, but that happens regardless of PATH_INFO.
912 if (defined $parentrefname) {
913 # if there is parent let the default be 'shortlog' action
914 # (for http://git.example.com/repo.git/A..B links); if there
915 # is no parent, dispatch will detect type of object and set
916 # action appropriately if required (if action is not set)
917 $input_params{'action'} ||= "shortlog";
919 if ($input_params{'action'} &&
920 grep { $_ eq $input_params{'action'} } @wants_base) {
921 $input_params{'hash_base'} ||= $refname;
922 } else {
923 $input_params{'hash'} ||= $refname;
927 # next, handle the 'parent' part, if present
928 if (defined $parentrefname) {
929 # a missing pathspec defaults to the 'current' filename, allowing e.g.
930 # someproject/blobdiff/oldrev..newrev:/filename
931 if ($parentpathname) {
932 $parentpathname =~ s,^/+,,;
933 $parentpathname =~ s,/$,,;
934 $input_params{'file_parent'} ||= $parentpathname;
935 } else {
936 $input_params{'file_parent'} ||= $input_params{'file_name'};
938 # we assume that hash_parent_base is wanted if a path was specified,
939 # or if the action wants hash_base instead of hash
940 if (defined $input_params{'file_parent'} ||
941 grep { $_ eq $input_params{'action'} } @wants_base) {
942 $input_params{'hash_parent_base'} ||= $parentrefname;
943 } else {
944 $input_params{'hash_parent'} ||= $parentrefname;
948 # for the snapshot action, we allow URLs in the form
949 # $project/snapshot/$hash.ext
950 # where .ext determines the snapshot and gets removed from the
951 # passed $refname to provide the $hash.
953 # To be able to tell that $refname includes the format extension, we
954 # require the following two conditions to be satisfied:
955 # - the hash input parameter MUST have been set from the $refname part
956 # of the URL (i.e. they must be equal)
957 # - the snapshot format MUST NOT have been defined already (e.g. from
958 # CGI parameter sf)
959 # It's also useless to try any matching unless $refname has a dot,
960 # so we check for that too
961 if (defined $input_params{'action'} &&
962 $input_params{'action'} eq 'snapshot' &&
963 defined $refname && index($refname, '.') != -1 &&
964 $refname eq $input_params{'hash'} &&
965 !defined $input_params{'snapshot_format'}) {
966 # We loop over the known snapshot formats, checking for
967 # extensions. Allowed extensions are both the defined suffix
968 # (which includes the initial dot already) and the snapshot
969 # format key itself, with a prepended dot
970 while (my ($fmt, $opt) = each %known_snapshot_formats) {
971 my $hash = $refname;
972 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
973 next;
975 my $sfx = $1;
976 # a valid suffix was found, so set the snapshot format
977 # and reset the hash parameter
978 $input_params{'snapshot_format'} = $fmt;
979 $input_params{'hash'} = $hash;
980 # we also set the format suffix to the one requested
981 # in the URL: this way a request for e.g. .tgz returns
982 # a .tgz instead of a .tar.gz
983 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
984 last;
989 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
990 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
991 $searchtext, $search_regexp, $project_filter);
992 sub evaluate_and_validate_params {
993 our $action = $input_params{'action'};
994 if (defined $action) {
995 if (!validate_action($action)) {
996 die_error(400, "Invalid action parameter");
1000 # parameters which are pathnames
1001 our $project = $input_params{'project'};
1002 if (defined $project) {
1003 if (!validate_project($project)) {
1004 undef $project;
1005 die_error(404, "No such project");
1009 our $project_filter = $input_params{'project_filter'};
1010 if (defined $project_filter) {
1011 if (!validate_pathname($project_filter)) {
1012 die_error(404, "Invalid project_filter parameter");
1016 our $file_name = $input_params{'file_name'};
1017 if (defined $file_name) {
1018 if (!validate_pathname($file_name)) {
1019 die_error(400, "Invalid file parameter");
1023 our $file_parent = $input_params{'file_parent'};
1024 if (defined $file_parent) {
1025 if (!validate_pathname($file_parent)) {
1026 die_error(400, "Invalid file parent parameter");
1030 # parameters which are refnames
1031 our $hash = $input_params{'hash'};
1032 if (defined $hash) {
1033 if (!validate_refname($hash)) {
1034 die_error(400, "Invalid hash parameter");
1038 our $hash_parent = $input_params{'hash_parent'};
1039 if (defined $hash_parent) {
1040 if (!validate_refname($hash_parent)) {
1041 die_error(400, "Invalid hash parent parameter");
1045 our $hash_base = $input_params{'hash_base'};
1046 if (defined $hash_base) {
1047 if (!validate_refname($hash_base)) {
1048 die_error(400, "Invalid hash base parameter");
1052 our @extra_options = @{$input_params{'extra_options'}};
1053 # @extra_options is always defined, since it can only be (currently) set from
1054 # CGI, and $cgi->param() returns the empty array in array context if the param
1055 # is not set
1056 foreach my $opt (@extra_options) {
1057 if (not exists $allowed_options{$opt}) {
1058 die_error(400, "Invalid option parameter");
1060 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1061 die_error(400, "Invalid option parameter for this action");
1065 our $hash_parent_base = $input_params{'hash_parent_base'};
1066 if (defined $hash_parent_base) {
1067 if (!validate_refname($hash_parent_base)) {
1068 die_error(400, "Invalid hash parent base parameter");
1072 # other parameters
1073 our $page = $input_params{'page'};
1074 if (defined $page) {
1075 if ($page =~ m/[^0-9]/) {
1076 die_error(400, "Invalid page parameter");
1080 our $searchtype = $input_params{'searchtype'};
1081 if (defined $searchtype) {
1082 if ($searchtype =~ m/[^a-z]/) {
1083 die_error(400, "Invalid searchtype parameter");
1087 our $search_use_regexp = $input_params{'search_use_regexp'};
1089 our $searchtext = $input_params{'searchtext'};
1090 our $search_regexp;
1091 if (defined $searchtext) {
1092 if (length($searchtext) < 2) {
1093 die_error(403, "At least two characters are required for search parameter");
1095 if ($search_use_regexp) {
1096 $search_regexp = $searchtext;
1097 if (!eval { qr/$search_regexp/; 1; }) {
1098 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1099 die_error(400, "Invalid search regexp '$search_regexp'",
1100 esc_html($error));
1102 } else {
1103 $search_regexp = quotemeta $searchtext;
1108 # path to the current git repository
1109 our $git_dir;
1110 sub evaluate_git_dir {
1111 our $git_dir = "$projectroot/$project" if $project;
1114 our (@snapshot_fmts, $git_avatar);
1115 sub configure_gitweb_features {
1116 # list of supported snapshot formats
1117 our @snapshot_fmts = gitweb_get_feature('snapshot');
1118 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1120 # check that the avatar feature is set to a known provider name,
1121 # and for each provider check if the dependencies are satisfied.
1122 # if the provider name is invalid or the dependencies are not met,
1123 # reset $git_avatar to the empty string.
1124 our ($git_avatar) = gitweb_get_feature('avatar');
1125 if ($git_avatar eq 'gravatar') {
1126 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1127 } elsif ($git_avatar eq 'picon') {
1128 # no dependencies
1129 } else {
1130 $git_avatar = '';
1134 # custom error handler: 'die <message>' is Internal Server Error
1135 sub handle_errors_html {
1136 my $msg = shift; # it is already HTML escaped
1138 # to avoid infinite loop where error occurs in die_error,
1139 # change handler to default handler, disabling handle_errors_html
1140 set_message("Error occured when inside die_error:\n$msg");
1142 # you cannot jump out of die_error when called as error handler;
1143 # the subroutine set via CGI::Carp::set_message is called _after_
1144 # HTTP headers are already written, so it cannot write them itself
1145 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1147 set_message(\&handle_errors_html);
1149 # dispatch
1150 sub dispatch {
1151 if (!defined $action) {
1152 if (defined $hash) {
1153 $action = git_get_type($hash);
1154 $action or die_error(404, "Object does not exist");
1155 } elsif (defined $hash_base && defined $file_name) {
1156 $action = git_get_type("$hash_base:$file_name");
1157 $action or die_error(404, "File or directory does not exist");
1158 } elsif (defined $project) {
1159 $action = 'summary';
1160 } else {
1161 $action = 'project_list';
1164 if (!defined($actions{$action})) {
1165 die_error(400, "Unknown action");
1167 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1168 !$project) {
1169 die_error(400, "Project needed");
1171 $actions{$action}->();
1174 sub reset_timer {
1175 our $t0 = [ gettimeofday() ]
1176 if defined $t0;
1177 our $number_of_git_cmds = 0;
1180 our $first_request = 1;
1181 sub run_request {
1182 reset_timer();
1184 evaluate_uri();
1185 if ($first_request) {
1186 evaluate_gitweb_config();
1187 evaluate_git_version();
1189 if ($per_request_config) {
1190 if (ref($per_request_config) eq 'CODE') {
1191 $per_request_config->();
1192 } elsif (!$first_request) {
1193 evaluate_gitweb_config();
1196 check_loadavg();
1198 # $projectroot and $projects_list might be set in gitweb config file
1199 $projects_list ||= $projectroot;
1201 evaluate_query_params();
1202 evaluate_path_info();
1203 evaluate_and_validate_params();
1204 evaluate_git_dir();
1206 configure_gitweb_features();
1208 dispatch();
1211 our $is_last_request = sub { 1 };
1212 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1213 our $CGI = 'CGI';
1214 our $cgi;
1215 sub configure_as_fcgi {
1216 require CGI::Fast;
1217 our $CGI = 'CGI::Fast';
1219 my $request_number = 0;
1220 # let each child service 100 requests
1221 our $is_last_request = sub { ++$request_number > 100 };
1223 sub evaluate_argv {
1224 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1225 configure_as_fcgi()
1226 if $script_name =~ /\.fcgi$/;
1228 return unless (@ARGV);
1230 require Getopt::Long;
1231 Getopt::Long::GetOptions(
1232 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1233 'nproc|n=i' => sub {
1234 my ($arg, $val) = @_;
1235 return unless eval { require FCGI::ProcManager; 1; };
1236 my $proc_manager = FCGI::ProcManager->new({
1237 n_processes => $val,
1239 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1240 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1241 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1246 sub run {
1247 evaluate_argv();
1249 $first_request = 1;
1250 $pre_listen_hook->()
1251 if $pre_listen_hook;
1253 REQUEST:
1254 while ($cgi = $CGI->new()) {
1255 $pre_dispatch_hook->()
1256 if $pre_dispatch_hook;
1258 run_request();
1260 $post_dispatch_hook->()
1261 if $post_dispatch_hook;
1262 $first_request = 0;
1264 last REQUEST if ($is_last_request->());
1267 DONE_GITWEB:
1271 run();
1273 if (defined caller) {
1274 # wrapped in a subroutine processing requests,
1275 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1276 return;
1277 } else {
1278 # pure CGI script, serving single request
1279 exit;
1282 ## ======================================================================
1283 ## action links
1285 # possible values of extra options
1286 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1287 # -replay => 1 - start from a current view (replay with modifications)
1288 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1289 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1290 sub href {
1291 my %params = @_;
1292 # default is to use -absolute url() i.e. $my_uri
1293 my $href = $params{-full} ? $my_url : $my_uri;
1295 # implicit -replay, must be first of implicit params
1296 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1298 $params{'project'} = $project unless exists $params{'project'};
1300 if ($params{-replay}) {
1301 while (my ($name, $symbol) = each %cgi_param_mapping) {
1302 if (!exists $params{$name}) {
1303 $params{$name} = $input_params{$name};
1308 my $use_pathinfo = gitweb_check_feature('pathinfo');
1309 if (defined $params{'project'} &&
1310 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1311 # try to put as many parameters as possible in PATH_INFO:
1312 # - project name
1313 # - action
1314 # - hash_parent or hash_parent_base:/file_parent
1315 # - hash or hash_base:/filename
1316 # - the snapshot_format as an appropriate suffix
1318 # When the script is the root DirectoryIndex for the domain,
1319 # $href here would be something like http://gitweb.example.com/
1320 # Thus, we strip any trailing / from $href, to spare us double
1321 # slashes in the final URL
1322 $href =~ s,/$,,;
1324 # Then add the project name, if present
1325 $href .= "/".esc_path_info($params{'project'});
1326 delete $params{'project'};
1328 # since we destructively absorb parameters, we keep this
1329 # boolean that remembers if we're handling a snapshot
1330 my $is_snapshot = $params{'action'} eq 'snapshot';
1332 # Summary just uses the project path URL, any other action is
1333 # added to the URL
1334 if (defined $params{'action'}) {
1335 $href .= "/".esc_path_info($params{'action'})
1336 unless $params{'action'} eq 'summary';
1337 delete $params{'action'};
1340 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1341 # stripping nonexistent or useless pieces
1342 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1343 || $params{'hash_parent'} || $params{'hash'});
1344 if (defined $params{'hash_base'}) {
1345 if (defined $params{'hash_parent_base'}) {
1346 $href .= esc_path_info($params{'hash_parent_base'});
1347 # skip the file_parent if it's the same as the file_name
1348 if (defined $params{'file_parent'}) {
1349 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1350 delete $params{'file_parent'};
1351 } elsif ($params{'file_parent'} !~ /\.\./) {
1352 $href .= ":/".esc_path_info($params{'file_parent'});
1353 delete $params{'file_parent'};
1356 $href .= "..";
1357 delete $params{'hash_parent'};
1358 delete $params{'hash_parent_base'};
1359 } elsif (defined $params{'hash_parent'}) {
1360 $href .= esc_path_info($params{'hash_parent'}). "..";
1361 delete $params{'hash_parent'};
1364 $href .= esc_path_info($params{'hash_base'});
1365 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1366 $href .= ":/".esc_path_info($params{'file_name'});
1367 delete $params{'file_name'};
1369 delete $params{'hash'};
1370 delete $params{'hash_base'};
1371 } elsif (defined $params{'hash'}) {
1372 $href .= esc_path_info($params{'hash'});
1373 delete $params{'hash'};
1376 # If the action was a snapshot, we can absorb the
1377 # snapshot_format parameter too
1378 if ($is_snapshot) {
1379 my $fmt = $params{'snapshot_format'};
1380 # snapshot_format should always be defined when href()
1381 # is called, but just in case some code forgets, we
1382 # fall back to the default
1383 $fmt ||= $snapshot_fmts[0];
1384 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1385 delete $params{'snapshot_format'};
1389 # now encode the parameters explicitly
1390 my @result = ();
1391 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1392 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1393 if (defined $params{$name}) {
1394 if (ref($params{$name}) eq "ARRAY") {
1395 foreach my $par (@{$params{$name}}) {
1396 push @result, $symbol . "=" . esc_param($par);
1398 } else {
1399 push @result, $symbol . "=" . esc_param($params{$name});
1403 $href .= "?" . join(';', @result) if scalar @result;
1405 # final transformation: trailing spaces must be escaped (URI-encoded)
1406 $href =~ s/(\s+)$/CGI::escape($1)/e;
1408 if ($params{-anchor}) {
1409 $href .= "#".esc_param($params{-anchor});
1412 return $href;
1416 ## ======================================================================
1417 ## validation, quoting/unquoting and escaping
1419 sub validate_action {
1420 my $input = shift || return undef;
1421 return undef unless exists $actions{$input};
1422 return $input;
1425 sub validate_project {
1426 my $input = shift || return undef;
1427 if (!validate_pathname($input) ||
1428 !(-d "$projectroot/$input") ||
1429 !check_export_ok("$projectroot/$input") ||
1430 ($strict_export && !project_in_list($input))) {
1431 return undef;
1432 } else {
1433 return $input;
1437 sub validate_pathname {
1438 my $input = shift || return undef;
1440 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1441 # at the beginning, at the end, and between slashes.
1442 # also this catches doubled slashes
1443 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1444 return undef;
1446 # no null characters
1447 if ($input =~ m!\0!) {
1448 return undef;
1450 return $input;
1453 sub validate_refname {
1454 my $input = shift || return undef;
1456 # textual hashes are O.K.
1457 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1458 return $input;
1460 # it must be correct pathname
1461 $input = validate_pathname($input)
1462 or return undef;
1463 # restrictions on ref name according to git-check-ref-format
1464 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1465 return undef;
1467 return $input;
1470 # decode sequences of octets in utf8 into Perl's internal form,
1471 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1472 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1473 sub to_utf8 {
1474 my $str = shift;
1475 return undef unless defined $str;
1477 if (utf8::is_utf8($str) || utf8::decode($str)) {
1478 return $str;
1479 } else {
1480 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1484 # quote unsafe chars, but keep the slash, even when it's not
1485 # correct, but quoted slashes look too horrible in bookmarks
1486 sub esc_param {
1487 my $str = shift;
1488 return undef unless defined $str;
1489 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1490 $str =~ s/ /\+/g;
1491 return $str;
1494 # the quoting rules for path_info fragment are slightly different
1495 sub esc_path_info {
1496 my $str = shift;
1497 return undef unless defined $str;
1499 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1500 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1502 return $str;
1505 # quote unsafe chars in whole URL, so some characters cannot be quoted
1506 sub esc_url {
1507 my $str = shift;
1508 return undef unless defined $str;
1509 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1510 $str =~ s/ /\+/g;
1511 return $str;
1514 # quote unsafe characters in HTML attributes
1515 sub esc_attr {
1517 # for XHTML conformance escaping '"' to '&quot;' is not enough
1518 return esc_html(@_);
1521 # replace invalid utf8 character with SUBSTITUTION sequence
1522 sub esc_html {
1523 my $str = shift;
1524 my %opts = @_;
1526 return undef unless defined $str;
1528 $str = to_utf8($str);
1529 $str = $cgi->escapeHTML($str);
1530 if ($opts{'-nbsp'}) {
1531 $str =~ s/ /&nbsp;/g;
1533 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1534 return $str;
1537 # quote control characters and escape filename to HTML
1538 sub esc_path {
1539 my $str = shift;
1540 my %opts = @_;
1542 return undef unless defined $str;
1544 $str = to_utf8($str);
1545 $str = $cgi->escapeHTML($str);
1546 if ($opts{'-nbsp'}) {
1547 $str =~ s/ /&nbsp;/g;
1549 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1550 return $str;
1553 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1554 sub sanitize {
1555 my $str = shift;
1557 return undef unless defined $str;
1559 $str = to_utf8($str);
1560 $str =~ s|([[:cntrl:]])|($1 =~ /[\t\n\r]/ ? $1 : quot_cec($1))|eg;
1561 return $str;
1564 # Make control characters "printable", using character escape codes (CEC)
1565 sub quot_cec {
1566 my $cntrl = shift;
1567 my %opts = @_;
1568 my %es = ( # character escape codes, aka escape sequences
1569 "\t" => '\t', # tab (HT)
1570 "\n" => '\n', # line feed (LF)
1571 "\r" => '\r', # carrige return (CR)
1572 "\f" => '\f', # form feed (FF)
1573 "\b" => '\b', # backspace (BS)
1574 "\a" => '\a', # alarm (bell) (BEL)
1575 "\e" => '\e', # escape (ESC)
1576 "\013" => '\v', # vertical tab (VT)
1577 "\000" => '\0', # nul character (NUL)
1579 my $chr = ( (exists $es{$cntrl})
1580 ? $es{$cntrl}
1581 : sprintf('\%2x', ord($cntrl)) );
1582 if ($opts{-nohtml}) {
1583 return $chr;
1584 } else {
1585 return "<span class=\"cntrl\">$chr</span>";
1589 # Alternatively use unicode control pictures codepoints,
1590 # Unicode "printable representation" (PR)
1591 sub quot_upr {
1592 my $cntrl = shift;
1593 my %opts = @_;
1595 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1596 if ($opts{-nohtml}) {
1597 return $chr;
1598 } else {
1599 return "<span class=\"cntrl\">$chr</span>";
1603 # git may return quoted and escaped filenames
1604 sub unquote {
1605 my $str = shift;
1607 sub unq {
1608 my $seq = shift;
1609 my %es = ( # character escape codes, aka escape sequences
1610 't' => "\t", # tab (HT, TAB)
1611 'n' => "\n", # newline (NL)
1612 'r' => "\r", # return (CR)
1613 'f' => "\f", # form feed (FF)
1614 'b' => "\b", # backspace (BS)
1615 'a' => "\a", # alarm (bell) (BEL)
1616 'e' => "\e", # escape (ESC)
1617 'v' => "\013", # vertical tab (VT)
1620 if ($seq =~ m/^[0-7]{1,3}$/) {
1621 # octal char sequence
1622 return chr(oct($seq));
1623 } elsif (exists $es{$seq}) {
1624 # C escape sequence, aka character escape code
1625 return $es{$seq};
1627 # quoted ordinary character
1628 return $seq;
1631 if ($str =~ m/^"(.*)"$/) {
1632 # needs unquoting
1633 $str = $1;
1634 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1636 return $str;
1639 # escape tabs (convert tabs to spaces)
1640 sub untabify {
1641 my $line = shift;
1643 while ((my $pos = index($line, "\t")) != -1) {
1644 if (my $count = (8 - ($pos % 8))) {
1645 my $spaces = ' ' x $count;
1646 $line =~ s/\t/$spaces/;
1650 return $line;
1653 sub project_in_list {
1654 my $project = shift;
1655 my @list = git_get_projects_list();
1656 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1659 ## ----------------------------------------------------------------------
1660 ## HTML aware string manipulation
1662 # Try to chop given string on a word boundary between position
1663 # $len and $len+$add_len. If there is no word boundary there,
1664 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1665 # (marking chopped part) would be longer than given string.
1666 sub chop_str {
1667 my $str = shift;
1668 my $len = shift;
1669 my $add_len = shift || 10;
1670 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1672 # Make sure perl knows it is utf8 encoded so we don't
1673 # cut in the middle of a utf8 multibyte char.
1674 $str = to_utf8($str);
1676 # allow only $len chars, but don't cut a word if it would fit in $add_len
1677 # if it doesn't fit, cut it if it's still longer than the dots we would add
1678 # remove chopped character entities entirely
1680 # when chopping in the middle, distribute $len into left and right part
1681 # return early if chopping wouldn't make string shorter
1682 if ($where eq 'center') {
1683 return $str if ($len + 5 >= length($str)); # filler is length 5
1684 $len = int($len/2);
1685 } else {
1686 return $str if ($len + 4 >= length($str)); # filler is length 4
1689 # regexps: ending and beginning with word part up to $add_len
1690 my $endre = qr/.{$len}\w{0,$add_len}/;
1691 my $begre = qr/\w{0,$add_len}.{$len}/;
1693 if ($where eq 'left') {
1694 $str =~ m/^(.*?)($begre)$/;
1695 my ($lead, $body) = ($1, $2);
1696 if (length($lead) > 4) {
1697 $lead = " ...";
1699 return "$lead$body";
1701 } elsif ($where eq 'center') {
1702 $str =~ m/^($endre)(.*)$/;
1703 my ($left, $str) = ($1, $2);
1704 $str =~ m/^(.*?)($begre)$/;
1705 my ($mid, $right) = ($1, $2);
1706 if (length($mid) > 5) {
1707 $mid = " ... ";
1709 return "$left$mid$right";
1711 } else {
1712 $str =~ m/^($endre)(.*)$/;
1713 my $body = $1;
1714 my $tail = $2;
1715 if (length($tail) > 4) {
1716 $tail = "... ";
1718 return "$body$tail";
1722 # takes the same arguments as chop_str, but also wraps a <span> around the
1723 # result with a title attribute if it does get chopped. Additionally, the
1724 # string is HTML-escaped.
1725 sub chop_and_escape_str {
1726 my ($str) = @_;
1728 my $chopped = chop_str(@_);
1729 $str = to_utf8($str);
1730 if ($chopped eq $str) {
1731 return esc_html($chopped);
1732 } else {
1733 $str =~ s/[[:cntrl:]]/?/g;
1734 return $cgi->span({-title=>$str}, esc_html($chopped));
1738 # Highlight selected fragments of string, using given CSS class,
1739 # and escape HTML. It is assumed that fragments do not overlap.
1740 # Regions are passed as list of pairs (array references).
1742 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1743 # '<span class="mark">foo</span>bar'
1744 sub esc_html_hl_regions {
1745 my ($str, $css_class, @sel) = @_;
1746 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1747 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1748 return esc_html($str, %opts) unless @sel;
1750 my $out = '';
1751 my $pos = 0;
1753 for my $s (@sel) {
1754 my ($begin, $end) = @$s;
1756 # Don't create empty <span> elements.
1757 next if $end <= $begin;
1759 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1760 %opts);
1762 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1763 if ($begin - $pos > 0);
1764 $out .= $cgi->span({-class => $css_class}, $escaped);
1766 $pos = $end;
1768 $out .= esc_html(substr($str, $pos), %opts)
1769 if ($pos < length($str));
1771 return $out;
1774 # return positions of beginning and end of each match
1775 sub matchpos_list {
1776 my ($str, $regexp) = @_;
1777 return unless (defined $str && defined $regexp);
1779 my @matches;
1780 while ($str =~ /$regexp/g) {
1781 push @matches, [$-[0], $+[0]];
1783 return @matches;
1786 # highlight match (if any), and escape HTML
1787 sub esc_html_match_hl {
1788 my ($str, $regexp) = @_;
1789 return esc_html($str) unless defined $regexp;
1791 my @matches = matchpos_list($str, $regexp);
1792 return esc_html($str) unless @matches;
1794 return esc_html_hl_regions($str, 'match', @matches);
1798 # highlight match (if any) of shortened string, and escape HTML
1799 sub esc_html_match_hl_chopped {
1800 my ($str, $chopped, $regexp) = @_;
1801 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1803 my @matches = matchpos_list($str, $regexp);
1804 return esc_html($chopped) unless @matches;
1806 # filter matches so that we mark chopped string
1807 my $tail = "... "; # see chop_str
1808 unless ($chopped =~ s/\Q$tail\E$//) {
1809 $tail = '';
1811 my $chop_len = length($chopped);
1812 my $tail_len = length($tail);
1813 my @filtered;
1815 for my $m (@matches) {
1816 if ($m->[0] > $chop_len) {
1817 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1818 last;
1819 } elsif ($m->[1] > $chop_len) {
1820 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1821 last;
1823 push @filtered, $m;
1826 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1829 ## ----------------------------------------------------------------------
1830 ## functions returning short strings
1832 # CSS class for given age value (in seconds)
1833 sub age_class {
1834 my $age = shift;
1836 if (!defined $age) {
1837 return "noage";
1838 } elsif ($age < 60*60*2) {
1839 return "age0";
1840 } elsif ($age < 60*60*24*2) {
1841 return "age1";
1842 } else {
1843 return "age2";
1847 # convert age in seconds to "nn units ago" string
1848 sub age_string {
1849 my $age = shift;
1850 my $age_str;
1852 if ($age > 60*60*24*365*2) {
1853 $age_str = (int $age/60/60/24/365);
1854 $age_str .= " years ago";
1855 } elsif ($age > 60*60*24*(365/12)*2) {
1856 $age_str = int $age/60/60/24/(365/12);
1857 $age_str .= " months ago";
1858 } elsif ($age > 60*60*24*7*2) {
1859 $age_str = int $age/60/60/24/7;
1860 $age_str .= " weeks ago";
1861 } elsif ($age > 60*60*24*2) {
1862 $age_str = int $age/60/60/24;
1863 $age_str .= " days ago";
1864 } elsif ($age > 60*60*2) {
1865 $age_str = int $age/60/60;
1866 $age_str .= " hours ago";
1867 } elsif ($age > 60*2) {
1868 $age_str = int $age/60;
1869 $age_str .= " min ago";
1870 } elsif ($age > 2) {
1871 $age_str = int $age;
1872 $age_str .= " sec ago";
1873 } else {
1874 $age_str .= " right now";
1876 return $age_str;
1879 use constant {
1880 S_IFINVALID => 0030000,
1881 S_IFGITLINK => 0160000,
1884 # submodule/subproject, a commit object reference
1885 sub S_ISGITLINK {
1886 my $mode = shift;
1888 return (($mode & S_IFMT) == S_IFGITLINK)
1891 # convert file mode in octal to symbolic file mode string
1892 sub mode_str {
1893 my $mode = oct shift;
1895 if (S_ISGITLINK($mode)) {
1896 return 'm---------';
1897 } elsif (S_ISDIR($mode & S_IFMT)) {
1898 return 'drwxr-xr-x';
1899 } elsif (S_ISLNK($mode)) {
1900 return 'lrwxrwxrwx';
1901 } elsif (S_ISREG($mode)) {
1902 # git cares only about the executable bit
1903 if ($mode & S_IXUSR) {
1904 return '-rwxr-xr-x';
1905 } else {
1906 return '-rw-r--r--';
1908 } else {
1909 return '----------';
1913 # convert file mode in octal to file type string
1914 sub file_type {
1915 my $mode = shift;
1917 if ($mode !~ m/^[0-7]+$/) {
1918 return $mode;
1919 } else {
1920 $mode = oct $mode;
1923 if (S_ISGITLINK($mode)) {
1924 return "submodule";
1925 } elsif (S_ISDIR($mode & S_IFMT)) {
1926 return "directory";
1927 } elsif (S_ISLNK($mode)) {
1928 return "symlink";
1929 } elsif (S_ISREG($mode)) {
1930 return "file";
1931 } else {
1932 return "unknown";
1936 # convert file mode in octal to file type description string
1937 sub file_type_long {
1938 my $mode = shift;
1940 if ($mode !~ m/^[0-7]+$/) {
1941 return $mode;
1942 } else {
1943 $mode = oct $mode;
1946 if (S_ISGITLINK($mode)) {
1947 return "submodule";
1948 } elsif (S_ISDIR($mode & S_IFMT)) {
1949 return "directory";
1950 } elsif (S_ISLNK($mode)) {
1951 return "symlink";
1952 } elsif (S_ISREG($mode)) {
1953 if ($mode & S_IXUSR) {
1954 return "executable";
1955 } else {
1956 return "file";
1958 } else {
1959 return "unknown";
1964 ## ----------------------------------------------------------------------
1965 ## functions returning short HTML fragments, or transforming HTML fragments
1966 ## which don't belong to other sections
1968 # format line of commit message.
1969 sub format_log_line_html {
1970 my $line = shift;
1972 $line = esc_html($line, -nbsp=>1);
1973 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1974 $cgi->a({-href => href(action=>"object", hash=>$1),
1975 -class => "text"}, $1);
1976 }eg;
1978 return $line;
1981 # format marker of refs pointing to given object
1983 # the destination action is chosen based on object type and current context:
1984 # - for annotated tags, we choose the tag view unless it's the current view
1985 # already, in which case we go to shortlog view
1986 # - for other refs, we keep the current view if we're in history, shortlog or
1987 # log view, and select shortlog otherwise
1988 sub format_ref_marker {
1989 my ($refs, $id) = @_;
1990 my $markers = '';
1992 if (defined $refs->{$id}) {
1993 foreach my $ref (@{$refs->{$id}}) {
1994 # this code exploits the fact that non-lightweight tags are the
1995 # only indirect objects, and that they are the only objects for which
1996 # we want to use tag instead of shortlog as action
1997 my ($type, $name) = qw();
1998 my $indirect = ($ref =~ s/\^\{\}$//);
1999 # e.g. tags/v2.6.11 or heads/next
2000 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2001 $type = $1;
2002 $name = $2;
2003 } else {
2004 $type = "ref";
2005 $name = $ref;
2008 my $class = $type;
2009 $class .= " indirect" if $indirect;
2011 my $dest_action = "shortlog";
2013 if ($indirect) {
2014 $dest_action = "tag" unless $action eq "tag";
2015 } elsif ($action =~ /^(history|(short)?log)$/) {
2016 $dest_action = $action;
2019 my $dest = "";
2020 $dest .= "refs/" unless $ref =~ m!^refs/!;
2021 $dest .= $ref;
2023 my $link = $cgi->a({
2024 -href => href(
2025 action=>$dest_action,
2026 hash=>$dest
2027 )}, $name);
2029 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2030 $link . "</span>";
2034 if ($markers) {
2035 return ' <span class="refs">'. $markers . '</span>';
2036 } else {
2037 return "";
2041 # format, perhaps shortened and with markers, title line
2042 sub format_subject_html {
2043 my ($long, $short, $href, $extra) = @_;
2044 $extra = '' unless defined($extra);
2046 if (length($short) < length($long)) {
2047 $long =~ s/[[:cntrl:]]/?/g;
2048 return $cgi->a({-href => $href, -class => "list subject",
2049 -title => to_utf8($long)},
2050 esc_html($short)) . $extra;
2051 } else {
2052 return $cgi->a({-href => $href, -class => "list subject"},
2053 esc_html($long)) . $extra;
2057 # Rather than recomputing the url for an email multiple times, we cache it
2058 # after the first hit. This gives a visible benefit in views where the avatar
2059 # for the same email is used repeatedly (e.g. shortlog).
2060 # The cache is shared by all avatar engines (currently gravatar only), which
2061 # are free to use it as preferred. Since only one avatar engine is used for any
2062 # given page, there's no risk for cache conflicts.
2063 our %avatar_cache = ();
2065 # Compute the picon url for a given email, by using the picon search service over at
2066 # http://www.cs.indiana.edu/picons/search.html
2067 sub picon_url {
2068 my $email = lc shift;
2069 if (!$avatar_cache{$email}) {
2070 my ($user, $domain) = split('@', $email);
2071 $avatar_cache{$email} =
2072 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2073 "$domain/$user/" .
2074 "users+domains+unknown/up/single";
2076 return $avatar_cache{$email};
2079 # Compute the gravatar url for a given email, if it's not in the cache already.
2080 # Gravatar stores only the part of the URL before the size, since that's the
2081 # one computationally more expensive. This also allows reuse of the cache for
2082 # different sizes (for this particular engine).
2083 sub gravatar_url {
2084 my $email = lc shift;
2085 my $size = shift;
2086 $avatar_cache{$email} ||=
2087 "http://www.gravatar.com/avatar/" .
2088 Digest::MD5::md5_hex($email) . "?s=";
2089 return $avatar_cache{$email} . $size;
2092 # Insert an avatar for the given $email at the given $size if the feature
2093 # is enabled.
2094 sub git_get_avatar {
2095 my ($email, %opts) = @_;
2096 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2097 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2098 $opts{-size} ||= 'default';
2099 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2100 my $url = "";
2101 if ($git_avatar eq 'gravatar') {
2102 $url = gravatar_url($email, $size);
2103 } elsif ($git_avatar eq 'picon') {
2104 $url = picon_url($email);
2106 # Other providers can be added by extending the if chain, defining $url
2107 # as needed. If no variant puts something in $url, we assume avatars
2108 # are completely disabled/unavailable.
2109 if ($url) {
2110 return $pre_white .
2111 "<img width=\"$size\" " .
2112 "class=\"avatar\" " .
2113 "src=\"".esc_url($url)."\" " .
2114 "alt=\"\" " .
2115 "/>" . $post_white;
2116 } else {
2117 return "";
2121 sub format_search_author {
2122 my ($author, $searchtype, $displaytext) = @_;
2123 my $have_search = gitweb_check_feature('search');
2125 if ($have_search) {
2126 my $performed = "";
2127 if ($searchtype eq 'author') {
2128 $performed = "authored";
2129 } elsif ($searchtype eq 'committer') {
2130 $performed = "committed";
2133 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2134 searchtext=>$author,
2135 searchtype=>$searchtype), class=>"list",
2136 title=>"Search for commits $performed by $author"},
2137 $displaytext);
2139 } else {
2140 return $displaytext;
2144 # format the author name of the given commit with the given tag
2145 # the author name is chopped and escaped according to the other
2146 # optional parameters (see chop_str).
2147 sub format_author_html {
2148 my $tag = shift;
2149 my $co = shift;
2150 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2151 return "<$tag class=\"author\">" .
2152 format_search_author($co->{'author_name'}, "author",
2153 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2154 $author) .
2155 "</$tag>";
2158 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2159 sub format_git_diff_header_line {
2160 my $line = shift;
2161 my $diffinfo = shift;
2162 my ($from, $to) = @_;
2164 if ($diffinfo->{'nparents'}) {
2165 # combined diff
2166 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2167 if ($to->{'href'}) {
2168 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2169 esc_path($to->{'file'}));
2170 } else { # file was deleted (no href)
2171 $line .= esc_path($to->{'file'});
2173 } else {
2174 # "ordinary" diff
2175 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2176 if ($from->{'href'}) {
2177 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2178 'a/' . esc_path($from->{'file'}));
2179 } else { # file was added (no href)
2180 $line .= 'a/' . esc_path($from->{'file'});
2182 $line .= ' ';
2183 if ($to->{'href'}) {
2184 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2185 'b/' . esc_path($to->{'file'}));
2186 } else { # file was deleted
2187 $line .= 'b/' . esc_path($to->{'file'});
2191 return "<div class=\"diff header\">$line</div>\n";
2194 # format extended diff header line, before patch itself
2195 sub format_extended_diff_header_line {
2196 my $line = shift;
2197 my $diffinfo = shift;
2198 my ($from, $to) = @_;
2200 # match <path>
2201 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2202 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2203 esc_path($from->{'file'}));
2205 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2206 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2207 esc_path($to->{'file'}));
2209 # match single <mode>
2210 if ($line =~ m/\s(\d{6})$/) {
2211 $line .= '<span class="info"> (' .
2212 file_type_long($1) .
2213 ')</span>';
2215 # match <hash>
2216 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2217 # can match only for combined diff
2218 $line = 'index ';
2219 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2220 if ($from->{'href'}[$i]) {
2221 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2222 -class=>"hash"},
2223 substr($diffinfo->{'from_id'}[$i],0,7));
2224 } else {
2225 $line .= '0' x 7;
2227 # separator
2228 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2230 $line .= '..';
2231 if ($to->{'href'}) {
2232 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2233 substr($diffinfo->{'to_id'},0,7));
2234 } else {
2235 $line .= '0' x 7;
2238 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2239 # can match only for ordinary diff
2240 my ($from_link, $to_link);
2241 if ($from->{'href'}) {
2242 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2243 substr($diffinfo->{'from_id'},0,7));
2244 } else {
2245 $from_link = '0' x 7;
2247 if ($to->{'href'}) {
2248 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2249 substr($diffinfo->{'to_id'},0,7));
2250 } else {
2251 $to_link = '0' x 7;
2253 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2254 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2257 return $line . "<br/>\n";
2260 # format from-file/to-file diff header
2261 sub format_diff_from_to_header {
2262 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2263 my $line;
2264 my $result = '';
2266 $line = $from_line;
2267 #assert($line =~ m/^---/) if DEBUG;
2268 # no extra formatting for "^--- /dev/null"
2269 if (! $diffinfo->{'nparents'}) {
2270 # ordinary (single parent) diff
2271 if ($line =~ m!^--- "?a/!) {
2272 if ($from->{'href'}) {
2273 $line = '--- a/' .
2274 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2275 esc_path($from->{'file'}));
2276 } else {
2277 $line = '--- a/' .
2278 esc_path($from->{'file'});
2281 $result .= qq!<div class="diff from_file">$line</div>\n!;
2283 } else {
2284 # combined diff (merge commit)
2285 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2286 if ($from->{'href'}[$i]) {
2287 $line = '--- ' .
2288 $cgi->a({-href=>href(action=>"blobdiff",
2289 hash_parent=>$diffinfo->{'from_id'}[$i],
2290 hash_parent_base=>$parents[$i],
2291 file_parent=>$from->{'file'}[$i],
2292 hash=>$diffinfo->{'to_id'},
2293 hash_base=>$hash,
2294 file_name=>$to->{'file'}),
2295 -class=>"path",
2296 -title=>"diff" . ($i+1)},
2297 $i+1) .
2298 '/' .
2299 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2300 esc_path($from->{'file'}[$i]));
2301 } else {
2302 $line = '--- /dev/null';
2304 $result .= qq!<div class="diff from_file">$line</div>\n!;
2308 $line = $to_line;
2309 #assert($line =~ m/^\+\+\+/) if DEBUG;
2310 # no extra formatting for "^+++ /dev/null"
2311 if ($line =~ m!^\+\+\+ "?b/!) {
2312 if ($to->{'href'}) {
2313 $line = '+++ b/' .
2314 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2315 esc_path($to->{'file'}));
2316 } else {
2317 $line = '+++ b/' .
2318 esc_path($to->{'file'});
2321 $result .= qq!<div class="diff to_file">$line</div>\n!;
2323 return $result;
2326 # create note for patch simplified by combined diff
2327 sub format_diff_cc_simplified {
2328 my ($diffinfo, @parents) = @_;
2329 my $result = '';
2331 $result .= "<div class=\"diff header\">" .
2332 "diff --cc ";
2333 if (!is_deleted($diffinfo)) {
2334 $result .= $cgi->a({-href => href(action=>"blob",
2335 hash_base=>$hash,
2336 hash=>$diffinfo->{'to_id'},
2337 file_name=>$diffinfo->{'to_file'}),
2338 -class => "path"},
2339 esc_path($diffinfo->{'to_file'}));
2340 } else {
2341 $result .= esc_path($diffinfo->{'to_file'});
2343 $result .= "</div>\n" . # class="diff header"
2344 "<div class=\"diff nodifferences\">" .
2345 "Simple merge" .
2346 "</div>\n"; # class="diff nodifferences"
2348 return $result;
2351 sub diff_line_class {
2352 my ($line, $from, $to) = @_;
2354 # ordinary diff
2355 my $num_sign = 1;
2356 # combined diff
2357 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2358 $num_sign = scalar @{$from->{'href'}};
2361 my @diff_line_classifier = (
2362 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2363 { regexp => qr/^\\/, class => "incomplete" },
2364 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2365 # classifier for context must come before classifier add/rem,
2366 # or we would have to use more complicated regexp, for example
2367 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2368 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2369 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2371 for my $clsfy (@diff_line_classifier) {
2372 return $clsfy->{'class'}
2373 if ($line =~ $clsfy->{'regexp'});
2376 # fallback
2377 return "";
2380 # assumes that $from and $to are defined and correctly filled,
2381 # and that $line holds a line of chunk header for unified diff
2382 sub format_unidiff_chunk_header {
2383 my ($line, $from, $to) = @_;
2385 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2386 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2388 $from_lines = 0 unless defined $from_lines;
2389 $to_lines = 0 unless defined $to_lines;
2391 if ($from->{'href'}) {
2392 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2393 -class=>"list"}, $from_text);
2395 if ($to->{'href'}) {
2396 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2397 -class=>"list"}, $to_text);
2399 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2400 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2401 return $line;
2404 # assumes that $from and $to are defined and correctly filled,
2405 # and that $line holds a line of chunk header for combined diff
2406 sub format_cc_diff_chunk_header {
2407 my ($line, $from, $to) = @_;
2409 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2410 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2412 @from_text = split(' ', $ranges);
2413 for (my $i = 0; $i < @from_text; ++$i) {
2414 ($from_start[$i], $from_nlines[$i]) =
2415 (split(',', substr($from_text[$i], 1)), 0);
2418 $to_text = pop @from_text;
2419 $to_start = pop @from_start;
2420 $to_nlines = pop @from_nlines;
2422 $line = "<span class=\"chunk_info\">$prefix ";
2423 for (my $i = 0; $i < @from_text; ++$i) {
2424 if ($from->{'href'}[$i]) {
2425 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2426 -class=>"list"}, $from_text[$i]);
2427 } else {
2428 $line .= $from_text[$i];
2430 $line .= " ";
2432 if ($to->{'href'}) {
2433 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2434 -class=>"list"}, $to_text);
2435 } else {
2436 $line .= $to_text;
2438 $line .= " $prefix</span>" .
2439 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2440 return $line;
2443 # process patch (diff) line (not to be used for diff headers),
2444 # returning HTML-formatted (but not wrapped) line.
2445 # If the line is passed as a reference, it is treated as HTML and not
2446 # esc_html()'ed.
2447 sub format_diff_line {
2448 my ($line, $diff_class, $from, $to) = @_;
2450 if (ref($line)) {
2451 $line = $$line;
2452 } else {
2453 chomp $line;
2454 $line = untabify($line);
2456 if ($from && $to && $line =~ m/^\@{2} /) {
2457 $line = format_unidiff_chunk_header($line, $from, $to);
2458 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2459 $line = format_cc_diff_chunk_header($line, $from, $to);
2460 } else {
2461 $line = esc_html($line, -nbsp=>1);
2465 my $diff_classes = "diff";
2466 $diff_classes .= " $diff_class" if ($diff_class);
2467 $line = "<div class=\"$diff_classes\">$line</div>\n";
2469 return $line;
2472 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2473 # linked. Pass the hash of the tree/commit to snapshot.
2474 sub format_snapshot_links {
2475 my ($hash) = @_;
2476 my $num_fmts = @snapshot_fmts;
2477 if ($num_fmts > 1) {
2478 # A parenthesized list of links bearing format names.
2479 # e.g. "snapshot (_tar.gz_ _zip_)"
2480 return "snapshot (" . join(' ', map
2481 $cgi->a({
2482 -href => href(
2483 action=>"snapshot",
2484 hash=>$hash,
2485 snapshot_format=>$_
2487 }, $known_snapshot_formats{$_}{'display'})
2488 , @snapshot_fmts) . ")";
2489 } elsif ($num_fmts == 1) {
2490 # A single "snapshot" link whose tooltip bears the format name.
2491 # i.e. "_snapshot_"
2492 my ($fmt) = @snapshot_fmts;
2493 return
2494 $cgi->a({
2495 -href => href(
2496 action=>"snapshot",
2497 hash=>$hash,
2498 snapshot_format=>$fmt
2500 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2501 }, "snapshot");
2502 } else { # $num_fmts == 0
2503 return undef;
2507 ## ......................................................................
2508 ## functions returning values to be passed, perhaps after some
2509 ## transformation, to other functions; e.g. returning arguments to href()
2511 # returns hash to be passed to href to generate gitweb URL
2512 # in -title key it returns description of link
2513 sub get_feed_info {
2514 my $format = shift || 'Atom';
2515 my %res = (action => lc($format));
2517 # feed links are possible only for project views
2518 return unless (defined $project);
2519 # some views should link to OPML, or to generic project feed,
2520 # or don't have specific feed yet (so they should use generic)
2521 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2523 my $branch;
2524 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2525 # from tag links; this also makes possible to detect branch links
2526 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2527 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2528 $branch = $1;
2530 # find log type for feed description (title)
2531 my $type = 'log';
2532 if (defined $file_name) {
2533 $type = "history of $file_name";
2534 $type .= "/" if ($action eq 'tree');
2535 $type .= " on '$branch'" if (defined $branch);
2536 } else {
2537 $type = "log of $branch" if (defined $branch);
2540 $res{-title} = $type;
2541 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2542 $res{'file_name'} = $file_name;
2544 return %res;
2547 ## ----------------------------------------------------------------------
2548 ## git utility subroutines, invoking git commands
2550 # returns path to the core git executable and the --git-dir parameter as list
2551 sub git_cmd {
2552 $number_of_git_cmds++;
2553 return $GIT, '--git-dir='.$git_dir;
2556 # quote the given arguments for passing them to the shell
2557 # quote_command("command", "arg 1", "arg with ' and ! characters")
2558 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2559 # Try to avoid using this function wherever possible.
2560 sub quote_command {
2561 return join(' ',
2562 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2565 # get HEAD ref of given project as hash
2566 sub git_get_head_hash {
2567 return git_get_full_hash(shift, 'HEAD');
2570 sub git_get_full_hash {
2571 return git_get_hash(@_);
2574 sub git_get_short_hash {
2575 return git_get_hash(@_, '--short=7');
2578 sub git_get_hash {
2579 my ($project, $hash, @options) = @_;
2580 my $o_git_dir = $git_dir;
2581 my $retval = undef;
2582 $git_dir = "$projectroot/$project";
2583 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2584 '--verify', '-q', @options, $hash) {
2585 $retval = <$fd>;
2586 chomp $retval if defined $retval;
2587 close $fd;
2589 if (defined $o_git_dir) {
2590 $git_dir = $o_git_dir;
2592 return $retval;
2595 # get type of given object
2596 sub git_get_type {
2597 my $hash = shift;
2599 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2600 my $type = <$fd>;
2601 close $fd or return;
2602 chomp $type;
2603 return $type;
2606 # repository configuration
2607 our $config_file = '';
2608 our %config;
2610 # store multiple values for single key as anonymous array reference
2611 # single values stored directly in the hash, not as [ <value> ]
2612 sub hash_set_multi {
2613 my ($hash, $key, $value) = @_;
2615 if (!exists $hash->{$key}) {
2616 $hash->{$key} = $value;
2617 } elsif (!ref $hash->{$key}) {
2618 $hash->{$key} = [ $hash->{$key}, $value ];
2619 } else {
2620 push @{$hash->{$key}}, $value;
2624 # return hash of git project configuration
2625 # optionally limited to some section, e.g. 'gitweb'
2626 sub git_parse_project_config {
2627 my $section_regexp = shift;
2628 my %config;
2630 local $/ = "\0";
2632 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2633 or return;
2635 while (my $keyval = <$fh>) {
2636 chomp $keyval;
2637 my ($key, $value) = split(/\n/, $keyval, 2);
2639 hash_set_multi(\%config, $key, $value)
2640 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2642 close $fh;
2644 return %config;
2647 # convert config value to boolean: 'true' or 'false'
2648 # no value, number > 0, 'true' and 'yes' values are true
2649 # rest of values are treated as false (never as error)
2650 sub config_to_bool {
2651 my $val = shift;
2653 return 1 if !defined $val; # section.key
2655 # strip leading and trailing whitespace
2656 $val =~ s/^\s+//;
2657 $val =~ s/\s+$//;
2659 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2660 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2663 # convert config value to simple decimal number
2664 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2665 # to be multiplied by 1024, 1048576, or 1073741824
2666 sub config_to_int {
2667 my $val = shift;
2669 # strip leading and trailing whitespace
2670 $val =~ s/^\s+//;
2671 $val =~ s/\s+$//;
2673 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2674 $unit = lc($unit);
2675 # unknown unit is treated as 1
2676 return $num * ($unit eq 'g' ? 1073741824 :
2677 $unit eq 'm' ? 1048576 :
2678 $unit eq 'k' ? 1024 : 1);
2680 return $val;
2683 # convert config value to array reference, if needed
2684 sub config_to_multi {
2685 my $val = shift;
2687 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2690 sub git_get_project_config {
2691 my ($key, $type) = @_;
2693 return unless defined $git_dir;
2695 # key sanity check
2696 return unless ($key);
2697 # only subsection, if exists, is case sensitive,
2698 # and not lowercased by 'git config -z -l'
2699 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2700 $key = join(".", lc($hi), $mi, lc($lo));
2701 } else {
2702 $key = lc($key);
2704 $key =~ s/^gitweb\.//;
2705 return if ($key =~ m/\W/);
2707 # type sanity check
2708 if (defined $type) {
2709 $type =~ s/^--//;
2710 $type = undef
2711 unless ($type eq 'bool' || $type eq 'int');
2714 # get config
2715 if (!defined $config_file ||
2716 $config_file ne "$git_dir/config") {
2717 %config = git_parse_project_config('gitweb');
2718 $config_file = "$git_dir/config";
2721 # check if config variable (key) exists
2722 return unless exists $config{"gitweb.$key"};
2724 # ensure given type
2725 if (!defined $type) {
2726 return $config{"gitweb.$key"};
2727 } elsif ($type eq 'bool') {
2728 # backward compatibility: 'git config --bool' returns true/false
2729 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2730 } elsif ($type eq 'int') {
2731 return config_to_int($config{"gitweb.$key"});
2733 return $config{"gitweb.$key"};
2736 # get hash of given path at given ref
2737 sub git_get_hash_by_path {
2738 my $base = shift;
2739 my $path = shift || return undef;
2740 my $type = shift;
2742 $path =~ s,/+$,,;
2744 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2745 or die_error(500, "Open git-ls-tree failed");
2746 my $line = <$fd>;
2747 close $fd or return undef;
2749 if (!defined $line) {
2750 # there is no tree or hash given by $path at $base
2751 return undef;
2754 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2755 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2756 if (defined $type && $type ne $2) {
2757 # type doesn't match
2758 return undef;
2760 return $3;
2763 # get path of entry with given hash at given tree-ish (ref)
2764 # used to get 'from' filename for combined diff (merge commit) for renames
2765 sub git_get_path_by_hash {
2766 my $base = shift || return;
2767 my $hash = shift || return;
2769 local $/ = "\0";
2771 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2772 or return undef;
2773 while (my $line = <$fd>) {
2774 chomp $line;
2776 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2777 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2778 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2779 close $fd;
2780 return $1;
2783 close $fd;
2784 return undef;
2787 ## ......................................................................
2788 ## git utility functions, directly accessing git repository
2790 # get the value of config variable either from file named as the variable
2791 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2792 # configuration variable in the repository config file.
2793 sub git_get_file_or_project_config {
2794 my ($path, $name) = @_;
2796 $git_dir = "$projectroot/$path";
2797 open my $fd, '<', "$git_dir/$name"
2798 or return git_get_project_config($name);
2799 my $conf = <$fd>;
2800 close $fd;
2801 if (defined $conf) {
2802 chomp $conf;
2804 return $conf;
2807 sub git_get_project_description {
2808 my $path = shift;
2809 return git_get_file_or_project_config($path, 'description');
2812 sub git_get_project_category {
2813 my $path = shift;
2814 return git_get_file_or_project_config($path, 'category');
2818 # supported formats:
2819 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2820 # - if its contents is a number, use it as tag weight,
2821 # - otherwise add a tag with weight 1
2822 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2823 # the same value multiple times increases tag weight
2824 # * `gitweb.ctag' multi-valued repo config variable
2825 sub git_get_project_ctags {
2826 my $project = shift;
2827 my $ctags = {};
2829 $git_dir = "$projectroot/$project";
2830 if (opendir my $dh, "$git_dir/ctags") {
2831 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2832 foreach my $tagfile (@files) {
2833 open my $ct, '<', $tagfile
2834 or next;
2835 my $val = <$ct>;
2836 chomp $val if $val;
2837 close $ct;
2839 (my $ctag = $tagfile) =~ s#.*/##;
2840 if ($val =~ /^\d+$/) {
2841 $ctags->{$ctag} = $val;
2842 } else {
2843 $ctags->{$ctag} = 1;
2846 closedir $dh;
2848 } elsif (open my $fh, '<', "$git_dir/ctags") {
2849 while (my $line = <$fh>) {
2850 chomp $line;
2851 $ctags->{$line}++ if $line;
2853 close $fh;
2855 } else {
2856 my $taglist = config_to_multi(git_get_project_config('ctag'));
2857 foreach my $tag (@$taglist) {
2858 $ctags->{$tag}++;
2862 return $ctags;
2865 # return hash, where keys are content tags ('ctags'),
2866 # and values are sum of weights of given tag in every project
2867 sub git_gather_all_ctags {
2868 my $projects = shift;
2869 my $ctags = {};
2871 foreach my $p (@$projects) {
2872 foreach my $ct (keys %{$p->{'ctags'}}) {
2873 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2877 return $ctags;
2880 sub git_populate_project_tagcloud {
2881 my $ctags = shift;
2883 # First, merge different-cased tags; tags vote on casing
2884 my %ctags_lc;
2885 foreach (keys %$ctags) {
2886 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2887 if (not $ctags_lc{lc $_}->{topcount}
2888 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2889 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2890 $ctags_lc{lc $_}->{topname} = $_;
2894 my $cloud;
2895 my $matched = $input_params{'ctag'};
2896 if (eval { require HTML::TagCloud; 1; }) {
2897 $cloud = HTML::TagCloud->new;
2898 foreach my $ctag (sort keys %ctags_lc) {
2899 # Pad the title with spaces so that the cloud looks
2900 # less crammed.
2901 my $title = esc_html($ctags_lc{$ctag}->{topname});
2902 $title =~ s/ /&nbsp;/g;
2903 $title =~ s/^/&nbsp;/g;
2904 $title =~ s/$/&nbsp;/g;
2905 if (defined $matched && $matched eq $ctag) {
2906 $title = qq(<span class="match">$title</span>);
2908 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2909 $ctags_lc{$ctag}->{count});
2911 } else {
2912 $cloud = {};
2913 foreach my $ctag (keys %ctags_lc) {
2914 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
2915 if (defined $matched && $matched eq $ctag) {
2916 $title = qq(<span class="match">$title</span>);
2918 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
2919 $cloud->{$ctag}{ctag} =
2920 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
2923 return $cloud;
2926 sub git_show_project_tagcloud {
2927 my ($cloud, $count) = @_;
2928 if (ref $cloud eq 'HTML::TagCloud') {
2929 return $cloud->html_and_css($count);
2930 } else {
2931 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
2932 return
2933 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
2934 join (', ', map {
2935 $cloud->{$_}->{'ctag'}
2936 } splice(@tags, 0, $count)) .
2937 '</div>';
2941 sub git_get_project_url_list {
2942 my $path = shift;
2944 $git_dir = "$projectroot/$path";
2945 open my $fd, '<', "$git_dir/cloneurl"
2946 or return wantarray ?
2947 @{ config_to_multi(git_get_project_config('url')) } :
2948 config_to_multi(git_get_project_config('url'));
2949 my @git_project_url_list = map { chomp; $_ } <$fd>;
2950 close $fd;
2952 return wantarray ? @git_project_url_list : \@git_project_url_list;
2955 sub git_get_projects_list {
2956 my $filter = shift || '';
2957 my $paranoid = shift;
2958 my @list;
2960 if (-d $projects_list) {
2961 # search in directory
2962 my $dir = $projects_list;
2963 # remove the trailing "/"
2964 $dir =~ s!/+$!!;
2965 my $pfxlen = length("$dir");
2966 my $pfxdepth = ($dir =~ tr!/!!);
2967 # when filtering, search only given subdirectory
2968 if ($filter && !$paranoid) {
2969 $dir .= "/$filter";
2970 $dir =~ s!/+$!!;
2973 File::Find::find({
2974 follow_fast => 1, # follow symbolic links
2975 follow_skip => 2, # ignore duplicates
2976 dangling_symlinks => 0, # ignore dangling symlinks, silently
2977 wanted => sub {
2978 # global variables
2979 our $project_maxdepth;
2980 our $projectroot;
2981 # skip project-list toplevel, if we get it.
2982 return if (m!^[/.]$!);
2983 # only directories can be git repositories
2984 return unless (-d $_);
2985 # don't traverse too deep (Find is super slow on os x)
2986 # $project_maxdepth excludes depth of $projectroot
2987 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2988 $File::Find::prune = 1;
2989 return;
2992 my $path = substr($File::Find::name, $pfxlen + 1);
2993 # paranoidly only filter here
2994 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
2995 next;
2997 # we check related file in $projectroot
2998 if (check_export_ok("$projectroot/$path")) {
2999 push @list, { path => $path };
3000 $File::Find::prune = 1;
3003 }, "$dir");
3005 } elsif (-f $projects_list) {
3006 # read from file(url-encoded):
3007 # 'git%2Fgit.git Linus+Torvalds'
3008 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3009 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3010 open my $fd, '<', $projects_list or return;
3011 PROJECT:
3012 while (my $line = <$fd>) {
3013 chomp $line;
3014 my ($path, $owner) = split ' ', $line;
3015 $path = unescape($path);
3016 $owner = unescape($owner);
3017 if (!defined $path) {
3018 next;
3020 # if $filter is rpovided, check if $path begins with $filter
3021 if ($filter && $path !~ m!^\Q$filter\E/!) {
3022 next;
3024 if (check_export_ok("$projectroot/$path")) {
3025 my $pr = {
3026 path => $path
3028 if ($owner) {
3029 $pr->{'owner'} = to_utf8($owner);
3031 push @list, $pr;
3034 close $fd;
3036 return @list;
3039 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3040 # as side effects it sets 'forks' field to list of forks for forked projects
3041 sub filter_forks_from_projects_list {
3042 my $projects = shift;
3044 my %trie; # prefix tree of directories (path components)
3045 # generate trie out of those directories that might contain forks
3046 foreach my $pr (@$projects) {
3047 my $path = $pr->{'path'};
3048 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3049 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3050 next unless ($path); # skip '.git' repository: tests, git-instaweb
3051 next unless (-d "$projectroot/$path"); # containing directory exists
3052 $pr->{'forks'} = []; # there can be 0 or more forks of project
3054 # add to trie
3055 my @dirs = split('/', $path);
3056 # walk the trie, until either runs out of components or out of trie
3057 my $ref = \%trie;
3058 while (scalar @dirs &&
3059 exists($ref->{$dirs[0]})) {
3060 $ref = $ref->{shift @dirs};
3062 # create rest of trie structure from rest of components
3063 foreach my $dir (@dirs) {
3064 $ref = $ref->{$dir} = {};
3066 # create end marker, store $pr as a data
3067 $ref->{''} = $pr if (!exists $ref->{''});
3070 # filter out forks, by finding shortest prefix match for paths
3071 my @filtered;
3072 PROJECT:
3073 foreach my $pr (@$projects) {
3074 # trie lookup
3075 my $ref = \%trie;
3076 DIR:
3077 foreach my $dir (split('/', $pr->{'path'})) {
3078 if (exists $ref->{''}) {
3079 # found [shortest] prefix, is a fork - skip it
3080 push @{$ref->{''}{'forks'}}, $pr;
3081 next PROJECT;
3083 if (!exists $ref->{$dir}) {
3084 # not in trie, cannot have prefix, not a fork
3085 push @filtered, $pr;
3086 next PROJECT;
3088 # If the dir is there, we just walk one step down the trie.
3089 $ref = $ref->{$dir};
3091 # we ran out of trie
3092 # (shouldn't happen: it's either no match, or end marker)
3093 push @filtered, $pr;
3096 return @filtered;
3099 # note: fill_project_list_info must be run first,
3100 # for 'descr_long' and 'ctags' to be filled
3101 sub search_projects_list {
3102 my ($projlist, %opts) = @_;
3103 my $tagfilter = $opts{'tagfilter'};
3104 my $search_re = $opts{'search_regexp'};
3106 return @$projlist
3107 unless ($tagfilter || $search_re);
3109 # searching projects require filling to be run before it;
3110 fill_project_list_info($projlist,
3111 $tagfilter ? 'ctags' : (),
3112 $search_re ? ('path', 'descr') : ());
3113 my @projects;
3114 PROJECT:
3115 foreach my $pr (@$projlist) {
3117 if ($tagfilter) {
3118 next unless ref($pr->{'ctags'}) eq 'HASH';
3119 next unless
3120 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3123 if ($search_re) {
3124 next unless
3125 $pr->{'path'} =~ /$search_re/ ||
3126 $pr->{'descr_long'} =~ /$search_re/;
3129 push @projects, $pr;
3132 return @projects;
3135 our $gitweb_project_owner = undef;
3136 sub git_get_project_list_from_file {
3138 return if (defined $gitweb_project_owner);
3140 $gitweb_project_owner = {};
3141 # read from file (url-encoded):
3142 # 'git%2Fgit.git Linus+Torvalds'
3143 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3144 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3145 if (-f $projects_list) {
3146 open(my $fd, '<', $projects_list);
3147 while (my $line = <$fd>) {
3148 chomp $line;
3149 my ($pr, $ow) = split ' ', $line;
3150 $pr = unescape($pr);
3151 $ow = unescape($ow);
3152 $gitweb_project_owner->{$pr} = to_utf8($ow);
3154 close $fd;
3158 sub git_get_project_owner {
3159 my $project = shift;
3160 my $owner;
3162 return undef unless $project;
3163 $git_dir = "$projectroot/$project";
3165 if (!defined $gitweb_project_owner) {
3166 git_get_project_list_from_file();
3169 if (exists $gitweb_project_owner->{$project}) {
3170 $owner = $gitweb_project_owner->{$project};
3172 if (!defined $owner){
3173 $owner = git_get_project_config('owner');
3175 if (!defined $owner) {
3176 $owner = get_file_owner("$git_dir");
3179 return $owner;
3182 sub git_get_last_activity {
3183 my ($path) = @_;
3184 my $fd;
3186 $git_dir = "$projectroot/$path";
3187 open($fd, "-|", git_cmd(), 'for-each-ref',
3188 '--format=%(committer)',
3189 '--sort=-committerdate',
3190 '--count=1',
3191 'refs/heads') or return;
3192 my $most_recent = <$fd>;
3193 close $fd or return;
3194 if (defined $most_recent &&
3195 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3196 my $timestamp = $1;
3197 my $age = time - $timestamp;
3198 return ($age, age_string($age));
3200 return (undef, undef);
3203 # Implementation note: when a single remote is wanted, we cannot use 'git
3204 # remote show -n' because that command always work (assuming it's a remote URL
3205 # if it's not defined), and we cannot use 'git remote show' because that would
3206 # try to make a network roundtrip. So the only way to find if that particular
3207 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3208 # and when we find what we want.
3209 sub git_get_remotes_list {
3210 my $wanted = shift;
3211 my %remotes = ();
3213 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3214 return unless $fd;
3215 while (my $remote = <$fd>) {
3216 chomp $remote;
3217 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3218 next if $wanted and not $remote eq $wanted;
3219 my ($url, $key) = ($1, $2);
3221 $remotes{$remote} ||= { 'heads' => () };
3222 $remotes{$remote}{$key} = $url;
3224 close $fd or return;
3225 return wantarray ? %remotes : \%remotes;
3228 # Takes a hash of remotes as first parameter and fills it by adding the
3229 # available remote heads for each of the indicated remotes.
3230 sub fill_remote_heads {
3231 my $remotes = shift;
3232 my @heads = map { "remotes/$_" } keys %$remotes;
3233 my @remoteheads = git_get_heads_list(undef, @heads);
3234 foreach my $remote (keys %$remotes) {
3235 $remotes->{$remote}{'heads'} = [ grep {
3236 $_->{'name'} =~ s!^$remote/!!
3237 } @remoteheads ];
3241 sub git_get_references {
3242 my $type = shift || "";
3243 my %refs;
3244 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3245 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3246 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3247 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3248 or return;
3250 while (my $line = <$fd>) {
3251 chomp $line;
3252 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3253 if (defined $refs{$1}) {
3254 push @{$refs{$1}}, $2;
3255 } else {
3256 $refs{$1} = [ $2 ];
3260 close $fd or return;
3261 return \%refs;
3264 sub git_get_rev_name_tags {
3265 my $hash = shift || return undef;
3267 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3268 or return;
3269 my $name_rev = <$fd>;
3270 close $fd;
3272 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3273 return $1;
3274 } else {
3275 # catches also '$hash undefined' output
3276 return undef;
3280 ## ----------------------------------------------------------------------
3281 ## parse to hash functions
3283 sub parse_date {
3284 my $epoch = shift;
3285 my $tz = shift || "-0000";
3287 my %date;
3288 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3289 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3290 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3291 $date{'hour'} = $hour;
3292 $date{'minute'} = $min;
3293 $date{'mday'} = $mday;
3294 $date{'day'} = $days[$wday];
3295 $date{'month'} = $months[$mon];
3296 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3297 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3298 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3299 $mday, $months[$mon], $hour ,$min;
3300 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3301 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3303 my ($tz_sign, $tz_hour, $tz_min) =
3304 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3305 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3306 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3307 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3308 $date{'hour_local'} = $hour;
3309 $date{'minute_local'} = $min;
3310 $date{'tz_local'} = $tz;
3311 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3312 1900+$year, $mon+1, $mday,
3313 $hour, $min, $sec, $tz);
3314 return %date;
3317 sub parse_tag {
3318 my $tag_id = shift;
3319 my %tag;
3320 my @comment;
3322 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3323 $tag{'id'} = $tag_id;
3324 while (my $line = <$fd>) {
3325 chomp $line;
3326 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3327 $tag{'object'} = $1;
3328 } elsif ($line =~ m/^type (.+)$/) {
3329 $tag{'type'} = $1;
3330 } elsif ($line =~ m/^tag (.+)$/) {
3331 $tag{'name'} = $1;
3332 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3333 $tag{'author'} = $1;
3334 $tag{'author_epoch'} = $2;
3335 $tag{'author_tz'} = $3;
3336 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3337 $tag{'author_name'} = $1;
3338 $tag{'author_email'} = $2;
3339 } else {
3340 $tag{'author_name'} = $tag{'author'};
3342 } elsif ($line =~ m/--BEGIN/) {
3343 push @comment, $line;
3344 last;
3345 } elsif ($line eq "") {
3346 last;
3349 push @comment, <$fd>;
3350 $tag{'comment'} = \@comment;
3351 close $fd or return;
3352 if (!defined $tag{'name'}) {
3353 return
3355 return %tag
3358 sub parse_commit_text {
3359 my ($commit_text, $withparents) = @_;
3360 my @commit_lines = split '\n', $commit_text;
3361 my %co;
3363 pop @commit_lines; # Remove '\0'
3365 if (! @commit_lines) {
3366 return;
3369 my $header = shift @commit_lines;
3370 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3371 return;
3373 ($co{'id'}, my @parents) = split ' ', $header;
3374 while (my $line = shift @commit_lines) {
3375 last if $line eq "\n";
3376 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3377 $co{'tree'} = $1;
3378 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3379 push @parents, $1;
3380 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3381 $co{'author'} = to_utf8($1);
3382 $co{'author_epoch'} = $2;
3383 $co{'author_tz'} = $3;
3384 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3385 $co{'author_name'} = $1;
3386 $co{'author_email'} = $2;
3387 } else {
3388 $co{'author_name'} = $co{'author'};
3390 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3391 $co{'committer'} = to_utf8($1);
3392 $co{'committer_epoch'} = $2;
3393 $co{'committer_tz'} = $3;
3394 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3395 $co{'committer_name'} = $1;
3396 $co{'committer_email'} = $2;
3397 } else {
3398 $co{'committer_name'} = $co{'committer'};
3402 if (!defined $co{'tree'}) {
3403 return;
3405 $co{'parents'} = \@parents;
3406 $co{'parent'} = $parents[0];
3408 foreach my $title (@commit_lines) {
3409 $title =~ s/^ //;
3410 if ($title ne "") {
3411 $co{'title'} = chop_str($title, 80, 5);
3412 # remove leading stuff of merges to make the interesting part visible
3413 if (length($title) > 50) {
3414 $title =~ s/^Automatic //;
3415 $title =~ s/^merge (of|with) /Merge ... /i;
3416 if (length($title) > 50) {
3417 $title =~ s/(http|rsync):\/\///;
3419 if (length($title) > 50) {
3420 $title =~ s/(master|www|rsync)\.//;
3422 if (length($title) > 50) {
3423 $title =~ s/kernel.org:?//;
3425 if (length($title) > 50) {
3426 $title =~ s/\/pub\/scm//;
3429 $co{'title_short'} = chop_str($title, 50, 5);
3430 last;
3433 if (! defined $co{'title'} || $co{'title'} eq "") {
3434 $co{'title'} = $co{'title_short'} = '(no commit message)';
3436 # remove added spaces
3437 foreach my $line (@commit_lines) {
3438 $line =~ s/^ //;
3440 $co{'comment'} = \@commit_lines;
3442 my $age = time - $co{'committer_epoch'};
3443 $co{'age'} = $age;
3444 $co{'age_string'} = age_string($age);
3445 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3446 if ($age > 60*60*24*7*2) {
3447 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3448 $co{'age_string_age'} = $co{'age_string'};
3449 } else {
3450 $co{'age_string_date'} = $co{'age_string'};
3451 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3453 return %co;
3456 sub parse_commit {
3457 my ($commit_id) = @_;
3458 my %co;
3460 local $/ = "\0";
3462 open my $fd, "-|", git_cmd(), "rev-list",
3463 "--parents",
3464 "--header",
3465 "--max-count=1",
3466 $commit_id,
3467 "--",
3468 or die_error(500, "Open git-rev-list failed");
3469 %co = parse_commit_text(<$fd>, 1);
3470 close $fd;
3472 return %co;
3475 sub parse_commits {
3476 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3477 my @cos;
3479 $maxcount ||= 1;
3480 $skip ||= 0;
3482 local $/ = "\0";
3484 open my $fd, "-|", git_cmd(), "rev-list",
3485 "--header",
3486 @args,
3487 ("--max-count=" . $maxcount),
3488 ("--skip=" . $skip),
3489 @extra_options,
3490 $commit_id,
3491 "--",
3492 ($filename ? ($filename) : ())
3493 or die_error(500, "Open git-rev-list failed");
3494 while (my $line = <$fd>) {
3495 my %co = parse_commit_text($line);
3496 push @cos, \%co;
3498 close $fd;
3500 return wantarray ? @cos : \@cos;
3503 # parse line of git-diff-tree "raw" output
3504 sub parse_difftree_raw_line {
3505 my $line = shift;
3506 my %res;
3508 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3509 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3510 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3511 $res{'from_mode'} = $1;
3512 $res{'to_mode'} = $2;
3513 $res{'from_id'} = $3;
3514 $res{'to_id'} = $4;
3515 $res{'status'} = $5;
3516 $res{'similarity'} = $6;
3517 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3518 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3519 } else {
3520 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3523 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3524 # combined diff (for merge commit)
3525 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3526 $res{'nparents'} = length($1);
3527 $res{'from_mode'} = [ split(' ', $2) ];
3528 $res{'to_mode'} = pop @{$res{'from_mode'}};
3529 $res{'from_id'} = [ split(' ', $3) ];
3530 $res{'to_id'} = pop @{$res{'from_id'}};
3531 $res{'status'} = [ split('', $4) ];
3532 $res{'to_file'} = unquote($5);
3534 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3535 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3536 $res{'commit'} = $1;
3539 return wantarray ? %res : \%res;
3542 # wrapper: return parsed line of git-diff-tree "raw" output
3543 # (the argument might be raw line, or parsed info)
3544 sub parsed_difftree_line {
3545 my $line_or_ref = shift;
3547 if (ref($line_or_ref) eq "HASH") {
3548 # pre-parsed (or generated by hand)
3549 return $line_or_ref;
3550 } else {
3551 return parse_difftree_raw_line($line_or_ref);
3555 # parse line of git-ls-tree output
3556 sub parse_ls_tree_line {
3557 my $line = shift;
3558 my %opts = @_;
3559 my %res;
3561 if ($opts{'-l'}) {
3562 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3563 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3565 $res{'mode'} = $1;
3566 $res{'type'} = $2;
3567 $res{'hash'} = $3;
3568 $res{'size'} = $4;
3569 if ($opts{'-z'}) {
3570 $res{'name'} = $5;
3571 } else {
3572 $res{'name'} = unquote($5);
3574 } else {
3575 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3576 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3578 $res{'mode'} = $1;
3579 $res{'type'} = $2;
3580 $res{'hash'} = $3;
3581 if ($opts{'-z'}) {
3582 $res{'name'} = $4;
3583 } else {
3584 $res{'name'} = unquote($4);
3588 return wantarray ? %res : \%res;
3591 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3592 sub parse_from_to_diffinfo {
3593 my ($diffinfo, $from, $to, @parents) = @_;
3595 if ($diffinfo->{'nparents'}) {
3596 # combined diff
3597 $from->{'file'} = [];
3598 $from->{'href'} = [];
3599 fill_from_file_info($diffinfo, @parents)
3600 unless exists $diffinfo->{'from_file'};
3601 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3602 $from->{'file'}[$i] =
3603 defined $diffinfo->{'from_file'}[$i<