gitweb: detect correct type for blobs < 512 bytes
[git/gitweb.git] / gitweb / gitweb.perl
blob8fa4637c5faaa33ed94ba983a3562946ad0c4bca
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 File::Spec;
21 use Time::HiRes qw(gettimeofday tv_interval);
22 binmode STDOUT, ':utf8';
24 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
25 eval 'sub CGI::multi_param { CGI::param(@_) }'
28 our $t0 = [ gettimeofday() ];
29 our $number_of_git_cmds = 0;
31 BEGIN {
32 CGI->compile() if $ENV{'MOD_PERL'};
35 our $version = "++GIT_VERSION++";
37 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
38 sub evaluate_uri {
39 our $cgi;
41 our $my_url = $cgi->url();
42 our $my_uri = $cgi->url(-absolute => 1);
44 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
45 # needed and used only for URLs with nonempty PATH_INFO
46 our $base_url = $my_url;
48 # When the script is used as DirectoryIndex, the URL does not contain the name
49 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
50 # have to do it ourselves. We make $path_info global because it's also used
51 # later on.
53 # Another issue with the script being the DirectoryIndex is that the resulting
54 # $my_url data is not the full script URL: this is good, because we want
55 # generated links to keep implying the script name if it wasn't explicitly
56 # indicated in the URL we're handling, but it means that $my_url cannot be used
57 # as base URL.
58 # Therefore, if we needed to strip PATH_INFO, then we know that we have
59 # to build the base URL ourselves:
60 our $path_info = decode_utf8($ENV{"PATH_INFO"});
61 if ($path_info) {
62 # $path_info has already been URL-decoded by the web server, but
63 # $my_url and $my_uri have not. URL-decode them so we can properly
64 # strip $path_info.
65 $my_url = unescape($my_url);
66 $my_uri = unescape($my_uri);
67 if ($my_url =~ s,\Q$path_info\E$,, &&
68 $my_uri =~ s,\Q$path_info\E$,, &&
69 defined $ENV{'SCRIPT_NAME'}) {
70 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
74 # target of the home link on top of all pages
75 our $home_link = $my_uri || "/";
78 # core git executable to use
79 # this can just be "git" if your webserver has a sensible PATH
80 our $GIT = "++GIT_BINDIR++/git";
82 # absolute fs-path which will be prepended to the project path
83 #our $projectroot = "/pub/scm";
84 our $projectroot = "++GITWEB_PROJECTROOT++";
86 # fs traversing limit for getting project list
87 # the number is relative to the projectroot
88 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
90 # string of the home link on top of all pages
91 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
93 # extra breadcrumbs preceding the home link
94 our @extra_breadcrumbs = ();
96 # name of your site or organization to appear in page titles
97 # replace this with something more descriptive for clearer bookmarks
98 our $site_name = "++GITWEB_SITENAME++"
99 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
101 # html snippet to include in the <head> section of each page
102 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
103 # filename of html text to include at top of each page
104 our $site_header = "++GITWEB_SITE_HEADER++";
105 # html text to include at home page
106 our $home_text = "++GITWEB_HOMETEXT++";
107 # filename of html text to include at bottom of each page
108 our $site_footer = "++GITWEB_SITE_FOOTER++";
110 # URI of stylesheets
111 our @stylesheets = ("++GITWEB_CSS++");
112 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
113 our $stylesheet = undef;
114 # URI of GIT logo (72x27 size)
115 our $logo = "++GITWEB_LOGO++";
116 # URI of GIT favicon, assumed to be image/png type
117 our $favicon = "++GITWEB_FAVICON++";
118 # URI of gitweb.js (JavaScript code for gitweb)
119 our $javascript = "++GITWEB_JS++";
121 # URI and label (title) of GIT logo link
122 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
123 #our $logo_label = "git documentation";
124 our $logo_url = "http://git-scm.com/";
125 our $logo_label = "git homepage";
127 # source of projects list
128 our $projects_list = "++GITWEB_LIST++";
130 # the width (in characters) of the projects list "Description" column
131 our $projects_list_description_width = 25;
133 # group projects by category on the projects list
134 # (enabled if this variable evaluates to true)
135 our $projects_list_group_categories = 0;
137 # default category if none specified
138 # (leave the empty string for no category)
139 our $project_list_default_category = "";
141 # default order of projects list
142 # valid values are none, project, descr, owner, and age
143 our $default_projects_order = "project";
145 # show repository only if this file exists
146 # (only effective if this variable evaluates to true)
147 our $export_ok = "++GITWEB_EXPORT_OK++";
149 # don't generate age column on the projects list page
150 our $omit_age_column = 0;
152 # don't generate information about owners of repositories
153 our $omit_owner=0;
155 # show repository only if this subroutine returns true
156 # when given the path to the project, for example:
157 # sub { return -e "$_[0]/git-daemon-export-ok"; }
158 our $export_auth_hook = undef;
160 # only allow viewing of repositories also shown on the overview page
161 our $strict_export = "++GITWEB_STRICT_EXPORT++";
163 # list of git base URLs used for URL to where fetch project from,
164 # i.e. full URL is "$git_base_url/$project"
165 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
167 # default blob_plain mimetype and default charset for text/plain blob
168 our $default_blob_plain_mimetype = 'application/octet-stream';
169 our $default_text_plain_charset = undef;
171 # file to use for guessing MIME types before trying /etc/mime.types
172 # (relative to the current git repository)
173 our $mimetypes_file = undef;
175 # assume this charset if line contains non-UTF-8 characters;
176 # it should be valid encoding (see Encoding::Supported(3pm) for list),
177 # for which encoding all byte sequences are valid, for example
178 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
179 # could be even 'utf-8' for the old behavior)
180 our $fallback_encoding = 'latin1';
182 # rename detection options for git-diff and git-diff-tree
183 # - default is '-M', with the cost proportional to
184 # (number of removed files) * (number of new files).
185 # - more costly is '-C' (which implies '-M'), with the cost proportional to
186 # (number of changed files + number of removed files) * (number of new files)
187 # - even more costly is '-C', '--find-copies-harder' with cost
188 # (number of files in the original tree) * (number of new files)
189 # - one might want to include '-B' option, e.g. '-B', '-M'
190 our @diff_opts = ('-M'); # taken from git_commit
192 # Disables features that would allow repository owners to inject script into
193 # the gitweb domain.
194 our $prevent_xss = 0;
196 # Path to a POSIX shell. Needed to run $highlight_bin and a snapshot compressor.
197 # Only used when highlight is enabled or snapshots with compressors are enabled.
198 our $posix_shell_bin = "++POSIX_SHELL_BIN++";
200 # Path to the highlight executable to use (must be the one from
201 # http://www.andre-simon.de due to assumptions about parameters and output).
202 # Useful if highlight is not installed on your webserver's PATH.
203 # [Default: highlight]
204 our $highlight_bin = "++HIGHLIGHT_BIN++";
206 # information about snapshot formats that gitweb is capable of serving
207 our %known_snapshot_formats = (
208 # name => {
209 # 'display' => display name,
210 # 'type' => mime type,
211 # 'suffix' => filename suffix,
212 # 'format' => --format for git-archive,
213 # 'compressor' => [compressor command and arguments]
214 # (array reference, optional)
215 # 'disabled' => boolean (optional)}
217 'tgz' => {
218 'display' => 'tar.gz',
219 'type' => 'application/x-gzip',
220 'suffix' => '.tar.gz',
221 'format' => 'tar',
222 'compressor' => ['gzip', '-n']},
224 'tbz2' => {
225 'display' => 'tar.bz2',
226 'type' => 'application/x-bzip2',
227 'suffix' => '.tar.bz2',
228 'format' => 'tar',
229 'compressor' => ['bzip2']},
231 'txz' => {
232 'display' => 'tar.xz',
233 'type' => 'application/x-xz',
234 'suffix' => '.tar.xz',
235 'format' => 'tar',
236 'compressor' => ['xz'],
237 'disabled' => 1},
239 'zip' => {
240 'display' => 'zip',
241 'type' => 'application/x-zip',
242 'suffix' => '.zip',
243 'format' => 'zip'},
246 # Aliases so we understand old gitweb.snapshot values in repository
247 # configuration.
248 our %known_snapshot_format_aliases = (
249 'gzip' => 'tgz',
250 'bzip2' => 'tbz2',
251 'xz' => 'txz',
253 # backward compatibility: legacy gitweb config support
254 'x-gzip' => undef, 'gz' => undef,
255 'x-bzip2' => undef, 'bz2' => undef,
256 'x-zip' => undef, '' => undef,
259 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
260 # are changed, it may be appropriate to change these values too via
261 # $GITWEB_CONFIG.
262 our %avatar_size = (
263 'default' => 16,
264 'double' => 32
267 # Used to set the maximum load that we will still respond to gitweb queries.
268 # If server load exceed this value then return "503 server busy" error.
269 # If gitweb cannot determined server load, it is taken to be 0.
270 # Leave it undefined (or set to 'undef') to turn off load checking.
271 our $maxload = 300;
273 # configuration for 'highlight' (http://www.andre-simon.de/)
274 # match by basename
275 our %highlight_basename = (
276 #'Program' => 'py',
277 #'Library' => 'py',
278 'SConstruct' => 'py', # SCons equivalent of Makefile
279 'Makefile' => 'make',
281 # match by extension
282 our %highlight_ext = (
283 # main extensions, defining name of syntax;
284 # see files in /usr/share/highlight/langDefs/ directory
285 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
286 # alternate extensions, see /etc/highlight/filetypes.conf
287 (map { $_ => 'c' } qw(c h)),
288 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
289 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
290 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
291 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
292 (map { $_ => 'make'} qw(make mak mk)),
293 (map { $_ => 'xml' } qw(xml xhtml html htm)),
296 # You define site-wide feature defaults here; override them with
297 # $GITWEB_CONFIG as necessary.
298 our %feature = (
299 # feature => {
300 # 'sub' => feature-sub (subroutine),
301 # 'override' => allow-override (boolean),
302 # 'default' => [ default options...] (array reference)}
304 # if feature is overridable (it means that allow-override has true value),
305 # then feature-sub will be called with default options as parameters;
306 # return value of feature-sub indicates if to enable specified feature
308 # if there is no 'sub' key (no feature-sub), then feature cannot be
309 # overridden
311 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
312 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
313 # is enabled
315 # Enable the 'blame' blob view, showing the last commit that modified
316 # each line in the file. This can be very CPU-intensive.
318 # To enable system wide have in $GITWEB_CONFIG
319 # $feature{'blame'}{'default'} = [1];
320 # To have project specific config enable override in $GITWEB_CONFIG
321 # $feature{'blame'}{'override'} = 1;
322 # and in project config gitweb.blame = 0|1;
323 'blame' => {
324 'sub' => sub { feature_bool('blame', @_) },
325 'override' => 0,
326 'default' => [0]},
328 # Enable the 'snapshot' link, providing a compressed archive of any
329 # tree. This can potentially generate high traffic if you have large
330 # project.
332 # Value is a list of formats defined in %known_snapshot_formats that
333 # you wish to offer.
334 # To disable system wide have in $GITWEB_CONFIG
335 # $feature{'snapshot'}{'default'} = [];
336 # To have project specific config enable override in $GITWEB_CONFIG
337 # $feature{'snapshot'}{'override'} = 1;
338 # and in project config, a comma-separated list of formats or "none"
339 # to disable. Example: gitweb.snapshot = tbz2,zip;
340 'snapshot' => {
341 'sub' => \&feature_snapshot,
342 'override' => 0,
343 'default' => ['tgz']},
345 # Enable text search, which will list the commits which match author,
346 # committer or commit text to a given string. Enabled by default.
347 # Project specific override is not supported.
349 # Note that this controls all search features, which means that if
350 # it is disabled, then 'grep' and 'pickaxe' search would also be
351 # disabled.
352 'search' => {
353 'override' => 0,
354 'default' => [1]},
356 # Enable grep search, which will list the files in currently selected
357 # tree containing the given string. Enabled by default. This can be
358 # potentially CPU-intensive, of course.
359 # Note that you need to have 'search' feature enabled too.
361 # To enable system wide have in $GITWEB_CONFIG
362 # $feature{'grep'}{'default'} = [1];
363 # To have project specific config enable override in $GITWEB_CONFIG
364 # $feature{'grep'}{'override'} = 1;
365 # and in project config gitweb.grep = 0|1;
366 'grep' => {
367 'sub' => sub { feature_bool('grep', @_) },
368 'override' => 0,
369 'default' => [1]},
371 # Enable the pickaxe search, which will list the commits that modified
372 # a given string in a file. This can be practical and quite faster
373 # alternative to 'blame', but still potentially CPU-intensive.
374 # Note that you need to have 'search' feature enabled too.
376 # To enable system wide have in $GITWEB_CONFIG
377 # $feature{'pickaxe'}{'default'} = [1];
378 # To have project specific config enable override in $GITWEB_CONFIG
379 # $feature{'pickaxe'}{'override'} = 1;
380 # and in project config gitweb.pickaxe = 0|1;
381 'pickaxe' => {
382 'sub' => sub { feature_bool('pickaxe', @_) },
383 'override' => 0,
384 'default' => [1]},
386 # Enable showing size of blobs in a 'tree' view, in a separate
387 # column, similar to what 'ls -l' does. This cost a bit of IO.
389 # To disable system wide have in $GITWEB_CONFIG
390 # $feature{'show-sizes'}{'default'} = [0];
391 # To have project specific config enable override in $GITWEB_CONFIG
392 # $feature{'show-sizes'}{'override'} = 1;
393 # and in project config gitweb.showsizes = 0|1;
394 'show-sizes' => {
395 'sub' => sub { feature_bool('showsizes', @_) },
396 'override' => 0,
397 'default' => [1]},
399 # Make gitweb use an alternative format of the URLs which can be
400 # more readable and natural-looking: project name is embedded
401 # directly in the path and the query string contains other
402 # auxiliary information. All gitweb installations recognize
403 # URL in either format; this configures in which formats gitweb
404 # generates links.
406 # To enable system wide have in $GITWEB_CONFIG
407 # $feature{'pathinfo'}{'default'} = [1];
408 # Project specific override is not supported.
410 # Note that you will need to change the default location of CSS,
411 # favicon, logo and possibly other files to an absolute URL. Also,
412 # if gitweb.cgi serves as your indexfile, you will need to force
413 # $my_uri to contain the script name in your $GITWEB_CONFIG.
414 'pathinfo' => {
415 'override' => 0,
416 'default' => [0]},
418 # Make gitweb consider projects in project root subdirectories
419 # to be forks of existing projects. Given project $projname.git,
420 # projects matching $projname/*.git will not be shown in the main
421 # projects list, instead a '+' mark will be added to $projname
422 # there and a 'forks' view will be enabled for the project, listing
423 # all the forks. If project list is taken from a file, forks have
424 # to be listed after the main project.
426 # To enable system wide have in $GITWEB_CONFIG
427 # $feature{'forks'}{'default'} = [1];
428 # Project specific override is not supported.
429 'forks' => {
430 'override' => 0,
431 'default' => [0]},
433 # Insert custom links to the action bar of all project pages.
434 # This enables you mainly to link to third-party scripts integrating
435 # into gitweb; e.g. git-browser for graphical history representation
436 # or custom web-based repository administration interface.
438 # The 'default' value consists of a list of triplets in the form
439 # (label, link, position) where position is the label after which
440 # to insert the link and link is a format string where %n expands
441 # to the project name, %f to the project path within the filesystem,
442 # %h to the current hash (h gitweb parameter) and %b to the current
443 # hash base (hb gitweb parameter); %% expands to %.
445 # To enable system wide have in $GITWEB_CONFIG e.g.
446 # $feature{'actions'}{'default'} = [('graphiclog',
447 # '/git-browser/by-commit.html?r=%n', 'summary')];
448 # Project specific override is not supported.
449 'actions' => {
450 'override' => 0,
451 'default' => []},
453 # Allow gitweb scan project content tags of project repository,
454 # and display the popular Web 2.0-ish "tag cloud" near the projects
455 # list. Note that this is something COMPLETELY different from the
456 # normal Git tags.
458 # gitweb by itself can show existing tags, but it does not handle
459 # tagging itself; you need to do it externally, outside gitweb.
460 # The format is described in git_get_project_ctags() subroutine.
461 # You may want to install the HTML::TagCloud Perl module to get
462 # a pretty tag cloud instead of just a list of tags.
464 # To enable system wide have in $GITWEB_CONFIG
465 # $feature{'ctags'}{'default'} = [1];
466 # Project specific override is not supported.
468 # In the future whether ctags editing is enabled might depend
469 # on the value, but using 1 should always mean no editing of ctags.
470 'ctags' => {
471 'override' => 0,
472 'default' => [0]},
474 # The maximum number of patches in a patchset generated in patch
475 # view. Set this to 0 or undef to disable patch view, or to a
476 # negative number to remove any limit.
478 # To disable system wide have in $GITWEB_CONFIG
479 # $feature{'patches'}{'default'} = [0];
480 # To have project specific config enable override in $GITWEB_CONFIG
481 # $feature{'patches'}{'override'} = 1;
482 # and in project config gitweb.patches = 0|n;
483 # where n is the maximum number of patches allowed in a patchset.
484 'patches' => {
485 'sub' => \&feature_patches,
486 'override' => 0,
487 'default' => [16]},
489 # Avatar support. When this feature is enabled, views such as
490 # shortlog or commit will display an avatar associated with
491 # the email of the committer(s) and/or author(s).
493 # Currently available providers are gravatar and picon.
494 # If an unknown provider is specified, the feature is disabled.
496 # Gravatar depends on Digest::MD5.
497 # Picon currently relies on the indiana.edu database.
499 # To enable system wide have in $GITWEB_CONFIG
500 # $feature{'avatar'}{'default'} = ['<provider>'];
501 # where <provider> is either gravatar or picon.
502 # To have project specific config enable override in $GITWEB_CONFIG
503 # $feature{'avatar'}{'override'} = 1;
504 # and in project config gitweb.avatar = <provider>;
505 'avatar' => {
506 'sub' => \&feature_avatar,
507 'override' => 0,
508 'default' => ['']},
510 # Enable displaying how much time and how many git commands
511 # it took to generate and display page. Disabled by default.
512 # Project specific override is not supported.
513 'timed' => {
514 'override' => 0,
515 'default' => [0]},
517 # Enable turning some links into links to actions which require
518 # JavaScript to run (like 'blame_incremental'). Not enabled by
519 # default. Project specific override is currently not supported.
520 'javascript-actions' => {
521 'override' => 0,
522 'default' => [0]},
524 # Enable and configure ability to change common timezone for dates
525 # in gitweb output via JavaScript. Enabled by default.
526 # Project specific override is not supported.
527 'javascript-timezone' => {
528 'override' => 0,
529 'default' => [
530 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
531 # or undef to turn off this feature
532 'gitweb_tz', # name of cookie where to store selected timezone
533 'datetime', # CSS class used to mark up dates for manipulation
536 # Syntax highlighting support. This is based on Daniel Svensson's
537 # and Sham Chukoury's work in gitweb-xmms2.git.
538 # It requires the 'highlight' program present in $PATH,
539 # and therefore is disabled by default.
541 # To enable system wide have in $GITWEB_CONFIG
542 # $feature{'highlight'}{'default'} = [1];
544 'highlight' => {
545 'sub' => sub { feature_bool('highlight', @_) },
546 'override' => 0,
547 'default' => [0]},
549 # Enable displaying of remote heads in the heads list
551 # To enable system wide have in $GITWEB_CONFIG
552 # $feature{'remote_heads'}{'default'} = [1];
553 # To have project specific config enable override in $GITWEB_CONFIG
554 # $feature{'remote_heads'}{'override'} = 1;
555 # and in project config gitweb.remoteheads = 0|1;
556 'remote_heads' => {
557 'sub' => sub { feature_bool('remote_heads', @_) },
558 'override' => 0,
559 'default' => [0]},
561 # Enable showing branches under other refs in addition to heads
563 # To set system wide extra branch refs have in $GITWEB_CONFIG
564 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
565 # To have project specific config enable override in $GITWEB_CONFIG
566 # $feature{'extra-branch-refs'}{'override'} = 1;
567 # and in project config gitweb.extrabranchrefs = dirs of choice
568 # Every directory is separated with whitespace.
570 'extra-branch-refs' => {
571 'sub' => \&feature_extra_branch_refs,
572 'override' => 0,
573 'default' => []},
576 sub gitweb_get_feature {
577 my ($name) = @_;
578 return unless exists $feature{$name};
579 my ($sub, $override, @defaults) = (
580 $feature{$name}{'sub'},
581 $feature{$name}{'override'},
582 @{$feature{$name}{'default'}});
583 # project specific override is possible only if we have project
584 our $git_dir; # global variable, declared later
585 if (!$override || !defined $git_dir) {
586 return @defaults;
588 if (!defined $sub) {
589 warn "feature $name is not overridable";
590 return @defaults;
592 return $sub->(@defaults);
595 # A wrapper to check if a given feature is enabled.
596 # With this, you can say
598 # my $bool_feat = gitweb_check_feature('bool_feat');
599 # gitweb_check_feature('bool_feat') or somecode;
601 # instead of
603 # my ($bool_feat) = gitweb_get_feature('bool_feat');
604 # (gitweb_get_feature('bool_feat'))[0] or somecode;
606 sub gitweb_check_feature {
607 return (gitweb_get_feature(@_))[0];
611 sub feature_bool {
612 my $key = shift;
613 my ($val) = git_get_project_config($key, '--bool');
615 if (!defined $val) {
616 return ($_[0]);
617 } elsif ($val eq 'true') {
618 return (1);
619 } elsif ($val eq 'false') {
620 return (0);
624 sub feature_snapshot {
625 my (@fmts) = @_;
627 my ($val) = git_get_project_config('snapshot');
629 if ($val) {
630 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
633 return @fmts;
636 sub feature_patches {
637 my @val = (git_get_project_config('patches', '--int'));
639 if (@val) {
640 return @val;
643 return ($_[0]);
646 sub feature_avatar {
647 my @val = (git_get_project_config('avatar'));
649 return @val ? @val : @_;
652 sub feature_extra_branch_refs {
653 my (@branch_refs) = @_;
654 my $values = git_get_project_config('extrabranchrefs');
656 if ($values) {
657 $values = config_to_multi ($values);
658 @branch_refs = ();
659 foreach my $value (@{$values}) {
660 push @branch_refs, split /\s+/, $value;
664 return @branch_refs;
667 # checking HEAD file with -e is fragile if the repository was
668 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
669 # and then pruned.
670 sub check_head_link {
671 my ($dir) = @_;
672 my $headfile = "$dir/HEAD";
673 return ((-e $headfile) ||
674 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
677 sub check_export_ok {
678 my ($dir) = @_;
679 return (check_head_link($dir) &&
680 (!$export_ok || -e "$dir/$export_ok") &&
681 (!$export_auth_hook || $export_auth_hook->($dir)));
684 # process alternate names for backward compatibility
685 # filter out unsupported (unknown) snapshot formats
686 sub filter_snapshot_fmts {
687 my @fmts = @_;
689 @fmts = map {
690 exists $known_snapshot_format_aliases{$_} ?
691 $known_snapshot_format_aliases{$_} : $_} @fmts;
692 @fmts = grep {
693 exists $known_snapshot_formats{$_} &&
694 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
697 sub filter_and_validate_refs {
698 my @refs = @_;
699 my %unique_refs = ();
701 foreach my $ref (@refs) {
702 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
703 # 'heads' are added implicitly in get_branch_refs().
704 $unique_refs{$ref} = 1 if ($ref ne 'heads');
706 return sort keys %unique_refs;
709 # If it is set to code reference, it is code that it is to be run once per
710 # request, allowing updating configurations that change with each request,
711 # while running other code in config file only once.
713 # Otherwise, if it is false then gitweb would process config file only once;
714 # if it is true then gitweb config would be run for each request.
715 our $per_request_config = 1;
717 # read and parse gitweb config file given by its parameter.
718 # returns true on success, false on recoverable error, allowing
719 # to chain this subroutine, using first file that exists.
720 # dies on errors during parsing config file, as it is unrecoverable.
721 sub read_config_file {
722 my $filename = shift;
723 return unless defined $filename;
724 # die if there are errors parsing config file
725 if (-e $filename) {
726 do $filename;
727 die $@ if $@;
728 return 1;
730 return;
733 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
734 sub evaluate_gitweb_config {
735 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
736 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
737 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
739 # Protect against duplications of file names, to not read config twice.
740 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
741 # there possibility of duplication of filename there doesn't matter.
742 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
743 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
745 # Common system-wide settings for convenience.
746 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
747 read_config_file($GITWEB_CONFIG_COMMON);
749 # Use first config file that exists. This means use the per-instance
750 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
751 read_config_file($GITWEB_CONFIG) and return;
752 read_config_file($GITWEB_CONFIG_SYSTEM);
755 # Get loadavg of system, to compare against $maxload.
756 # Currently it requires '/proc/loadavg' present to get loadavg;
757 # if it is not present it returns 0, which means no load checking.
758 sub get_loadavg {
759 if( -e '/proc/loadavg' ){
760 open my $fd, '<', '/proc/loadavg'
761 or return 0;
762 my @load = split(/\s+/, scalar <$fd>);
763 close $fd;
765 # The first three columns measure CPU and IO utilization of the last one,
766 # five, and 10 minute periods. The fourth column shows the number of
767 # currently running processes and the total number of processes in the m/n
768 # format. The last column displays the last process ID used.
769 return $load[0] || 0;
771 # additional checks for load average should go here for things that don't export
772 # /proc/loadavg
774 return 0;
777 # version of the core git binary
778 our $git_version;
779 sub evaluate_git_version {
780 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
781 $number_of_git_cmds++;
784 sub check_loadavg {
785 if (defined $maxload && get_loadavg() > $maxload) {
786 die_error(503, "The load average on the server is too high");
790 # ======================================================================
791 # input validation and dispatch
793 # input parameters can be collected from a variety of sources (presently, CGI
794 # and PATH_INFO), so we define an %input_params hash that collects them all
795 # together during validation: this allows subsequent uses (e.g. href()) to be
796 # agnostic of the parameter origin
798 our %input_params = ();
800 # input parameters are stored with the long parameter name as key. This will
801 # also be used in the href subroutine to convert parameters to their CGI
802 # equivalent, and since the href() usage is the most frequent one, we store
803 # the name -> CGI key mapping here, instead of the reverse.
805 # XXX: Warning: If you touch this, check the search form for updating,
806 # too.
808 our @cgi_param_mapping = (
809 project => "p",
810 action => "a",
811 file_name => "f",
812 file_parent => "fp",
813 hash => "h",
814 hash_parent => "hp",
815 hash_base => "hb",
816 hash_parent_base => "hpb",
817 page => "pg",
818 order => "o",
819 searchtext => "s",
820 searchtype => "st",
821 snapshot_format => "sf",
822 extra_options => "opt",
823 search_use_regexp => "sr",
824 ctag => "by_tag",
825 diff_style => "ds",
826 project_filter => "pf",
827 # this must be last entry (for manipulation from JavaScript)
828 javascript => "js"
830 our %cgi_param_mapping = @cgi_param_mapping;
832 # we will also need to know the possible actions, for validation
833 our %actions = (
834 "blame" => \&git_blame,
835 "blame_incremental" => \&git_blame_incremental,
836 "blame_data" => \&git_blame_data,
837 "blobdiff" => \&git_blobdiff,
838 "blobdiff_plain" => \&git_blobdiff_plain,
839 "blob" => \&git_blob,
840 "blob_plain" => \&git_blob_plain,
841 "commitdiff" => \&git_commitdiff,
842 "commitdiff_plain" => \&git_commitdiff_plain,
843 "commit" => \&git_commit,
844 "forks" => \&git_forks,
845 "heads" => \&git_heads,
846 "history" => \&git_history,
847 "log" => \&git_log,
848 "patch" => \&git_patch,
849 "patches" => \&git_patches,
850 "remotes" => \&git_remotes,
851 "rss" => \&git_rss,
852 "atom" => \&git_atom,
853 "search" => \&git_search,
854 "search_help" => \&git_search_help,
855 "shortlog" => \&git_shortlog,
856 "summary" => \&git_summary,
857 "tag" => \&git_tag,
858 "tags" => \&git_tags,
859 "tree" => \&git_tree,
860 "snapshot" => \&git_snapshot,
861 "object" => \&git_object,
862 # those below don't need $project
863 "opml" => \&git_opml,
864 "project_list" => \&git_project_list,
865 "project_index" => \&git_project_index,
868 # finally, we have the hash of allowed extra_options for the commands that
869 # allow them
870 our %allowed_options = (
871 "--no-merges" => [ qw(rss atom log shortlog history) ],
874 # fill %input_params with the CGI parameters. All values except for 'opt'
875 # should be single values, but opt can be an array. We should probably
876 # build an array of parameters that can be multi-valued, but since for the time
877 # being it's only this one, we just single it out
878 sub evaluate_query_params {
879 our $cgi;
881 while (my ($name, $symbol) = each %cgi_param_mapping) {
882 if ($symbol eq 'opt') {
883 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
884 } else {
885 $input_params{$name} = decode_utf8($cgi->param($symbol));
890 # now read PATH_INFO and update the parameter list for missing parameters
891 sub evaluate_path_info {
892 return if defined $input_params{'project'};
893 return if !$path_info;
894 $path_info =~ s,^/+,,;
895 return if !$path_info;
897 # find which part of PATH_INFO is project
898 my $project = $path_info;
899 $project =~ s,/+$,,;
900 while ($project && !check_head_link("$projectroot/$project")) {
901 $project =~ s,/*[^/]*$,,;
903 return unless $project;
904 $input_params{'project'} = $project;
906 # do not change any parameters if an action is given using the query string
907 return if $input_params{'action'};
908 $path_info =~ s,^\Q$project\E/*,,;
910 # next, check if we have an action
911 my $action = $path_info;
912 $action =~ s,/.*$,,;
913 if (exists $actions{$action}) {
914 $path_info =~ s,^$action/*,,;
915 $input_params{'action'} = $action;
918 # list of actions that want hash_base instead of hash, but can have no
919 # pathname (f) parameter
920 my @wants_base = (
921 'tree',
922 'history',
925 # we want to catch, among others
926 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
927 my ($parentrefname, $parentpathname, $refname, $pathname) =
928 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
930 # first, analyze the 'current' part
931 if (defined $pathname) {
932 # we got "branch:filename" or "branch:dir/"
933 # we could use git_get_type(branch:pathname), but:
934 # - it needs $git_dir
935 # - it does a git() call
936 # - the convention of terminating directories with a slash
937 # makes it superfluous
938 # - embedding the action in the PATH_INFO would make it even
939 # more superfluous
940 $pathname =~ s,^/+,,;
941 if (!$pathname || substr($pathname, -1) eq "/") {
942 $input_params{'action'} ||= "tree";
943 $pathname =~ s,/$,,;
944 } else {
945 # the default action depends on whether we had parent info
946 # or not
947 if ($parentrefname) {
948 $input_params{'action'} ||= "blobdiff_plain";
949 } else {
950 $input_params{'action'} ||= "blob_plain";
953 $input_params{'hash_base'} ||= $refname;
954 $input_params{'file_name'} ||= $pathname;
955 } elsif (defined $refname) {
956 # we got "branch". In this case we have to choose if we have to
957 # set hash or hash_base.
959 # Most of the actions without a pathname only want hash to be
960 # set, except for the ones specified in @wants_base that want
961 # hash_base instead. It should also be noted that hand-crafted
962 # links having 'history' as an action and no pathname or hash
963 # set will fail, but that happens regardless of PATH_INFO.
964 if (defined $parentrefname) {
965 # if there is parent let the default be 'shortlog' action
966 # (for http://git.example.com/repo.git/A..B links); if there
967 # is no parent, dispatch will detect type of object and set
968 # action appropriately if required (if action is not set)
969 $input_params{'action'} ||= "shortlog";
971 if ($input_params{'action'} &&
972 grep { $_ eq $input_params{'action'} } @wants_base) {
973 $input_params{'hash_base'} ||= $refname;
974 } else {
975 $input_params{'hash'} ||= $refname;
979 # next, handle the 'parent' part, if present
980 if (defined $parentrefname) {
981 # a missing pathspec defaults to the 'current' filename, allowing e.g.
982 # someproject/blobdiff/oldrev..newrev:/filename
983 if ($parentpathname) {
984 $parentpathname =~ s,^/+,,;
985 $parentpathname =~ s,/$,,;
986 $input_params{'file_parent'} ||= $parentpathname;
987 } else {
988 $input_params{'file_parent'} ||= $input_params{'file_name'};
990 # we assume that hash_parent_base is wanted if a path was specified,
991 # or if the action wants hash_base instead of hash
992 if (defined $input_params{'file_parent'} ||
993 grep { $_ eq $input_params{'action'} } @wants_base) {
994 $input_params{'hash_parent_base'} ||= $parentrefname;
995 } else {
996 $input_params{'hash_parent'} ||= $parentrefname;
1000 # for the snapshot action, we allow URLs in the form
1001 # $project/snapshot/$hash.ext
1002 # where .ext determines the snapshot and gets removed from the
1003 # passed $refname to provide the $hash.
1005 # To be able to tell that $refname includes the format extension, we
1006 # require the following two conditions to be satisfied:
1007 # - the hash input parameter MUST have been set from the $refname part
1008 # of the URL (i.e. they must be equal)
1009 # - the snapshot format MUST NOT have been defined already (e.g. from
1010 # CGI parameter sf)
1011 # It's also useless to try any matching unless $refname has a dot,
1012 # so we check for that too
1013 if (defined $input_params{'action'} &&
1014 $input_params{'action'} eq 'snapshot' &&
1015 defined $refname && index($refname, '.') != -1 &&
1016 $refname eq $input_params{'hash'} &&
1017 !defined $input_params{'snapshot_format'}) {
1018 # We loop over the known snapshot formats, checking for
1019 # extensions. Allowed extensions are both the defined suffix
1020 # (which includes the initial dot already) and the snapshot
1021 # format key itself, with a prepended dot
1022 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1023 my $hash = $refname;
1024 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1025 next;
1027 my $sfx = $1;
1028 # a valid suffix was found, so set the snapshot format
1029 # and reset the hash parameter
1030 $input_params{'snapshot_format'} = $fmt;
1031 $input_params{'hash'} = $hash;
1032 # we also set the format suffix to the one requested
1033 # in the URL: this way a request for e.g. .tgz returns
1034 # a .tgz instead of a .tar.gz
1035 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1036 last;
1041 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1042 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1043 $searchtext, $search_regexp, $project_filter);
1044 sub evaluate_and_validate_params {
1045 our $action = $input_params{'action'};
1046 if (defined $action) {
1047 if (!is_valid_action($action)) {
1048 die_error(400, "Invalid action parameter");
1052 # parameters which are pathnames
1053 our $project = $input_params{'project'};
1054 if (defined $project) {
1055 if (!is_valid_project($project)) {
1056 undef $project;
1057 die_error(404, "No such project");
1061 our $project_filter = $input_params{'project_filter'};
1062 if (defined $project_filter) {
1063 if (!is_valid_pathname($project_filter)) {
1064 die_error(404, "Invalid project_filter parameter");
1068 our $file_name = $input_params{'file_name'};
1069 if (defined $file_name) {
1070 if (!is_valid_pathname($file_name)) {
1071 die_error(400, "Invalid file parameter");
1075 our $file_parent = $input_params{'file_parent'};
1076 if (defined $file_parent) {
1077 if (!is_valid_pathname($file_parent)) {
1078 die_error(400, "Invalid file parent parameter");
1082 # parameters which are refnames
1083 our $hash = $input_params{'hash'};
1084 if (defined $hash) {
1085 if (!is_valid_refname($hash)) {
1086 die_error(400, "Invalid hash parameter");
1090 our $hash_parent = $input_params{'hash_parent'};
1091 if (defined $hash_parent) {
1092 if (!is_valid_refname($hash_parent)) {
1093 die_error(400, "Invalid hash parent parameter");
1097 our $hash_base = $input_params{'hash_base'};
1098 if (defined $hash_base) {
1099 if (!is_valid_refname($hash_base)) {
1100 die_error(400, "Invalid hash base parameter");
1104 our @extra_options = @{$input_params{'extra_options'}};
1105 # @extra_options is always defined, since it can only be (currently) set from
1106 # CGI, and $cgi->param() returns the empty array in array context if the param
1107 # is not set
1108 foreach my $opt (@extra_options) {
1109 if (not exists $allowed_options{$opt}) {
1110 die_error(400, "Invalid option parameter");
1112 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1113 die_error(400, "Invalid option parameter for this action");
1117 our $hash_parent_base = $input_params{'hash_parent_base'};
1118 if (defined $hash_parent_base) {
1119 if (!is_valid_refname($hash_parent_base)) {
1120 die_error(400, "Invalid hash parent base parameter");
1124 # other parameters
1125 our $page = $input_params{'page'};
1126 if (defined $page) {
1127 if ($page =~ m/[^0-9]/) {
1128 die_error(400, "Invalid page parameter");
1132 our $searchtype = $input_params{'searchtype'};
1133 if (defined $searchtype) {
1134 if ($searchtype =~ m/[^a-z]/) {
1135 die_error(400, "Invalid searchtype parameter");
1139 our $search_use_regexp = $input_params{'search_use_regexp'};
1141 our $searchtext = $input_params{'searchtext'};
1142 our $search_regexp = undef;
1143 if (defined $searchtext) {
1144 if (length($searchtext) < 2) {
1145 die_error(403, "At least two characters are required for search parameter");
1147 if ($search_use_regexp) {
1148 $search_regexp = $searchtext;
1149 if (!eval { qr/$search_regexp/; 1; }) {
1150 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1151 die_error(400, "Invalid search regexp '$search_regexp'",
1152 esc_html($error));
1154 } else {
1155 $search_regexp = quotemeta $searchtext;
1160 # path to the current git repository
1161 our $git_dir;
1162 sub evaluate_git_dir {
1163 our $git_dir = "$projectroot/$project" if $project;
1166 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1167 sub configure_gitweb_features {
1168 # list of supported snapshot formats
1169 our @snapshot_fmts = gitweb_get_feature('snapshot');
1170 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1172 # check that the avatar feature is set to a known provider name,
1173 # and for each provider check if the dependencies are satisfied.
1174 # if the provider name is invalid or the dependencies are not met,
1175 # reset $git_avatar to the empty string.
1176 our ($git_avatar) = gitweb_get_feature('avatar');
1177 if ($git_avatar eq 'gravatar') {
1178 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1179 } elsif ($git_avatar eq 'picon') {
1180 # no dependencies
1181 } else {
1182 $git_avatar = '';
1185 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1186 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1189 sub get_branch_refs {
1190 return ('heads', @extra_branch_refs);
1193 # custom error handler: 'die <message>' is Internal Server Error
1194 sub handle_errors_html {
1195 my $msg = shift; # it is already HTML escaped
1197 # to avoid infinite loop where error occurs in die_error,
1198 # change handler to default handler, disabling handle_errors_html
1199 set_message("Error occurred when inside die_error:\n$msg");
1201 # you cannot jump out of die_error when called as error handler;
1202 # the subroutine set via CGI::Carp::set_message is called _after_
1203 # HTTP headers are already written, so it cannot write them itself
1204 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1206 set_message(\&handle_errors_html);
1208 # dispatch
1209 sub dispatch {
1210 if (!defined $action) {
1211 if (defined $hash) {
1212 $action = git_get_type($hash);
1213 $action or die_error(404, "Object does not exist");
1214 } elsif (defined $hash_base && defined $file_name) {
1215 $action = git_get_type("$hash_base:$file_name");
1216 $action or die_error(404, "File or directory does not exist");
1217 } elsif (defined $project) {
1218 $action = 'summary';
1219 } else {
1220 $action = 'project_list';
1223 if (!defined($actions{$action})) {
1224 die_error(400, "Unknown action");
1226 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1227 !$project) {
1228 die_error(400, "Project needed");
1230 $actions{$action}->();
1233 sub reset_timer {
1234 our $t0 = [ gettimeofday() ]
1235 if defined $t0;
1236 our $number_of_git_cmds = 0;
1239 our $first_request = 1;
1240 sub run_request {
1241 reset_timer();
1243 evaluate_uri();
1244 if ($first_request) {
1245 evaluate_gitweb_config();
1246 evaluate_git_version();
1248 if ($per_request_config) {
1249 if (ref($per_request_config) eq 'CODE') {
1250 $per_request_config->();
1251 } elsif (!$first_request) {
1252 evaluate_gitweb_config();
1255 check_loadavg();
1257 # $projectroot and $projects_list might be set in gitweb config file
1258 $projects_list ||= $projectroot;
1260 evaluate_query_params();
1261 evaluate_path_info();
1262 evaluate_and_validate_params();
1263 evaluate_git_dir();
1265 configure_gitweb_features();
1267 dispatch();
1270 our $is_last_request = sub { 1 };
1271 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1272 our $CGI = 'CGI';
1273 our $cgi;
1274 sub configure_as_fcgi {
1275 require CGI::Fast;
1276 our $CGI = 'CGI::Fast';
1278 my $request_number = 0;
1279 # let each child service 100 requests
1280 our $is_last_request = sub { ++$request_number > 100 };
1282 sub evaluate_argv {
1283 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1284 configure_as_fcgi()
1285 if $script_name =~ /\.fcgi$/;
1287 return unless (@ARGV);
1289 require Getopt::Long;
1290 Getopt::Long::GetOptions(
1291 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1292 'nproc|n=i' => sub {
1293 my ($arg, $val) = @_;
1294 return unless eval { require FCGI::ProcManager; 1; };
1295 my $proc_manager = FCGI::ProcManager->new({
1296 n_processes => $val,
1298 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1299 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1300 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1305 sub run {
1306 evaluate_argv();
1308 $first_request = 1;
1309 $pre_listen_hook->()
1310 if $pre_listen_hook;
1312 REQUEST:
1313 while ($cgi = $CGI->new()) {
1314 $pre_dispatch_hook->()
1315 if $pre_dispatch_hook;
1317 run_request();
1319 $post_dispatch_hook->()
1320 if $post_dispatch_hook;
1321 $first_request = 0;
1323 last REQUEST if ($is_last_request->());
1326 DONE_GITWEB:
1330 run();
1332 if (defined caller) {
1333 # wrapped in a subroutine processing requests,
1334 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1335 return;
1336 } else {
1337 # pure CGI script, serving single request
1338 exit;
1341 ## ======================================================================
1342 ## action links
1344 # possible values of extra options
1345 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1346 # -replay => 1 - start from a current view (replay with modifications)
1347 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1348 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1349 sub href {
1350 my %params = @_;
1351 # default is to use -absolute url() i.e. $my_uri
1352 my $href = $params{-full} ? $my_url : $my_uri;
1354 # implicit -replay, must be first of implicit params
1355 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1357 $params{'project'} = $project unless exists $params{'project'};
1359 if ($params{-replay}) {
1360 while (my ($name, $symbol) = each %cgi_param_mapping) {
1361 if (!exists $params{$name}) {
1362 $params{$name} = $input_params{$name};
1367 my $use_pathinfo = gitweb_check_feature('pathinfo');
1368 if (defined $params{'project'} &&
1369 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1370 # try to put as many parameters as possible in PATH_INFO:
1371 # - project name
1372 # - action
1373 # - hash_parent or hash_parent_base:/file_parent
1374 # - hash or hash_base:/filename
1375 # - the snapshot_format as an appropriate suffix
1377 # When the script is the root DirectoryIndex for the domain,
1378 # $href here would be something like http://gitweb.example.com/
1379 # Thus, we strip any trailing / from $href, to spare us double
1380 # slashes in the final URL
1381 $href =~ s,/$,,;
1383 # Then add the project name, if present
1384 $href .= "/".esc_path_info($params{'project'});
1385 delete $params{'project'};
1387 # since we destructively absorb parameters, we keep this
1388 # boolean that remembers if we're handling a snapshot
1389 my $is_snapshot = $params{'action'} eq 'snapshot';
1391 # Summary just uses the project path URL, any other action is
1392 # added to the URL
1393 if (defined $params{'action'}) {
1394 $href .= "/".esc_path_info($params{'action'})
1395 unless $params{'action'} eq 'summary';
1396 delete $params{'action'};
1399 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1400 # stripping nonexistent or useless pieces
1401 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1402 || $params{'hash_parent'} || $params{'hash'});
1403 if (defined $params{'hash_base'}) {
1404 if (defined $params{'hash_parent_base'}) {
1405 $href .= esc_path_info($params{'hash_parent_base'});
1406 # skip the file_parent if it's the same as the file_name
1407 if (defined $params{'file_parent'}) {
1408 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1409 delete $params{'file_parent'};
1410 } elsif ($params{'file_parent'} !~ /\.\./) {
1411 $href .= ":/".esc_path_info($params{'file_parent'});
1412 delete $params{'file_parent'};
1415 $href .= "..";
1416 delete $params{'hash_parent'};
1417 delete $params{'hash_parent_base'};
1418 } elsif (defined $params{'hash_parent'}) {
1419 $href .= esc_path_info($params{'hash_parent'}). "..";
1420 delete $params{'hash_parent'};
1423 $href .= esc_path_info($params{'hash_base'});
1424 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1425 $href .= ":/".esc_path_info($params{'file_name'});
1426 delete $params{'file_name'};
1428 delete $params{'hash'};
1429 delete $params{'hash_base'};
1430 } elsif (defined $params{'hash'}) {
1431 $href .= esc_path_info($params{'hash'});
1432 delete $params{'hash'};
1435 # If the action was a snapshot, we can absorb the
1436 # snapshot_format parameter too
1437 if ($is_snapshot) {
1438 my $fmt = $params{'snapshot_format'};
1439 # snapshot_format should always be defined when href()
1440 # is called, but just in case some code forgets, we
1441 # fall back to the default
1442 $fmt ||= $snapshot_fmts[0];
1443 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1444 delete $params{'snapshot_format'};
1448 # now encode the parameters explicitly
1449 my @result = ();
1450 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1451 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1452 if (defined $params{$name}) {
1453 if (ref($params{$name}) eq "ARRAY") {
1454 foreach my $par (@{$params{$name}}) {
1455 push @result, $symbol . "=" . esc_param($par);
1457 } else {
1458 push @result, $symbol . "=" . esc_param($params{$name});
1462 $href .= "?" . join(';', @result) if scalar @result;
1464 # final transformation: trailing spaces must be escaped (URI-encoded)
1465 $href =~ s/(\s+)$/CGI::escape($1)/e;
1467 if ($params{-anchor}) {
1468 $href .= "#".esc_param($params{-anchor});
1471 return $href;
1475 ## ======================================================================
1476 ## validation, quoting/unquoting and escaping
1478 sub is_valid_action {
1479 my $input = shift;
1480 return undef unless exists $actions{$input};
1481 return 1;
1484 sub is_valid_project {
1485 my $input = shift;
1487 return unless defined $input;
1488 if (!is_valid_pathname($input) ||
1489 !(-d "$projectroot/$input") ||
1490 !check_export_ok("$projectroot/$input") ||
1491 ($strict_export && !project_in_list($input))) {
1492 return undef;
1493 } else {
1494 return 1;
1498 sub is_valid_pathname {
1499 my $input = shift;
1501 return undef unless defined $input;
1502 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1503 # at the beginning, at the end, and between slashes.
1504 # also this catches doubled slashes
1505 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1506 return undef;
1508 # no null characters
1509 if ($input =~ m!\0!) {
1510 return undef;
1512 return 1;
1515 sub is_valid_ref_format {
1516 my $input = shift;
1518 return undef unless defined $input;
1519 # restrictions on ref name according to git-check-ref-format
1520 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1521 return undef;
1523 return 1;
1526 sub is_valid_refname {
1527 my $input = shift;
1529 return undef unless defined $input;
1530 # textual hashes are O.K.
1531 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1532 return 1;
1534 # it must be correct pathname
1535 is_valid_pathname($input) or return undef;
1536 # check git-check-ref-format restrictions
1537 is_valid_ref_format($input) or return undef;
1538 return 1;
1541 # decode sequences of octets in utf8 into Perl's internal form,
1542 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1543 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1544 sub to_utf8 {
1545 my $str = shift;
1546 return undef unless defined $str;
1548 if (utf8::is_utf8($str) || utf8::decode($str)) {
1549 return $str;
1550 } else {
1551 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1555 # quote unsafe chars, but keep the slash, even when it's not
1556 # correct, but quoted slashes look too horrible in bookmarks
1557 sub esc_param {
1558 my $str = shift;
1559 return undef unless defined $str;
1560 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1561 $str =~ s/ /\+/g;
1562 return $str;
1565 # the quoting rules for path_info fragment are slightly different
1566 sub esc_path_info {
1567 my $str = shift;
1568 return undef unless defined $str;
1570 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1571 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1573 return $str;
1576 # quote unsafe chars in whole URL, so some characters cannot be quoted
1577 sub esc_url {
1578 my $str = shift;
1579 return undef unless defined $str;
1580 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1581 $str =~ s/ /\+/g;
1582 return $str;
1585 # quote unsafe characters in HTML attributes
1586 sub esc_attr {
1588 # for XHTML conformance escaping '"' to '&quot;' is not enough
1589 return esc_html(@_);
1592 # replace invalid utf8 character with SUBSTITUTION sequence
1593 sub esc_html {
1594 my $str = shift;
1595 my %opts = @_;
1597 return undef unless defined $str;
1599 $str = to_utf8($str);
1600 $str = $cgi->escapeHTML($str);
1601 if ($opts{'-nbsp'}) {
1602 $str =~ s/ /&nbsp;/g;
1604 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1605 return $str;
1608 # quote control characters and escape filename to HTML
1609 sub esc_path {
1610 my $str = shift;
1611 my %opts = @_;
1613 return undef unless defined $str;
1615 $str = to_utf8($str);
1616 $str = $cgi->escapeHTML($str);
1617 if ($opts{'-nbsp'}) {
1618 $str =~ s/ /&nbsp;/g;
1620 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1621 return $str;
1624 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1625 sub sanitize {
1626 my $str = shift;
1628 return undef unless defined $str;
1630 $str = to_utf8($str);
1631 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1632 return $str;
1635 # Make control characters "printable", using character escape codes (CEC)
1636 sub quot_cec {
1637 my $cntrl = shift;
1638 my %opts = @_;
1639 my %es = ( # character escape codes, aka escape sequences
1640 "\t" => '\t', # tab (HT)
1641 "\n" => '\n', # line feed (LF)
1642 "\r" => '\r', # carrige return (CR)
1643 "\f" => '\f', # form feed (FF)
1644 "\b" => '\b', # backspace (BS)
1645 "\a" => '\a', # alarm (bell) (BEL)
1646 "\e" => '\e', # escape (ESC)
1647 "\013" => '\v', # vertical tab (VT)
1648 "\000" => '\0', # nul character (NUL)
1650 my $chr = ( (exists $es{$cntrl})
1651 ? $es{$cntrl}
1652 : sprintf('\%2x', ord($cntrl)) );
1653 if ($opts{-nohtml}) {
1654 return $chr;
1655 } else {
1656 return "<span class=\"cntrl\">$chr</span>";
1660 # Alternatively use unicode control pictures codepoints,
1661 # Unicode "printable representation" (PR)
1662 sub quot_upr {
1663 my $cntrl = shift;
1664 my %opts = @_;
1666 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1667 if ($opts{-nohtml}) {
1668 return $chr;
1669 } else {
1670 return "<span class=\"cntrl\">$chr</span>";
1674 # git may return quoted and escaped filenames
1675 sub unquote {
1676 my $str = shift;
1678 sub unq {
1679 my $seq = shift;
1680 my %es = ( # character escape codes, aka escape sequences
1681 't' => "\t", # tab (HT, TAB)
1682 'n' => "\n", # newline (NL)
1683 'r' => "\r", # return (CR)
1684 'f' => "\f", # form feed (FF)
1685 'b' => "\b", # backspace (BS)
1686 'a' => "\a", # alarm (bell) (BEL)
1687 'e' => "\e", # escape (ESC)
1688 'v' => "\013", # vertical tab (VT)
1691 if ($seq =~ m/^[0-7]{1,3}$/) {
1692 # octal char sequence
1693 return chr(oct($seq));
1694 } elsif (exists $es{$seq}) {
1695 # C escape sequence, aka character escape code
1696 return $es{$seq};
1698 # quoted ordinary character
1699 return $seq;
1702 if ($str =~ m/^"(.*)"$/) {
1703 # needs unquoting
1704 $str = $1;
1705 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1707 return $str;
1710 # escape tabs (convert tabs to spaces)
1711 sub untabify {
1712 my $line = shift;
1714 while ((my $pos = index($line, "\t")) != -1) {
1715 if (my $count = (8 - ($pos % 8))) {
1716 my $spaces = ' ' x $count;
1717 $line =~ s/\t/$spaces/;
1721 return $line;
1724 sub project_in_list {
1725 my $project = shift;
1726 my @list = git_get_projects_list();
1727 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1730 ## ----------------------------------------------------------------------
1731 ## HTML aware string manipulation
1733 # Try to chop given string on a word boundary between position
1734 # $len and $len+$add_len. If there is no word boundary there,
1735 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1736 # (marking chopped part) would be longer than given string.
1737 sub chop_str {
1738 my $str = shift;
1739 my $len = shift;
1740 my $add_len = shift || 10;
1741 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1743 # Make sure perl knows it is utf8 encoded so we don't
1744 # cut in the middle of a utf8 multibyte char.
1745 $str = to_utf8($str);
1747 # allow only $len chars, but don't cut a word if it would fit in $add_len
1748 # if it doesn't fit, cut it if it's still longer than the dots we would add
1749 # remove chopped character entities entirely
1751 # when chopping in the middle, distribute $len into left and right part
1752 # return early if chopping wouldn't make string shorter
1753 if ($where eq 'center') {
1754 return $str if ($len + 5 >= length($str)); # filler is length 5
1755 $len = int($len/2);
1756 } else {
1757 return $str if ($len + 4 >= length($str)); # filler is length 4
1760 # regexps: ending and beginning with word part up to $add_len
1761 my $endre = qr/.{$len}\w{0,$add_len}/;
1762 my $begre = qr/\w{0,$add_len}.{$len}/;
1764 if ($where eq 'left') {
1765 $str =~ m/^(.*?)($begre)$/;
1766 my ($lead, $body) = ($1, $2);
1767 if (length($lead) > 4) {
1768 $lead = " ...";
1770 return "$lead$body";
1772 } elsif ($where eq 'center') {
1773 $str =~ m/^($endre)(.*)$/;
1774 my ($left, $str) = ($1, $2);
1775 $str =~ m/^(.*?)($begre)$/;
1776 my ($mid, $right) = ($1, $2);
1777 if (length($mid) > 5) {
1778 $mid = " ... ";
1780 return "$left$mid$right";
1782 } else {
1783 $str =~ m/^($endre)(.*)$/;
1784 my $body = $1;
1785 my $tail = $2;
1786 if (length($tail) > 4) {
1787 $tail = "... ";
1789 return "$body$tail";
1793 # takes the same arguments as chop_str, but also wraps a <span> around the
1794 # result with a title attribute if it does get chopped. Additionally, the
1795 # string is HTML-escaped.
1796 sub chop_and_escape_str {
1797 my ($str) = @_;
1799 my $chopped = chop_str(@_);
1800 $str = to_utf8($str);
1801 if ($chopped eq $str) {
1802 return esc_html($chopped);
1803 } else {
1804 $str =~ s/[[:cntrl:]]/?/g;
1805 return $cgi->span({-title=>$str}, esc_html($chopped));
1809 # Highlight selected fragments of string, using given CSS class,
1810 # and escape HTML. It is assumed that fragments do not overlap.
1811 # Regions are passed as list of pairs (array references).
1813 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1814 # '<span class="mark">foo</span>bar'
1815 sub esc_html_hl_regions {
1816 my ($str, $css_class, @sel) = @_;
1817 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1818 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1819 return esc_html($str, %opts) unless @sel;
1821 my $out = '';
1822 my $pos = 0;
1824 for my $s (@sel) {
1825 my ($begin, $end) = @$s;
1827 # Don't create empty <span> elements.
1828 next if $end <= $begin;
1830 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1831 %opts);
1833 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1834 if ($begin - $pos > 0);
1835 $out .= $cgi->span({-class => $css_class}, $escaped);
1837 $pos = $end;
1839 $out .= esc_html(substr($str, $pos), %opts)
1840 if ($pos < length($str));
1842 return $out;
1845 # return positions of beginning and end of each match
1846 sub matchpos_list {
1847 my ($str, $regexp) = @_;
1848 return unless (defined $str && defined $regexp);
1850 my @matches;
1851 while ($str =~ /$regexp/g) {
1852 push @matches, [$-[0], $+[0]];
1854 return @matches;
1857 # highlight match (if any), and escape HTML
1858 sub esc_html_match_hl {
1859 my ($str, $regexp) = @_;
1860 return esc_html($str) unless defined $regexp;
1862 my @matches = matchpos_list($str, $regexp);
1863 return esc_html($str) unless @matches;
1865 return esc_html_hl_regions($str, 'match', @matches);
1869 # highlight match (if any) of shortened string, and escape HTML
1870 sub esc_html_match_hl_chopped {
1871 my ($str, $chopped, $regexp) = @_;
1872 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1874 my @matches = matchpos_list($str, $regexp);
1875 return esc_html($chopped) unless @matches;
1877 # filter matches so that we mark chopped string
1878 my $tail = "... "; # see chop_str
1879 unless ($chopped =~ s/\Q$tail\E$//) {
1880 $tail = '';
1882 my $chop_len = length($chopped);
1883 my $tail_len = length($tail);
1884 my @filtered;
1886 for my $m (@matches) {
1887 if ($m->[0] > $chop_len) {
1888 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1889 last;
1890 } elsif ($m->[1] > $chop_len) {
1891 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1892 last;
1894 push @filtered, $m;
1897 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1900 ## ----------------------------------------------------------------------
1901 ## functions returning short strings
1903 # CSS class for given age value (in seconds)
1904 sub age_class {
1905 my $age = shift;
1907 if (!defined $age) {
1908 return "noage";
1909 } elsif ($age < 60*60*2) {
1910 return "age0";
1911 } elsif ($age < 60*60*24*2) {
1912 return "age1";
1913 } else {
1914 return "age2";
1918 # convert age in seconds to "nn units ago" string
1919 sub age_string {
1920 my $age = shift;
1921 my $age_str;
1923 if ($age > 60*60*24*365*2) {
1924 $age_str = (int $age/60/60/24/365);
1925 $age_str .= " years ago";
1926 } elsif ($age > 60*60*24*(365/12)*2) {
1927 $age_str = int $age/60/60/24/(365/12);
1928 $age_str .= " months ago";
1929 } elsif ($age > 60*60*24*7*2) {
1930 $age_str = int $age/60/60/24/7;
1931 $age_str .= " weeks ago";
1932 } elsif ($age > 60*60*24*2) {
1933 $age_str = int $age/60/60/24;
1934 $age_str .= " days ago";
1935 } elsif ($age > 60*60*2) {
1936 $age_str = int $age/60/60;
1937 $age_str .= " hours ago";
1938 } elsif ($age > 60*2) {
1939 $age_str = int $age/60;
1940 $age_str .= " min ago";
1941 } elsif ($age > 2) {
1942 $age_str = int $age;
1943 $age_str .= " sec ago";
1944 } else {
1945 $age_str .= " right now";
1947 return $age_str;
1950 use constant {
1951 S_IFINVALID => 0030000,
1952 S_IFGITLINK => 0160000,
1955 # submodule/subproject, a commit object reference
1956 sub S_ISGITLINK {
1957 my $mode = shift;
1959 return (($mode & S_IFMT) == S_IFGITLINK)
1962 # convert file mode in octal to symbolic file mode string
1963 sub mode_str {
1964 my $mode = oct shift;
1966 if (S_ISGITLINK($mode)) {
1967 return 'm---------';
1968 } elsif (S_ISDIR($mode & S_IFMT)) {
1969 return 'drwxr-xr-x';
1970 } elsif (S_ISLNK($mode)) {
1971 return 'lrwxrwxrwx';
1972 } elsif (S_ISREG($mode)) {
1973 # git cares only about the executable bit
1974 if ($mode & S_IXUSR) {
1975 return '-rwxr-xr-x';
1976 } else {
1977 return '-rw-r--r--';
1979 } else {
1980 return '----------';
1984 # convert file mode in octal to file type string
1985 sub file_type {
1986 my $mode = shift;
1988 if ($mode !~ m/^[0-7]+$/) {
1989 return $mode;
1990 } else {
1991 $mode = oct $mode;
1994 if (S_ISGITLINK($mode)) {
1995 return "submodule";
1996 } elsif (S_ISDIR($mode & S_IFMT)) {
1997 return "directory";
1998 } elsif (S_ISLNK($mode)) {
1999 return "symlink";
2000 } elsif (S_ISREG($mode)) {
2001 return "file";
2002 } else {
2003 return "unknown";
2007 # convert file mode in octal to file type description string
2008 sub file_type_long {
2009 my $mode = shift;
2011 if ($mode !~ m/^[0-7]+$/) {
2012 return $mode;
2013 } else {
2014 $mode = oct $mode;
2017 if (S_ISGITLINK($mode)) {
2018 return "submodule";
2019 } elsif (S_ISDIR($mode & S_IFMT)) {
2020 return "directory";
2021 } elsif (S_ISLNK($mode)) {
2022 return "symlink";
2023 } elsif (S_ISREG($mode)) {
2024 if ($mode & S_IXUSR) {
2025 return "executable";
2026 } else {
2027 return "file";
2029 } else {
2030 return "unknown";
2035 ## ----------------------------------------------------------------------
2036 ## functions returning short HTML fragments, or transforming HTML fragments
2037 ## which don't belong to other sections
2039 # format line of commit message.
2040 sub format_log_line_html {
2041 my $line = shift;
2043 $line = esc_html($line, -nbsp=>1);
2044 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2045 $cgi->a({-href => href(action=>"object", hash=>$1),
2046 -class => "text"}, $1);
2047 }eg;
2049 return $line;
2052 # format marker of refs pointing to given object
2054 # the destination action is chosen based on object type and current context:
2055 # - for annotated tags, we choose the tag view unless it's the current view
2056 # already, in which case we go to shortlog view
2057 # - for other refs, we keep the current view if we're in history, shortlog or
2058 # log view, and select shortlog otherwise
2059 sub format_ref_marker {
2060 my ($refs, $id) = @_;
2061 my $markers = '';
2063 if (defined $refs->{$id}) {
2064 foreach my $ref (@{$refs->{$id}}) {
2065 # this code exploits the fact that non-lightweight tags are the
2066 # only indirect objects, and that they are the only objects for which
2067 # we want to use tag instead of shortlog as action
2068 my ($type, $name) = qw();
2069 my $indirect = ($ref =~ s/\^\{\}$//);
2070 # e.g. tags/v2.6.11 or heads/next
2071 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2072 $type = $1;
2073 $name = $2;
2074 } else {
2075 $type = "ref";
2076 $name = $ref;
2079 my $class = $type;
2080 $class .= " indirect" if $indirect;
2082 my $dest_action = "shortlog";
2084 if ($indirect) {
2085 $dest_action = "tag" unless $action eq "tag";
2086 } elsif ($action =~ /^(history|(short)?log)$/) {
2087 $dest_action = $action;
2090 my $dest = "";
2091 $dest .= "refs/" unless $ref =~ m!^refs/!;
2092 $dest .= $ref;
2094 my $link = $cgi->a({
2095 -href => href(
2096 action=>$dest_action,
2097 hash=>$dest
2098 )}, $name);
2100 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2101 $link . "</span>";
2105 if ($markers) {
2106 return ' <span class="refs">'. $markers . '</span>';
2107 } else {
2108 return "";
2112 # format, perhaps shortened and with markers, title line
2113 sub format_subject_html {
2114 my ($long, $short, $href, $extra) = @_;
2115 $extra = '' unless defined($extra);
2117 if (length($short) < length($long)) {
2118 $long =~ s/[[:cntrl:]]/?/g;
2119 return $cgi->a({-href => $href, -class => "list subject",
2120 -title => to_utf8($long)},
2121 esc_html($short)) . $extra;
2122 } else {
2123 return $cgi->a({-href => $href, -class => "list subject"},
2124 esc_html($long)) . $extra;
2128 # Rather than recomputing the url for an email multiple times, we cache it
2129 # after the first hit. This gives a visible benefit in views where the avatar
2130 # for the same email is used repeatedly (e.g. shortlog).
2131 # The cache is shared by all avatar engines (currently gravatar only), which
2132 # are free to use it as preferred. Since only one avatar engine is used for any
2133 # given page, there's no risk for cache conflicts.
2134 our %avatar_cache = ();
2136 # Compute the picon url for a given email, by using the picon search service over at
2137 # http://www.cs.indiana.edu/picons/search.html
2138 sub picon_url {
2139 my $email = lc shift;
2140 if (!$avatar_cache{$email}) {
2141 my ($user, $domain) = split('@', $email);
2142 $avatar_cache{$email} =
2143 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2144 "$domain/$user/" .
2145 "users+domains+unknown/up/single";
2147 return $avatar_cache{$email};
2150 # Compute the gravatar url for a given email, if it's not in the cache already.
2151 # Gravatar stores only the part of the URL before the size, since that's the
2152 # one computationally more expensive. This also allows reuse of the cache for
2153 # different sizes (for this particular engine).
2154 sub gravatar_url {
2155 my $email = lc shift;
2156 my $size = shift;
2157 $avatar_cache{$email} ||=
2158 "//www.gravatar.com/avatar/" .
2159 Digest::MD5::md5_hex($email) . "?s=";
2160 return $avatar_cache{$email} . $size;
2163 # Insert an avatar for the given $email at the given $size if the feature
2164 # is enabled.
2165 sub git_get_avatar {
2166 my ($email, %opts) = @_;
2167 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2168 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2169 $opts{-size} ||= 'default';
2170 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2171 my $url = "";
2172 if ($git_avatar eq 'gravatar') {
2173 $url = gravatar_url($email, $size);
2174 } elsif ($git_avatar eq 'picon') {
2175 $url = picon_url($email);
2177 # Other providers can be added by extending the if chain, defining $url
2178 # as needed. If no variant puts something in $url, we assume avatars
2179 # are completely disabled/unavailable.
2180 if ($url) {
2181 return $pre_white .
2182 "<img width=\"$size\" " .
2183 "class=\"avatar\" " .
2184 "src=\"".esc_url($url)."\" " .
2185 "alt=\"\" " .
2186 "/>" . $post_white;
2187 } else {
2188 return "";
2192 sub format_search_author {
2193 my ($author, $searchtype, $displaytext) = @_;
2194 my $have_search = gitweb_check_feature('search');
2196 if ($have_search) {
2197 my $performed = "";
2198 if ($searchtype eq 'author') {
2199 $performed = "authored";
2200 } elsif ($searchtype eq 'committer') {
2201 $performed = "committed";
2204 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2205 searchtext=>$author,
2206 searchtype=>$searchtype), class=>"list",
2207 title=>"Search for commits $performed by $author"},
2208 $displaytext);
2210 } else {
2211 return $displaytext;
2215 # format the author name of the given commit with the given tag
2216 # the author name is chopped and escaped according to the other
2217 # optional parameters (see chop_str).
2218 sub format_author_html {
2219 my $tag = shift;
2220 my $co = shift;
2221 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2222 return "<$tag class=\"author\">" .
2223 format_search_author($co->{'author_name'}, "author",
2224 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2225 $author) .
2226 "</$tag>";
2229 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2230 sub format_git_diff_header_line {
2231 my $line = shift;
2232 my $diffinfo = shift;
2233 my ($from, $to) = @_;
2235 if ($diffinfo->{'nparents'}) {
2236 # combined diff
2237 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2238 if ($to->{'href'}) {
2239 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2240 esc_path($to->{'file'}));
2241 } else { # file was deleted (no href)
2242 $line .= esc_path($to->{'file'});
2244 } else {
2245 # "ordinary" diff
2246 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2247 if ($from->{'href'}) {
2248 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2249 'a/' . esc_path($from->{'file'}));
2250 } else { # file was added (no href)
2251 $line .= 'a/' . esc_path($from->{'file'});
2253 $line .= ' ';
2254 if ($to->{'href'}) {
2255 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2256 'b/' . esc_path($to->{'file'}));
2257 } else { # file was deleted
2258 $line .= 'b/' . esc_path($to->{'file'});
2262 return "<div class=\"diff header\">$line</div>\n";
2265 # format extended diff header line, before patch itself
2266 sub format_extended_diff_header_line {
2267 my $line = shift;
2268 my $diffinfo = shift;
2269 my ($from, $to) = @_;
2271 # match <path>
2272 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2273 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2274 esc_path($from->{'file'}));
2276 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2277 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2278 esc_path($to->{'file'}));
2280 # match single <mode>
2281 if ($line =~ m/\s(\d{6})$/) {
2282 $line .= '<span class="info"> (' .
2283 file_type_long($1) .
2284 ')</span>';
2286 # match <hash>
2287 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2288 # can match only for combined diff
2289 $line = 'index ';
2290 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2291 if ($from->{'href'}[$i]) {
2292 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2293 -class=>"hash"},
2294 substr($diffinfo->{'from_id'}[$i],0,7));
2295 } else {
2296 $line .= '0' x 7;
2298 # separator
2299 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2301 $line .= '..';
2302 if ($to->{'href'}) {
2303 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2304 substr($diffinfo->{'to_id'},0,7));
2305 } else {
2306 $line .= '0' x 7;
2309 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2310 # can match only for ordinary diff
2311 my ($from_link, $to_link);
2312 if ($from->{'href'}) {
2313 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2314 substr($diffinfo->{'from_id'},0,7));
2315 } else {
2316 $from_link = '0' x 7;
2318 if ($to->{'href'}) {
2319 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2320 substr($diffinfo->{'to_id'},0,7));
2321 } else {
2322 $to_link = '0' x 7;
2324 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2325 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2328 return $line . "<br/>\n";
2331 # format from-file/to-file diff header
2332 sub format_diff_from_to_header {
2333 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2334 my $line;
2335 my $result = '';
2337 $line = $from_line;
2338 #assert($line =~ m/^---/) if DEBUG;
2339 # no extra formatting for "^--- /dev/null"
2340 if (! $diffinfo->{'nparents'}) {
2341 # ordinary (single parent) diff
2342 if ($line =~ m!^--- "?a/!) {
2343 if ($from->{'href'}) {
2344 $line = '--- a/' .
2345 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2346 esc_path($from->{'file'}));
2347 } else {
2348 $line = '--- a/' .
2349 esc_path($from->{'file'});
2352 $result .= qq!<div class="diff from_file">$line</div>\n!;
2354 } else {
2355 # combined diff (merge commit)
2356 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2357 if ($from->{'href'}[$i]) {
2358 $line = '--- ' .
2359 $cgi->a({-href=>href(action=>"blobdiff",
2360 hash_parent=>$diffinfo->{'from_id'}[$i],
2361 hash_parent_base=>$parents[$i],
2362 file_parent=>$from->{'file'}[$i],
2363 hash=>$diffinfo->{'to_id'},
2364 hash_base=>$hash,
2365 file_name=>$to->{'file'}),
2366 -class=>"path",
2367 -title=>"diff" . ($i+1)},
2368 $i+1) .
2369 '/' .
2370 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2371 esc_path($from->{'file'}[$i]));
2372 } else {
2373 $line = '--- /dev/null';
2375 $result .= qq!<div class="diff from_file">$line</div>\n!;
2379 $line = $to_line;
2380 #assert($line =~ m/^\+\+\+/) if DEBUG;
2381 # no extra formatting for "^+++ /dev/null"
2382 if ($line =~ m!^\+\+\+ "?b/!) {
2383 if ($to->{'href'}) {
2384 $line = '+++ b/' .
2385 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2386 esc_path($to->{'file'}));
2387 } else {
2388 $line = '+++ b/' .
2389 esc_path($to->{'file'});
2392 $result .= qq!<div class="diff to_file">$line</div>\n!;
2394 return $result;
2397 # create note for patch simplified by combined diff
2398 sub format_diff_cc_simplified {
2399 my ($diffinfo, @parents) = @_;
2400 my $result = '';
2402 $result .= "<div class=\"diff header\">" .
2403 "diff --cc ";
2404 if (!is_deleted($diffinfo)) {
2405 $result .= $cgi->a({-href => href(action=>"blob",
2406 hash_base=>$hash,
2407 hash=>$diffinfo->{'to_id'},
2408 file_name=>$diffinfo->{'to_file'}),
2409 -class => "path"},
2410 esc_path($diffinfo->{'to_file'}));
2411 } else {
2412 $result .= esc_path($diffinfo->{'to_file'});
2414 $result .= "</div>\n" . # class="diff header"
2415 "<div class=\"diff nodifferences\">" .
2416 "Simple merge" .
2417 "</div>\n"; # class="diff nodifferences"
2419 return $result;
2422 sub diff_line_class {
2423 my ($line, $from, $to) = @_;
2425 # ordinary diff
2426 my $num_sign = 1;
2427 # combined diff
2428 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2429 $num_sign = scalar @{$from->{'href'}};
2432 my @diff_line_classifier = (
2433 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2434 { regexp => qr/^\\/, class => "incomplete" },
2435 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2436 # classifier for context must come before classifier add/rem,
2437 # or we would have to use more complicated regexp, for example
2438 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2439 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2440 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2442 for my $clsfy (@diff_line_classifier) {
2443 return $clsfy->{'class'}
2444 if ($line =~ $clsfy->{'regexp'});
2447 # fallback
2448 return "";
2451 # assumes that $from and $to are defined and correctly filled,
2452 # and that $line holds a line of chunk header for unified diff
2453 sub format_unidiff_chunk_header {
2454 my ($line, $from, $to) = @_;
2456 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2457 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2459 $from_lines = 0 unless defined $from_lines;
2460 $to_lines = 0 unless defined $to_lines;
2462 if ($from->{'href'}) {
2463 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2464 -class=>"list"}, $from_text);
2466 if ($to->{'href'}) {
2467 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2468 -class=>"list"}, $to_text);
2470 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2471 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2472 return $line;
2475 # assumes that $from and $to are defined and correctly filled,
2476 # and that $line holds a line of chunk header for combined diff
2477 sub format_cc_diff_chunk_header {
2478 my ($line, $from, $to) = @_;
2480 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2481 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2483 @from_text = split(' ', $ranges);
2484 for (my $i = 0; $i < @from_text; ++$i) {
2485 ($from_start[$i], $from_nlines[$i]) =
2486 (split(',', substr($from_text[$i], 1)), 0);
2489 $to_text = pop @from_text;
2490 $to_start = pop @from_start;
2491 $to_nlines = pop @from_nlines;
2493 $line = "<span class=\"chunk_info\">$prefix ";
2494 for (my $i = 0; $i < @from_text; ++$i) {
2495 if ($from->{'href'}[$i]) {
2496 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2497 -class=>"list"}, $from_text[$i]);
2498 } else {
2499 $line .= $from_text[$i];
2501 $line .= " ";
2503 if ($to->{'href'}) {
2504 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2505 -class=>"list"}, $to_text);
2506 } else {
2507 $line .= $to_text;
2509 $line .= " $prefix</span>" .
2510 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2511 return $line;
2514 # process patch (diff) line (not to be used for diff headers),
2515 # returning HTML-formatted (but not wrapped) line.
2516 # If the line is passed as a reference, it is treated as HTML and not
2517 # esc_html()'ed.
2518 sub format_diff_line {
2519 my ($line, $diff_class, $from, $to) = @_;
2521 if (ref($line)) {
2522 $line = $$line;
2523 } else {
2524 chomp $line;
2525 $line = untabify($line);
2527 if ($from && $to && $line =~ m/^\@{2} /) {
2528 $line = format_unidiff_chunk_header($line, $from, $to);
2529 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2530 $line = format_cc_diff_chunk_header($line, $from, $to);
2531 } else {
2532 $line = esc_html($line, -nbsp=>1);
2536 my $diff_classes = "diff";
2537 $diff_classes .= " $diff_class" if ($diff_class);
2538 $line = "<div class=\"$diff_classes\">$line</div>\n";
2540 return $line;
2543 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2544 # linked. Pass the hash of the tree/commit to snapshot.
2545 sub format_snapshot_links {
2546 my ($hash) = @_;
2547 my $num_fmts = @snapshot_fmts;
2548 if ($num_fmts > 1) {
2549 # A parenthesized list of links bearing format names.
2550 # e.g. "snapshot (_tar.gz_ _zip_)"
2551 return "snapshot (" . join(' ', map
2552 $cgi->a({
2553 -href => href(
2554 action=>"snapshot",
2555 hash=>$hash,
2556 snapshot_format=>$_
2558 }, $known_snapshot_formats{$_}{'display'})
2559 , @snapshot_fmts) . ")";
2560 } elsif ($num_fmts == 1) {
2561 # A single "snapshot" link whose tooltip bears the format name.
2562 # i.e. "_snapshot_"
2563 my ($fmt) = @snapshot_fmts;
2564 return
2565 $cgi->a({
2566 -href => href(
2567 action=>"snapshot",
2568 hash=>$hash,
2569 snapshot_format=>$fmt
2571 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2572 }, "snapshot");
2573 } else { # $num_fmts == 0
2574 return undef;
2578 ## ......................................................................
2579 ## functions returning values to be passed, perhaps after some
2580 ## transformation, to other functions; e.g. returning arguments to href()
2582 # returns hash to be passed to href to generate gitweb URL
2583 # in -title key it returns description of link
2584 sub get_feed_info {
2585 my $format = shift || 'Atom';
2586 my %res = (action => lc($format));
2587 my $matched_ref = 0;
2589 # feed links are possible only for project views
2590 return unless (defined $project);
2591 # some views should link to OPML, or to generic project feed,
2592 # or don't have specific feed yet (so they should use generic)
2593 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2595 my $branch = undef;
2596 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2597 # (fullname) to differentiate from tag links; this also makes
2598 # possible to detect branch links
2599 for my $ref (get_branch_refs()) {
2600 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2601 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2602 $branch = $1;
2603 $matched_ref = $ref;
2604 last;
2607 # find log type for feed description (title)
2608 my $type = 'log';
2609 if (defined $file_name) {
2610 $type = "history of $file_name";
2611 $type .= "/" if ($action eq 'tree');
2612 $type .= " on '$branch'" if (defined $branch);
2613 } else {
2614 $type = "log of $branch" if (defined $branch);
2617 $res{-title} = $type;
2618 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2619 $res{'file_name'} = $file_name;
2621 return %res;
2624 ## ----------------------------------------------------------------------
2625 ## git utility subroutines, invoking git commands
2627 # returns path to the core git executable and the --git-dir parameter as list
2628 sub git_cmd {
2629 $number_of_git_cmds++;
2630 return $GIT, '--git-dir='.$git_dir;
2633 # opens a "-|" cmd pipe handle with 2>/dev/null and returns it
2634 sub cmd_pipe {
2636 # In order to be compatible with FCGI mode we must use POSIX
2637 # and access the STDERR_FILENO file descriptor directly
2639 use POSIX qw(STDERR_FILENO dup dup2);
2641 open(my $null, '>', File::Spec->devnull) or die "couldn't open devnull: $!";
2642 (my $saveerr = dup(STDERR_FILENO)) or die "couldn't dup STDERR: $!";
2643 my $dup2ok = dup2(fileno($null), STDERR_FILENO);
2644 close($null) or !$dup2ok or die "couldn't close NULL: $!";
2645 $dup2ok or POSIX::close($saveerr), die "couldn't dup NULL to STDERR: $!";
2646 my $result = open(my $fd, "-|", @_);
2647 $dup2ok = dup2($saveerr, STDERR_FILENO);
2648 POSIX::close($saveerr) or !$dup2ok or die "couldn't close SAVEERR: $!";
2649 $dup2ok or die "couldn't dup SAVERR to STDERR: $!";
2651 return $result ? $fd : undef;
2654 # opens a "-|" git_cmd pipe handle with 2>/dev/null and returns it
2655 sub git_cmd_pipe {
2656 return cmd_pipe git_cmd(), @_;
2659 # quote the given arguments for passing them to the shell
2660 # quote_command("command", "arg 1", "arg with ' and ! characters")
2661 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2662 # Try to avoid using this function wherever possible.
2663 sub quote_command {
2664 return join(' ',
2665 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2668 # get HEAD ref of given project as hash
2669 sub git_get_head_hash {
2670 return git_get_full_hash(shift, 'HEAD');
2673 sub git_get_full_hash {
2674 return git_get_hash(@_);
2677 sub git_get_short_hash {
2678 return git_get_hash(@_, '--short=7');
2681 sub git_get_hash {
2682 my ($project, $hash, @options) = @_;
2683 my $o_git_dir = $git_dir;
2684 my $retval = undef;
2685 $git_dir = "$projectroot/$project";
2686 if (defined(my $fd = git_cmd_pipe 'rev-parse',
2687 '--verify', '-q', @options, $hash)) {
2688 $retval = <$fd>;
2689 chomp $retval if defined $retval;
2690 close $fd;
2692 if (defined $o_git_dir) {
2693 $git_dir = $o_git_dir;
2695 return $retval;
2698 # get type of given object
2699 sub git_get_type {
2700 my $hash = shift;
2702 defined(my $fd = git_cmd_pipe "cat-file", '-t', $hash) or return;
2703 my $type = <$fd>;
2704 close $fd or return;
2705 chomp $type;
2706 return $type;
2709 # repository configuration
2710 our $config_file = '';
2711 our %config;
2713 # store multiple values for single key as anonymous array reference
2714 # single values stored directly in the hash, not as [ <value> ]
2715 sub hash_set_multi {
2716 my ($hash, $key, $value) = @_;
2718 if (!exists $hash->{$key}) {
2719 $hash->{$key} = $value;
2720 } elsif (!ref $hash->{$key}) {
2721 $hash->{$key} = [ $hash->{$key}, $value ];
2722 } else {
2723 push @{$hash->{$key}}, $value;
2727 # return hash of git project configuration
2728 # optionally limited to some section, e.g. 'gitweb'
2729 sub git_parse_project_config {
2730 my $section_regexp = shift;
2731 my %config;
2733 local $/ = "\0";
2735 defined(my $fh = git_cmd_pipe "config", '-z', '-l')
2736 or return;
2738 while (my $keyval = to_utf8(scalar <$fh>)) {
2739 chomp $keyval;
2740 my ($key, $value) = split(/\n/, $keyval, 2);
2742 hash_set_multi(\%config, $key, $value)
2743 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2745 close $fh;
2747 return %config;
2750 # convert config value to boolean: 'true' or 'false'
2751 # no value, number > 0, 'true' and 'yes' values are true
2752 # rest of values are treated as false (never as error)
2753 sub config_to_bool {
2754 my $val = shift;
2756 return 1 if !defined $val; # section.key
2758 # strip leading and trailing whitespace
2759 $val =~ s/^\s+//;
2760 $val =~ s/\s+$//;
2762 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2763 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2766 # convert config value to simple decimal number
2767 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2768 # to be multiplied by 1024, 1048576, or 1073741824
2769 sub config_to_int {
2770 my $val = shift;
2772 # strip leading and trailing whitespace
2773 $val =~ s/^\s+//;
2774 $val =~ s/\s+$//;
2776 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2777 $unit = lc($unit);
2778 # unknown unit is treated as 1
2779 return $num * ($unit eq 'g' ? 1073741824 :
2780 $unit eq 'm' ? 1048576 :
2781 $unit eq 'k' ? 1024 : 1);
2783 return $val;
2786 # convert config value to array reference, if needed
2787 sub config_to_multi {
2788 my $val = shift;
2790 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2793 sub git_get_project_config {
2794 my ($key, $type) = @_;
2796 return unless defined $git_dir;
2798 # key sanity check
2799 return unless ($key);
2800 # only subsection, if exists, is case sensitive,
2801 # and not lowercased by 'git config -z -l'
2802 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2803 $lo =~ s/_//g;
2804 $key = join(".", lc($hi), $mi, lc($lo));
2805 return if ($lo =~ /\W/ || $hi =~ /\W/);
2806 } else {
2807 $key = lc($key);
2808 $key =~ s/_//g;
2809 return if ($key =~ /\W/);
2811 $key =~ s/^gitweb\.//;
2813 # type sanity check
2814 if (defined $type) {
2815 $type =~ s/^--//;
2816 $type = undef
2817 unless ($type eq 'bool' || $type eq 'int');
2820 # get config
2821 if (!defined $config_file ||
2822 $config_file ne "$git_dir/config") {
2823 %config = git_parse_project_config('gitweb');
2824 $config_file = "$git_dir/config";
2827 # check if config variable (key) exists
2828 return unless exists $config{"gitweb.$key"};
2830 # ensure given type
2831 if (!defined $type) {
2832 return $config{"gitweb.$key"};
2833 } elsif ($type eq 'bool') {
2834 # backward compatibility: 'git config --bool' returns true/false
2835 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2836 } elsif ($type eq 'int') {
2837 return config_to_int($config{"gitweb.$key"});
2839 return $config{"gitweb.$key"};
2842 # get hash of given path at given ref
2843 sub git_get_hash_by_path {
2844 my $base = shift;
2845 my $path = shift || return undef;
2846 my $type = shift;
2848 $path =~ s,/+$,,;
2850 defined(my $fd = git_cmd_pipe "ls-tree", $base, "--", $path)
2851 or die_error(500, "Open git-ls-tree failed");
2852 my $line = to_utf8(scalar <$fd>);
2853 close $fd or return undef;
2855 if (!defined $line) {
2856 # there is no tree or hash given by $path at $base
2857 return undef;
2860 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2861 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2862 if (defined $type && $type ne $2) {
2863 # type doesn't match
2864 return undef;
2866 return $3;
2869 # get path of entry with given hash at given tree-ish (ref)
2870 # used to get 'from' filename for combined diff (merge commit) for renames
2871 sub git_get_path_by_hash {
2872 my $base = shift || return;
2873 my $hash = shift || return;
2875 local $/ = "\0";
2877 defined(my $fd = git_cmd_pipe "ls-tree", '-r', '-t', '-z', $base)
2878 or return undef;
2879 while (my $line = to_utf8(scalar <$fd>)) {
2880 chomp $line;
2882 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2883 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2884 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2885 close $fd;
2886 return $1;
2889 close $fd;
2890 return undef;
2893 ## ......................................................................
2894 ## git utility functions, directly accessing git repository
2896 # get the value of config variable either from file named as the variable
2897 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2898 # configuration variable in the repository config file.
2899 sub git_get_file_or_project_config {
2900 my ($path, $name) = @_;
2902 $git_dir = "$projectroot/$path";
2903 open my $fd, '<', "$git_dir/$name"
2904 or return git_get_project_config($name);
2905 my $conf = to_utf8(scalar <$fd>);
2906 close $fd;
2907 if (defined $conf) {
2908 chomp $conf;
2910 return $conf;
2913 sub git_get_project_description {
2914 my $path = shift;
2915 return git_get_file_or_project_config($path, 'description');
2918 sub git_get_project_category {
2919 my $path = shift;
2920 return git_get_file_or_project_config($path, 'category');
2924 # supported formats:
2925 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2926 # - if its contents is a number, use it as tag weight,
2927 # - otherwise add a tag with weight 1
2928 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2929 # the same value multiple times increases tag weight
2930 # * `gitweb.ctag' multi-valued repo config variable
2931 sub git_get_project_ctags {
2932 my $project = shift;
2933 my $ctags = {};
2935 $git_dir = "$projectroot/$project";
2936 if (opendir my $dh, "$git_dir/ctags") {
2937 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2938 foreach my $tagfile (@files) {
2939 open my $ct, '<', $tagfile
2940 or next;
2941 my $val = <$ct>;
2942 chomp $val if $val;
2943 close $ct;
2945 (my $ctag = $tagfile) =~ s#.*/##;
2946 $ctag = to_utf8($ctag);
2947 if ($val =~ /^\d+$/) {
2948 $ctags->{$ctag} = $val;
2949 } else {
2950 $ctags->{$ctag} = 1;
2953 closedir $dh;
2955 } elsif (open my $fh, '<', "$git_dir/ctags") {
2956 while (my $line = to_utf8(scalar <$fh>)) {
2957 chomp $line;
2958 $ctags->{$line}++ if $line;
2960 close $fh;
2962 } else {
2963 my $taglist = config_to_multi(git_get_project_config('ctag'));
2964 foreach my $tag (@$taglist) {
2965 $ctags->{$tag}++;
2969 return $ctags;
2972 # return hash, where keys are content tags ('ctags'),
2973 # and values are sum of weights of given tag in every project
2974 sub git_gather_all_ctags {
2975 my $projects = shift;
2976 my $ctags = {};
2978 foreach my $p (@$projects) {
2979 foreach my $ct (keys %{$p->{'ctags'}}) {
2980 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2984 return $ctags;
2987 sub git_populate_project_tagcloud {
2988 my $ctags = shift;
2990 # First, merge different-cased tags; tags vote on casing
2991 my %ctags_lc;
2992 foreach (keys %$ctags) {
2993 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2994 if (not $ctags_lc{lc $_}->{topcount}
2995 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2996 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2997 $ctags_lc{lc $_}->{topname} = $_;
3001 my $cloud;
3002 my $matched = $input_params{'ctag'};
3003 if (eval { require HTML::TagCloud; 1; }) {
3004 $cloud = HTML::TagCloud->new;
3005 foreach my $ctag (sort keys %ctags_lc) {
3006 # Pad the title with spaces so that the cloud looks
3007 # less crammed.
3008 my $title = esc_html($ctags_lc{$ctag}->{topname});
3009 $title =~ s/ /&nbsp;/g;
3010 $title =~ s/^/&nbsp;/g;
3011 $title =~ s/$/&nbsp;/g;
3012 if (defined $matched && $matched eq $ctag) {
3013 $title = qq(<span class="match">$title</span>);
3015 $cloud->add($title, href(project=>undef, ctag=>$ctag),
3016 $ctags_lc{$ctag}->{count});
3018 } else {
3019 $cloud = {};
3020 foreach my $ctag (keys %ctags_lc) {
3021 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3022 if (defined $matched && $matched eq $ctag) {
3023 $title = qq(<span class="match">$title</span>);
3025 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3026 $cloud->{$ctag}{ctag} =
3027 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3030 return $cloud;
3033 sub git_show_project_tagcloud {
3034 my ($cloud, $count) = @_;
3035 if (ref $cloud eq 'HTML::TagCloud') {
3036 return $cloud->html_and_css($count);
3037 } else {
3038 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3039 return
3040 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3041 join (', ', map {
3042 $cloud->{$_}->{'ctag'}
3043 } splice(@tags, 0, $count)) .
3044 '</div>';
3048 sub git_get_project_url_list {
3049 my $path = shift;
3051 $git_dir = "$projectroot/$path";
3052 open my $fd, '<', "$git_dir/cloneurl"
3053 or return wantarray ?
3054 @{ config_to_multi(git_get_project_config('url')) } :
3055 config_to_multi(git_get_project_config('url'));
3056 my @git_project_url_list = map { chomp; to_utf8($_) } <$fd>;
3057 close $fd;
3059 return wantarray ? @git_project_url_list : \@git_project_url_list;
3062 sub git_get_projects_list {
3063 my $filter = shift || '';
3064 my $paranoid = shift;
3065 my @list;
3067 if (-d $projects_list) {
3068 # search in directory
3069 my $dir = $projects_list;
3070 # remove the trailing "/"
3071 $dir =~ s!/+$!!;
3072 my $pfxlen = length("$dir");
3073 my $pfxdepth = ($dir =~ tr!/!!);
3074 # when filtering, search only given subdirectory
3075 if ($filter && !$paranoid) {
3076 $dir .= "/$filter";
3077 $dir =~ s!/+$!!;
3080 File::Find::find({
3081 follow_fast => 1, # follow symbolic links
3082 follow_skip => 2, # ignore duplicates
3083 dangling_symlinks => 0, # ignore dangling symlinks, silently
3084 wanted => sub {
3085 # global variables
3086 our $project_maxdepth;
3087 our $projectroot;
3088 # skip project-list toplevel, if we get it.
3089 return if (m!^[/.]$!);
3090 # only directories can be git repositories
3091 return unless (-d $_);
3092 # don't traverse too deep (Find is super slow on os x)
3093 # $project_maxdepth excludes depth of $projectroot
3094 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3095 $File::Find::prune = 1;
3096 return;
3099 my $path = substr($File::Find::name, $pfxlen + 1);
3100 # paranoidly only filter here
3101 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3102 next;
3104 # we check related file in $projectroot
3105 if (check_export_ok("$projectroot/$path")) {
3106 push @list, { path => $path };
3107 $File::Find::prune = 1;
3110 }, "$dir");
3112 } elsif (-f $projects_list) {
3113 # read from file(url-encoded):
3114 # 'git%2Fgit.git Linus+Torvalds'
3115 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3116 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3117 open my $fd, '<', $projects_list or return;
3118 PROJECT:
3119 while (my $line = <$fd>) {
3120 chomp $line;
3121 my ($path, $owner) = split ' ', $line;
3122 $path = unescape($path);
3123 $owner = unescape($owner);
3124 if (!defined $path) {
3125 next;
3127 # if $filter is rpovided, check if $path begins with $filter
3128 if ($filter && $path !~ m!^\Q$filter\E/!) {
3129 next;
3131 if (check_export_ok("$projectroot/$path")) {
3132 my $pr = {
3133 path => $path
3135 if ($owner) {
3136 $pr->{'owner'} = to_utf8($owner);
3138 push @list, $pr;
3141 close $fd;
3143 return @list;
3146 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3147 # as side effects it sets 'forks' field to list of forks for forked projects
3148 sub filter_forks_from_projects_list {
3149 my $projects = shift;
3151 my %trie; # prefix tree of directories (path components)
3152 # generate trie out of those directories that might contain forks
3153 foreach my $pr (@$projects) {
3154 my $path = $pr->{'path'};
3155 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3156 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3157 next unless ($path); # skip '.git' repository: tests, git-instaweb
3158 next unless (-d "$projectroot/$path"); # containing directory exists
3159 $pr->{'forks'} = []; # there can be 0 or more forks of project
3161 # add to trie
3162 my @dirs = split('/', $path);
3163 # walk the trie, until either runs out of components or out of trie
3164 my $ref = \%trie;
3165 while (scalar @dirs &&
3166 exists($ref->{$dirs[0]})) {
3167 $ref = $ref->{shift @dirs};
3169 # create rest of trie structure from rest of components
3170 foreach my $dir (@dirs) {
3171 $ref = $ref->{$dir} = {};
3173 # create end marker, store $pr as a data
3174 $ref->{''} = $pr if (!exists $ref->{''});
3177 # filter out forks, by finding shortest prefix match for paths
3178 my @filtered;
3179 PROJECT:
3180 foreach my $pr (@$projects) {
3181 # trie lookup
3182 my $ref = \%trie;
3183 DIR:
3184 foreach my $dir (split('/', $pr->{'path'})) {
3185 if (exists $ref->{''}) {
3186 # found [shortest] prefix, is a fork - skip it
3187 push @{$ref->{''}{'forks'}}, $pr;
3188 next PROJECT;
3190 if (!exists $ref->{$dir}) {
3191 # not in trie, cannot have prefix, not a fork
3192 push @filtered, $pr;
3193 next PROJECT;
3195 # If the dir is there, we just walk one step down the trie.
3196 $ref = $ref->{$dir};
3198 # we ran out of trie
3199 # (shouldn't happen: it's either no match, or end marker)
3200 push @filtered, $pr;
3203 return @filtered;
3206 # note: fill_project_list_info must be run first,
3207 # for 'descr_long' and 'ctags' to be filled
3208 sub search_projects_list {
3209 my ($projlist, %opts) = @_;
3210 my $tagfilter = $opts{'tagfilter'};
3211 my $search_re = $opts{'search_regexp'};
3213 return @$projlist
3214 unless ($tagfilter || $search_re);
3216 # searching projects require filling to be run before it;
3217 fill_project_list_info($projlist,
3218 $tagfilter ? 'ctags' : (),
3219 $search_re ? ('path', 'descr') : ());
3220 my @projects;
3221 PROJECT:
3222 foreach my $pr (@$projlist) {
3224 if ($tagfilter) {
3225 next unless ref($pr->{'ctags'}) eq 'HASH';
3226 next unless
3227 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3230 if ($search_re) {
3231 next unless
3232 $pr->{'path'} =~ /$search_re/ ||
3233 $pr->{'descr_long'} =~ /$search_re/;
3236 push @projects, $pr;
3239 return @projects;
3242 our $gitweb_project_owner = undef;
3243 sub git_get_project_list_from_file {
3245 return if (defined $gitweb_project_owner);
3247 $gitweb_project_owner = {};
3248 # read from file (url-encoded):
3249 # 'git%2Fgit.git Linus+Torvalds'
3250 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3251 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3252 if (-f $projects_list) {
3253 open(my $fd, '<', $projects_list);
3254 while (my $line = <$fd>) {
3255 chomp $line;
3256 my ($pr, $ow) = split ' ', $line;
3257 $pr = unescape($pr);
3258 $ow = unescape($ow);
3259 $gitweb_project_owner->{$pr} = to_utf8($ow);
3261 close $fd;
3265 sub git_get_project_owner {
3266 my $project = shift;
3267 my $owner;
3269 return undef unless $project;
3270 $git_dir = "$projectroot/$project";
3272 if (!defined $gitweb_project_owner) {
3273 git_get_project_list_from_file();
3276 if (exists $gitweb_project_owner->{$project}) {
3277 $owner = $gitweb_project_owner->{$project};
3279 if (!defined $owner){
3280 $owner = git_get_project_config('owner');
3282 if (!defined $owner) {
3283 $owner = get_file_owner("$git_dir");
3286 return $owner;
3289 sub git_get_last_activity {
3290 my ($path) = @_;
3291 my $fd;
3293 $git_dir = "$projectroot/$path";
3294 defined($fd = git_cmd_pipe 'for-each-ref',
3295 '--format=%(committer)',
3296 '--sort=-committerdate',
3297 '--count=1',
3298 map { "refs/$_" } get_branch_refs ()) or return;
3299 my $most_recent = <$fd>;
3300 close $fd or return;
3301 if (defined $most_recent &&
3302 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3303 my $timestamp = $1;
3304 my $age = time - $timestamp;
3305 return ($age, age_string($age));
3307 return (undef, undef);
3310 # Implementation note: when a single remote is wanted, we cannot use 'git
3311 # remote show -n' because that command always work (assuming it's a remote URL
3312 # if it's not defined), and we cannot use 'git remote show' because that would
3313 # try to make a network roundtrip. So the only way to find if that particular
3314 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3315 # and when we find what we want.
3316 sub git_get_remotes_list {
3317 my $wanted = shift;
3318 my %remotes = ();
3320 my $fd = git_cmd_pipe 'remote', '-v';
3321 return unless $fd;
3322 while (my $remote = to_utf8(scalar <$fd>)) {
3323 chomp $remote;
3324 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3325 next if $wanted and not $remote eq $wanted;
3326 my ($url, $key) = ($1, $2);
3328 $remotes{$remote} ||= { 'heads' => () };
3329 $remotes{$remote}{$key} = $url;
3331 close $fd or return;
3332 return wantarray ? %remotes : \%remotes;
3335 # Takes a hash of remotes as first parameter and fills it by adding the
3336 # available remote heads for each of the indicated remotes.
3337 sub fill_remote_heads {
3338 my $remotes = shift;
3339 my @heads = map { "remotes/$_" } keys %$remotes;
3340 my @remoteheads = git_get_heads_list(undef, @heads);
3341 foreach my $remote (keys %$remotes) {
3342 $remotes->{$remote}{'heads'} = [ grep {
3343 $_->{'name'} =~ s!^$remote/!!
3344 } @remoteheads ];
3348 sub git_get_references {
3349 my $type = shift || "";
3350 my %refs;
3351 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3352 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3353 defined(my $fd = git_cmd_pipe "show-ref", "--dereference",
3354 ($type ? ("--", "refs/$type") : ())) # use -- <pattern> if $type
3355 or return;
3357 while (my $line = to_utf8(scalar <$fd>)) {
3358 chomp $line;
3359 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3360 if (defined $refs{$1}) {
3361 push @{$refs{$1}}, $2;
3362 } else {
3363 $refs{$1} = [ $2 ];
3367 close $fd or return;
3368 return \%refs;
3371 sub git_get_rev_name_tags {
3372 my $hash = shift || return undef;
3374 defined(my $fd = git_cmd_pipe "name-rev", "--tags", $hash)
3375 or return;
3376 my $name_rev = to_utf8(scalar <$fd>);
3377 close $fd;
3379 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3380 return $1;
3381 } else {
3382 # catches also '$hash undefined' output
3383 return undef;
3387 ## ----------------------------------------------------------------------
3388 ## parse to hash functions
3390 sub parse_date {
3391 my $epoch = shift;
3392 my $tz = shift || "-0000";
3394 my %date;
3395 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3396 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3397 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3398 $date{'hour'} = $hour;
3399 $date{'minute'} = $min;
3400 $date{'mday'} = $mday;
3401 $date{'day'} = $days[$wday];
3402 $date{'month'} = $months[$mon];
3403 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3404 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3405 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3406 $mday, $months[$mon], $hour ,$min;
3407 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3408 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3410 my ($tz_sign, $tz_hour, $tz_min) =
3411 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3412 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3413 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3414 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3415 $date{'hour_local'} = $hour;
3416 $date{'minute_local'} = $min;
3417 $date{'tz_local'} = $tz;
3418 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3419 1900+$year, $mon+1, $mday,
3420 $hour, $min, $sec, $tz);
3421 return %date;
3424 sub parse_tag {
3425 my $tag_id = shift;
3426 my %tag;
3427 my @comment;
3429 defined(my $fd = git_cmd_pipe "cat-file", "tag", $tag_id) or return;
3430 $tag{'id'} = $tag_id;
3431 while (my $line = to_utf8(scalar <$fd>)) {
3432 chomp $line;
3433 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3434 $tag{'object'} = $1;
3435 } elsif ($line =~ m/^type (.+)$/) {
3436 $tag{'type'} = $1;
3437 } elsif ($line =~ m/^tag (.+)$/) {
3438 $tag{'name'} = $1;
3439 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3440 $tag{'author'} = $1;
3441 $tag{'author_epoch'} = $2;
3442 $tag{'author_tz'} = $3;
3443 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3444 $tag{'author_name'} = $1;
3445 $tag{'author_email'} = $2;
3446 } else {
3447 $tag{'author_name'} = $tag{'author'};
3449 } elsif ($line =~ m/--BEGIN/) {
3450 push @comment, $line;
3451 last;
3452 } elsif ($line eq "") {
3453 last;
3456 push @comment, map(to_utf8($_), <$fd>);
3457 $tag{'comment'} = \@comment;
3458 close $fd or return;
3459 if (!defined $tag{'name'}) {
3460 return
3462 return %tag
3465 sub parse_commit_text {
3466 my ($commit_text, $withparents) = @_;
3467 my @commit_lines = split '\n', $commit_text;
3468 my %co;
3470 pop @commit_lines; # Remove '\0'
3472 if (! @commit_lines) {
3473 return;
3476 my $header = shift @commit_lines;
3477 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3478 return;
3480 ($co{'id'}, my @parents) = split ' ', $header;
3481 while (my $line = shift @commit_lines) {
3482 last if $line eq "\n";
3483 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3484 $co{'tree'} = $1;
3485 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3486 push @parents, $1;
3487 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3488 $co{'author'} = to_utf8($1);
3489 $co{'author_epoch'} = $2;
3490 $co{'author_tz'} = $3;
3491 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3492 $co{'author_name'} = $1;
3493 $co{'author_email'} = $2;
3494 } else {
3495 $co{'author_name'} = $co{'author'};
3497 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3498 $co{'committer'} = to_utf8($1);
3499 $co{'committer_epoch'} = $2;
3500 $co{'committer_tz'} = $3;
3501 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3502 $co{'committer_name'} = $1;
3503 $co{'committer_email'} = $2;
3504 } else {
3505 $co{'committer_name'} = $co{'committer'};
3509 if (!defined $co{'tree'}) {
3510 return;
3512 $co{'parents'} = \@parents;
3513 $co{'parent'} = $parents[0];
3515 @commit_lines = map to_utf8($_), @commit_lines;
3516 foreach my $title (@commit_lines) {
3517 $title =~ s/^ //;
3518 if ($title ne "") {
3519 $co{'title'} = chop_str($title, 80, 5);
3520 # remove leading stuff of merges to make the interesting part visible
3521 if (length($title) > 50) {
3522 $title =~ s/^Automatic //;
3523 $title =~ s/^merge (of|with) /Merge ... /i;
3524 if (length($title) > 50) {
3525 $title =~ s/(http|rsync):\/\///;
3527 if (length($title) > 50) {
3528 $title =~ s/(master|www|rsync)\.//;
3530 if (length($title) > 50) {
3531 $title =~ s/kernel.org:?//;
3533 if (length($title) > 50) {
3534 $title =~ s/\/pub\/scm//;
3537 $co{'title_short'} = chop_str($title, 50, 5);
3538 last;
3541 if (! defined $co{'title'} || $co{'title'} eq "") {
3542 $co{'title'} = $co{'title_short'} = '(no commit message)';
3544 # remove added spaces
3545 foreach my $line (@commit_lines) {
3546 $line =~ s/^ //;
3548 $co{'comment'} = \@commit_lines;
3550 my $age = time - $co{'committer_epoch'};
3551 $co{'age'} = $age;
3552 $co{'age_string'} = age_string($age);
3553 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3554 if ($age > 60*60*24*7*2) {
3555 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3556 $co{'age_string_age'} = $co{'age_string'};
3557 } else {
3558 $co{'age_string_date'} = $co{'age_string'};
3559 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3561 return %co;
3564 sub parse_commit {
3565 my ($commit_id) = @_;
3566 my %co;
3568 local $/ = "\0";
3570 defined(my $fd = git_cmd_pipe "rev-list",
3571 "--parents",
3572 "--header",
3573 "--max-count=1",
3574 $commit_id,
3575 "--")
3576 or die_error(500, "Open git-rev-list failed");
3577 %co = parse_commit_text(<$fd>, 1);
3578 close $fd;
3580 return %co;
3583 sub parse_commits {
3584 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3585 my @cos;
3587 $maxcount ||= 1;
3588 $skip ||= 0;
3590 local $/ = "\0";
3592 defined(my $fd = git_cmd_pipe "rev-list",
3593 "--header",
3594 @args,
3595 ("--max-count=" . $maxcount),
3596 ("--skip=" . $skip),
3597 @extra_options,
3598 $commit_id,
3599 "--",
3600 ($filename ? ($filename) : ()))
3601 or die_error(500, "Open git-rev-list failed");
3602 while (my $line = <$fd>) {
3603 my %co = parse_commit_text($line);
3604 push @cos, \%co;
3606 close $fd;
3608 return wantarray ? @cos : \@cos;
3611 # parse line of git-diff-tree "raw" output
3612 sub parse_difftree_raw_line {
3613 my $line = shift;
3614 my %res;
3616 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3617 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3618 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3619 $res{'from_mode'} = $1;
3620 $res{'to_mode'} = $2;
3621 $res{'from_id'} = $3;
3622 $res{'to_id'} = $4;
3623 $res{'status'} = $5;
3624 $res{'similarity'} = $6;
3625 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3626 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3627 } else {
3628 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3631 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3632 # combined diff (for merge commit)
3633 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3634 $res{'nparents'} = length($1);
3635 $res{'from_mode'} = [ split(' ', $2) ];
3636 $res{'to_mode'} = pop @{$res{'from_mode'}};
3637 $res{'from_id'} = [ split(' ', $3) ];
3638 $res{'to_id'} = pop @{$res{'from_id'}};
3639 $res{'status'} = [ split('', $4) ];
3640 $res{'to_file'} = unquote($5);
3642 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3643 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3644 $res{'commit'} = $1;
3647 return wantarray ? %res : \%res;
3650 # wrapper: return parsed line of git-diff-tree "raw" output
3651 # (the argument might be raw line, or parsed info)
3652 sub parsed_difftree_line {
3653 my $line_or_ref = shift;
3655 if (ref($line_or_ref) eq "HASH") {
3656 # pre-parsed (or generated by hand)
3657 return $line_or_ref;
3658 } else {
3659 return parse_difftree_raw_line($line_or_ref);
3663 # parse line of git-ls-tree output
3664 sub parse_ls_tree_line {
3665 my $line = shift;
3666 my %opts = @_;
3667 my %res;
3669 if ($opts{'-l'}) {
3670 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3671 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3673 $res{'mode'} = $1;
3674 $res{'type'} = $2;
3675 $res{'hash'} = $3;
3676 $res{'size'} = $4;
3677 if ($opts{'-z'}) {
3678 $res{'name'} = $5;
3679 } else {
3680 $res{'name'} = unquote($5);
3682 } else {
3683 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3684 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3686 $res{'mode'} = $1;
3687 $res{'type'} = $2;
3688 $res{'hash'} = $3;
3689 if ($opts{'-z'}) {
3690 $res{'name'} = $4;
3691 } else {
3692 $res{'name'} = unquote($4);
3696 return wantarray ? %res : \%res;
3699 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3700 sub parse_from_to_diffinfo {
3701 my ($diffinfo, $from, $to, @parents) = @_;
3703 if ($diffinfo->{'nparents'}) {
3704 # combined diff
3705 $from->{'file'} = [];
3706 $from->{'href'} = [];
3707 fill_from_file_info($diffinfo, @parents)
3708 unless exists $diffinfo->{'from_file'};
3709 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3710 $from->{'file'}[$i] =
3711 defined $diffinfo->{'from_file'}[$i] ?
3712 $diffinfo->{'from_file'}[$i] :
3713 $diffinfo->{'to_file'};
3714 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3715 $from->{'href'}[$i] = href(action=>"blob",
3716 hash_base=>$parents[$i],
3717 hash=>$diffinfo->{'from_id'}[$i],
3718 file_name=>$from->{'file'}[$i]);
3719 } else {
3720 $from->{'href'}[$i] = undef;
3723 } else {
3724 # ordinary (not combined) diff
3725 $from->{'file'} = $diffinfo->{'from_file'};
3726 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3727 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3728 hash=>$diffinfo->{'from_id'},
3729 file_name=>$from->{'file'});
3730 } else {
3731 delete $from->{'href'};
3735 $to->{'file'} = $diffinfo->{'to_file'};
3736 if (!is_deleted($diffinfo)) { # file exists in result
3737 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3738 hash=>$diffinfo->{'to_id'},
3739 file_name=>$to->{'file'});
3740 } else {
3741 delete $to->{'href'};
3745 ## ......................................................................
3746 ## parse to array of hashes functions
3748 sub git_get_heads_list {
3749 my ($limit, @classes) = @_;
3750 @classes = get_branch_refs() unless @classes;
3751 my @patterns = map { "refs/$_" } @classes;
3752 my @headslist;
3754 defined(my $fd = git_cmd_pipe 'for-each-ref',
3755 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3756 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3757 @patterns)
3758 or return;
3759 while (my $line = to_utf8(scalar <$fd>)) {
3760 my %ref_item;
3762 chomp $line;
3763 my ($refinfo, $committerinfo) = split(/\0/, $line);
3764 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3765 my ($committer, $epoch, $tz) =
3766 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3767 $ref_item{'fullname'} = $name;
3768 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3769 $name =~ s!^refs/($strip_refs|remotes)/!!;
3770 $ref_item{'name'} = $name;
3771 # for refs neither in 'heads' nor 'remotes' we want to
3772 # show their ref dir
3773 my $ref_dir = (defined $1) ? $1 : '';
3774 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3775 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3778 $ref_item{'id'} = $hash;
3779 $ref_item{'title'} = $title || '(no commit message)';
3780 $ref_item{'epoch'} = $epoch;
3781 if ($epoch) {
3782 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3783 } else {
3784 $ref_item{'age'} = "unknown";
3787 push @headslist, \%ref_item;
3789 close $fd;
3791 return wantarray ? @headslist : \@headslist;
3794 sub git_get_tags_list {
3795 my $limit = shift;
3796 my @tagslist;
3798 defined(my $fd = git_cmd_pipe 'for-each-ref',
3799 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3800 '--format=%(objectname) %(objecttype) %(refname) '.
3801 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3802 'refs/tags')
3803 or return;
3804 while (my $line = to_utf8(scalar <$fd>)) {
3805 my %ref_item;
3807 chomp $line;
3808 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3809 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3810 my ($creator, $epoch, $tz) =
3811 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3812 $ref_item{'fullname'} = $name;
3813 $name =~ s!^refs/tags/!!;
3815 $ref_item{'type'} = $type;
3816 $ref_item{'id'} = $id;
3817 $ref_item{'name'} = $name;
3818 if ($type eq "tag") {
3819 $ref_item{'subject'} = $title;
3820 $ref_item{'reftype'} = $reftype;
3821 $ref_item{'refid'} = $refid;
3822 } else {
3823 $ref_item{'reftype'} = $type;
3824 $ref_item{'refid'} = $id;
3827 if ($type eq "tag" || $type eq "commit") {
3828 $ref_item{'epoch'} = $epoch;
3829 if ($epoch) {
3830 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3831 } else {
3832 $ref_item{'age'} = "unknown";
3836 push @tagslist, \%ref_item;
3838 close $fd;
3840 return wantarray ? @tagslist : \@tagslist;
3843 ## ----------------------------------------------------------------------
3844 ## filesystem-related functions
3846 sub get_file_owner {
3847 my $path = shift;
3849 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3850 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3851 if (!defined $gcos) {
3852 return undef;
3854 my $owner = $gcos;
3855 $owner =~ s/[,;].*$//;
3856 return to_utf8($owner);
3859 # assume that file exists
3860 sub insert_file {
3861 my $filename = shift;
3863 open my $fd, '<', $filename;
3864 print map { to_utf8($_) } <$fd>;
3865 close $fd;
3868 ## ......................................................................
3869 ## mimetype related functions
3871 sub mimetype_guess_file {
3872 my $filename = shift;
3873 my $mimemap = shift;
3874 -r $mimemap or return undef;
3876 my %mimemap;
3877 open(my $mh, '<', $mimemap) or return undef;
3878 while (<$mh>) {
3879 next if m/^#/; # skip comments
3880 my ($mimetype, @exts) = split(/\s+/);
3881 foreach my $ext (@exts) {
3882 $mimemap{$ext} = $mimetype;
3885 close($mh);
3887 my ($ext, $ans);
3888 $ext = $1 if $filename =~ /\.([^.]*)$/;
3889 $ans = $mimemap{$ext} if $ext;
3890 $ans = 'text/html' if $ans && lc($ans) eq 'application/xhtml+xml';
3891 return $ans;
3894 sub mimetype_guess {
3895 my $filename = shift;
3896 my $mime;
3897 $filename =~ /\./ or return undef;
3899 if ($mimetypes_file) {
3900 my $file = $mimetypes_file;
3901 if ($file !~ m!^/!) { # if it is relative path
3902 # it is relative to project
3903 $file = "$projectroot/$project/$file";
3905 $mime = mimetype_guess_file($filename, $file);
3907 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3908 return $mime;
3911 sub blob_mimetype {
3912 my $fd = shift;
3913 my $filename = shift;
3914 my $mime;
3916 # The -T/-B file operators produce the wrong result unless a perlio
3917 # layer is present when the file handle is a pipe that delivers less
3918 # than 512 bytes of data before reaching EOF.
3920 # If we are running in a Perl that uses the stdio layer rather than the
3921 # unix+perlio layers we will end up adding a perlio layer on top of the
3922 # stdio layer and get a second level of buffering. This is harmless
3923 # and it makes the -T/-B file operators work properly in all cases.
3925 binmode $fd, ":perlio" or die_error(500, "Adding perlio layer failed")
3926 unless grep /^perlio$/, PerlIO::get_layers($fd);
3928 $mime = mimetype_guess($filename) if defined $filename;
3930 if (!$mime && $filename) {
3931 if ($filename =~ m/\.html?$/i) {
3932 $mime = 'text/html';
3933 } elsif ($filename =~ m/\.xht(?:ml)?$/i) {
3934 $mime = 'text/html';
3935 } elsif ($filename =~ m/\.te?xt?$/i) {
3936 $mime = 'text/plain';
3937 } elsif ($filename =~ m/\.(?:markdown|md)$/i) {
3938 $mime = 'text/plain';
3939 } elsif ($filename =~ m/\.png$/i) {
3940 $mime = 'image/png';
3941 } elsif ($filename =~ m/\.gif$/i) {
3942 $mime = 'image/gif';
3943 } elsif ($filename =~ m/\.jpe?g$/i) {
3944 $mime = 'image/jpeg';
3945 } elsif ($filename =~ m/\.svgz?$/i) {
3946 $mime = 'image/svg+xml';
3950 # just in case
3951 return $default_blob_plain_mimetype || 'application/octet-stream' unless $fd || $mime;
3953 $mime = -T $fd ? 'text/plain' : 'application/octet-stream' unless $mime;
3955 return $mime;
3958 sub is_ascii {
3959 use bytes;
3960 my $data = shift;
3961 return scalar($data =~ /^[\x00-\x7f]*$/);
3964 sub is_valid_utf8 {
3965 my $data = shift;
3966 return utf8::decode($data);
3969 sub extract_html_charset {
3970 return undef unless $_[0] && "$_[0]</head>" =~ m#<head(?:\s+[^>]*)?(?<!/)>(.*?)</head\s*>#is;
3971 my $head = $1;
3972 return $2 if $head =~ m#<meta\s+charset\s*=\s*(['"])\s*([a-z0-9(:)_.+-]+)\s*\1\s*/?>#is;
3973 while ($head =~ m#<meta\s+(http-equiv|content)\s*=\s*(['"])\s*([^\2]+?)\s*\2\s*(http-equiv|content)\s*=\s*(['"])\s*([^\5]+?)\s*\5\s*/?>#sig) {
3974 my %kv = (lc($1) => $3, lc($4) => $6);
3975 my ($he, $c) = (lc($kv{'http-equiv'}), $kv{'content'});
3976 return $1 if $he && $c && $he eq 'content-type' &&
3977 $c =~ m!\s*text/html\s*;\s*charset\s*=\s*([a-z0-9(:)_.+-]+)\s*$!is;
3979 return undef;
3982 sub blob_contenttype {
3983 my ($fd, $file_name, $type) = @_;
3985 $type ||= blob_mimetype($fd, $file_name);
3986 return $type unless $type =~ m!^text/.+!i;
3987 my ($leader, $charset, $htmlcharset);
3988 if ($fd && read($fd, $leader, 16384)) {{
3989 $charset='US-ASCII' if is_ascii($leader);
3990 return ("$type; charset=UTF-8", $leader) if !$charset && is_valid_utf8($leader);
3991 $charset='ISO-8859-1' unless $charset;
3992 $htmlcharset = extract_html_charset($leader) if $type eq 'text/html';
3993 if ($htmlcharset && $charset ne 'US-ASCII') {
3994 $htmlcharset = undef if $htmlcharset =~ /^(?:utf-8|us-ascii)$/i
3997 return ("$type; charset=$htmlcharset", $leader) if $htmlcharset;
3998 my $defcharset = $default_text_plain_charset || '';
3999 $defcharset =~ s/^\s+//;
4000 $defcharset =~ s/\s+$//;
4001 $defcharset = '' if $charset && $charset ne 'US-ASCII' && $defcharset =~ /^(?:utf-8|us-ascii)$/i;
4002 return ("$type: charset=" . ($defcharset || 'ISO-8859-1'), $leader);
4005 # guess file syntax for syntax highlighting; return undef if no highlighting
4006 # the name of syntax can (in the future) depend on syntax highlighter used
4007 sub guess_file_syntax {
4008 my ($highlight, $mimetype, $file_name) = @_;
4009 return undef unless ($highlight && defined $file_name);
4010 my $basename = basename($file_name, '.in');
4011 return $highlight_basename{$basename}
4012 if exists $highlight_basename{$basename};
4014 $basename =~ /\.([^.]*)$/;
4015 my $ext = $1 or return undef;
4016 return $highlight_ext{$ext}
4017 if exists $highlight_ext{$ext};
4019 return undef;
4022 # run highlighter and return FD of its output,
4023 # or return original FD if no highlighting
4024 sub run_highlighter {
4025 my ($fd, $highlight, $syntax) = @_;
4026 return $fd unless ($highlight && defined $syntax);
4028 close $fd;
4029 defined($fd = cmd_pipe $posix_shell_bin, '-c',
4030 quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
4031 quote_command($highlight_bin).
4032 " --replace-tabs=8 --fragment --syntax $syntax")
4033 or die_error(500, "Couldn't open file or run syntax highlighter");
4034 return $fd;
4037 ## ======================================================================
4038 ## functions printing HTML: header, footer, error page
4040 sub get_page_title {
4041 my $title = to_utf8($site_name);
4043 unless (defined $project) {
4044 if (defined $project_filter) {
4045 $title .= " - projects in '" . esc_path($project_filter) . "'";
4047 return $title;
4049 $title .= " - " . to_utf8($project);
4051 return $title unless (defined $action);
4052 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
4054 return $title unless (defined $file_name);
4055 $title .= " - " . esc_path($file_name);
4056 if ($action eq "tree" && $file_name !~ m|/$|) {
4057 $title .= "/";
4060 return $title;
4063 sub get_content_type_html {
4064 # require explicit support from the UA if we are to send the page as
4065 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4066 # we have to do this because MSIE sometimes globs '*/*', pretending to
4067 # support xhtml+xml but choking when it gets what it asked for.
4068 if (defined $cgi->http('HTTP_ACCEPT') &&
4069 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4070 $cgi->Accept('application/xhtml+xml') != 0) {
4071 return 'application/xhtml+xml';
4072 } else {
4073 return 'text/html';
4077 sub print_feed_meta {
4078 if (defined $project) {
4079 my %href_params = get_feed_info();
4080 if (!exists $href_params{'-title'}) {
4081 $href_params{'-title'} = 'log';
4084 foreach my $format (qw(RSS Atom)) {
4085 my $type = lc($format);
4086 my %link_attr = (
4087 '-rel' => 'alternate',
4088 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4089 '-type' => "application/$type+xml"
4092 $href_params{'extra_options'} = undef;
4093 $href_params{'action'} = $type;
4094 $link_attr{'-href'} = href(%href_params);
4095 print "<link ".
4096 "rel=\"$link_attr{'-rel'}\" ".
4097 "title=\"$link_attr{'-title'}\" ".
4098 "href=\"$link_attr{'-href'}\" ".
4099 "type=\"$link_attr{'-type'}\" ".
4100 "/>\n";
4102 $href_params{'extra_options'} = '--no-merges';
4103 $link_attr{'-href'} = href(%href_params);
4104 $link_attr{'-title'} .= ' (no merges)';
4105 print "<link ".
4106 "rel=\"$link_attr{'-rel'}\" ".
4107 "title=\"$link_attr{'-title'}\" ".
4108 "href=\"$link_attr{'-href'}\" ".
4109 "type=\"$link_attr{'-type'}\" ".
4110 "/>\n";
4113 } else {
4114 printf('<link rel="alternate" title="%s projects list" '.
4115 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4116 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4117 printf('<link rel="alternate" title="%s projects feeds" '.
4118 'href="%s" type="text/x-opml" />'."\n",
4119 esc_attr($site_name), href(project=>undef, action=>"opml"));
4123 sub print_header_links {
4124 my $status = shift;
4126 # print out each stylesheet that exist, providing backwards capability
4127 # for those people who defined $stylesheet in a config file
4128 if (defined $stylesheet) {
4129 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4130 } else {
4131 foreach my $stylesheet (@stylesheets) {
4132 next unless $stylesheet;
4133 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4136 print_feed_meta()
4137 if ($status eq '200 OK');
4138 if (defined $favicon) {
4139 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4143 sub print_nav_breadcrumbs_path {
4144 my $dirprefix = undef;
4145 while (my $part = shift) {
4146 $dirprefix .= "/" if defined $dirprefix;
4147 $dirprefix .= $part;
4148 print $cgi->a({-href => href(project => undef,
4149 project_filter => $dirprefix,
4150 action => "project_list")},
4151 esc_html($part)) . " / ";
4155 sub print_nav_breadcrumbs {
4156 my %opts = @_;
4158 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4159 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4161 if (defined $project) {
4162 my @dirname = split '/', $project;
4163 my $projectbasename = pop @dirname;
4164 print_nav_breadcrumbs_path(@dirname);
4165 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4166 if (defined $action) {
4167 my $action_print = $action ;
4168 if (defined $opts{-action_extra}) {
4169 $action_print = $cgi->a({-href => href(action=>$action)},
4170 $action);
4172 print " / $action_print";
4174 if (defined $opts{-action_extra}) {
4175 print " / $opts{-action_extra}";
4177 print "\n";
4178 } elsif (defined $project_filter) {
4179 print_nav_breadcrumbs_path(split '/', $project_filter);
4183 sub print_search_form {
4184 if (!defined $searchtext) {
4185 $searchtext = "";
4187 my $search_hash;
4188 if (defined $hash_base) {
4189 $search_hash = $hash_base;
4190 } elsif (defined $hash) {
4191 $search_hash = $hash;
4192 } else {
4193 $search_hash = "HEAD";
4195 my $action = $my_uri;
4196 my $use_pathinfo = gitweb_check_feature('pathinfo');
4197 if ($use_pathinfo) {
4198 $action .= "/".esc_url($project);
4200 print $cgi->start_form(-method => "get", -action => $action) .
4201 "<div class=\"search\">\n" .
4202 (!$use_pathinfo &&
4203 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4204 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4205 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4206 $cgi->popup_menu(-name => 'st', -default => 'commit',
4207 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4208 " " . $cgi->a({-href => href(action=>"search_help"),
4209 -title => "search help" }, "?") . " search:\n",
4210 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4211 "<span title=\"Extended regular expression\">" .
4212 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4213 -checked => $search_use_regexp) .
4214 "</span>" .
4215 "</div>" .
4216 $cgi->end_form() . "\n";
4219 sub git_header_html {
4220 my $status = shift || "200 OK";
4221 my $expires = shift;
4222 my %opts = @_;
4224 my $title = get_page_title();
4225 my $content_type = get_content_type_html();
4226 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4227 -status=> $status, -expires => $expires)
4228 unless ($opts{'-no_http_header'});
4229 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4230 print <<EOF;
4231 <?xml version="1.0" encoding="utf-8"?>
4232 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4233 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4234 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4235 <!-- git core binaries version $git_version -->
4236 <head>
4237 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4238 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4239 <meta name="robots" content="index, nofollow"/>
4240 <title>$title</title>
4242 # the stylesheet, favicon etc urls won't work correctly with path_info
4243 # unless we set the appropriate base URL
4244 if ($ENV{'PATH_INFO'}) {
4245 print "<base href=\"".esc_url($base_url)."\" />\n";
4247 print_header_links($status);
4249 if (defined $site_html_head_string) {
4250 print to_utf8($site_html_head_string);
4253 print "</head>\n" .
4254 "<body>\n";
4256 if (defined $site_header && -f $site_header) {
4257 insert_file($site_header);
4260 print "<div class=\"page_header\">\n";
4261 if (defined $logo) {
4262 print $cgi->a({-href => esc_url($logo_url),
4263 -title => $logo_label},
4264 $cgi->img({-src => esc_url($logo),
4265 -width => 72, -height => 27,
4266 -alt => "git",
4267 -class => "logo"}));
4269 print_nav_breadcrumbs(%opts);
4270 print "</div>\n";
4272 my $have_search = gitweb_check_feature('search');
4273 if (defined $project && $have_search) {
4274 print_search_form();
4278 sub git_footer_html {
4279 my $feed_class = 'rss_logo';
4281 print "<div class=\"page_footer\">\n";
4282 if (defined $project) {
4283 my $descr = git_get_project_description($project);
4284 if (defined $descr) {
4285 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4288 my %href_params = get_feed_info();
4289 if (!%href_params) {
4290 $feed_class .= ' generic';
4292 $href_params{'-title'} ||= 'log';
4294 foreach my $format (qw(RSS Atom)) {
4295 $href_params{'action'} = lc($format);
4296 print $cgi->a({-href => href(%href_params),
4297 -title => "$href_params{'-title'} $format feed",
4298 -class => $feed_class}, $format)."\n";
4301 } else {
4302 print $cgi->a({-href => href(project=>undef, action=>"opml",
4303 project_filter => $project_filter),
4304 -class => $feed_class}, "OPML") . " ";
4305 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4306 project_filter => $project_filter),
4307 -class => $feed_class}, "TXT") . "\n";
4309 print "</div>\n"; # class="page_footer"
4311 if (defined $t0 && gitweb_check_feature('timed')) {
4312 print "<div id=\"generating_info\">\n";
4313 print 'This page took '.
4314 '<span id="generating_time" class="time_span">'.
4315 tv_interval($t0, [ gettimeofday() ]).
4316 ' seconds </span>'.
4317 ' and '.
4318 '<span id="generating_cmd">'.
4319 $number_of_git_cmds.
4320 '</span> git commands '.
4321 " to generate.\n";
4322 print "</div>\n"; # class="page_footer"
4325 if (defined $site_footer && -f $site_footer) {
4326 insert_file($site_footer);
4329 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4330 if (defined $action &&
4331 $action eq 'blame_incremental') {
4332 print qq!<script type="text/javascript">\n!.
4333 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4334 qq! "!. href() .qq!");\n!.
4335 qq!</script>\n!;
4336 } else {
4337 my ($jstimezone, $tz_cookie, $datetime_class) =
4338 gitweb_get_feature('javascript-timezone');
4340 print qq!<script type="text/javascript">\n!.
4341 qq!window.onload = function () {\n!;
4342 if (gitweb_check_feature('javascript-actions')) {
4343 print qq! fixLinks();\n!;
4345 if ($jstimezone && $tz_cookie && $datetime_class) {
4346 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4347 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4349 print qq!};\n!.
4350 qq!</script>\n!;
4353 print "</body>\n" .
4354 "</html>";
4357 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4358 # Example: die_error(404, 'Hash not found')
4359 # By convention, use the following status codes (as defined in RFC 2616):
4360 # 400: Invalid or missing CGI parameters, or
4361 # requested object exists but has wrong type.
4362 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4363 # this server or project.
4364 # 404: Requested object/revision/project doesn't exist.
4365 # 500: The server isn't configured properly, or
4366 # an internal error occurred (e.g. failed assertions caused by bugs), or
4367 # an unknown error occurred (e.g. the git binary died unexpectedly).
4368 # 503: The server is currently unavailable (because it is overloaded,
4369 # or down for maintenance). Generally, this is a temporary state.
4370 sub die_error {
4371 my $status = shift || 500;
4372 my $error = esc_html(shift) || "Internal Server Error";
4373 my $extra = shift;
4374 my %opts = @_;
4376 my %http_responses = (
4377 400 => '400 Bad Request',
4378 403 => '403 Forbidden',
4379 404 => '404 Not Found',
4380 500 => '500 Internal Server Error',
4381 503 => '503 Service Unavailable',
4383 git_header_html($http_responses{$status}, undef, %opts);
4384 print <<EOF;
4385 <div class="page_body">
4386 <br /><br />
4387 $status - $error
4388 <br />
4390 if (defined $extra) {
4391 print "<hr />\n" .
4392 "$extra\n";
4394 print "</div>\n";
4396 git_footer_html();
4397 goto DONE_GITWEB
4398 unless ($opts{'-error_handler'});
4401 ## ----------------------------------------------------------------------
4402 ## functions printing or outputting HTML: navigation
4404 sub git_print_page_nav {
4405 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4406 $extra = '' if !defined $extra; # pager or formats
4408 my @navs = qw(summary shortlog log commit commitdiff tree);
4409 if ($suppress) {
4410 @navs = grep { $_ ne $suppress } @navs;
4413 my %arg = map { $_ => {action=>$_} } @navs;
4414 if (defined $head) {
4415 for (qw(commit commitdiff)) {
4416 $arg{$_}{'hash'} = $head;
4418 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4419 for (qw(shortlog log)) {
4420 $arg{$_}{'hash'} = $head;
4425 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4426 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4428 my @actions = gitweb_get_feature('actions');
4429 my %repl = (
4430 '%' => '%',
4431 'n' => $project, # project name
4432 'f' => $git_dir, # project path within filesystem
4433 'h' => $treehead || '', # current hash ('h' parameter)
4434 'b' => $treebase || '', # hash base ('hb' parameter)
4436 while (@actions) {
4437 my ($label, $link, $pos) = splice(@actions,0,3);
4438 # insert
4439 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4440 # munch munch
4441 $link =~ s/%([%nfhb])/$repl{$1}/g;
4442 $arg{$label}{'_href'} = $link;
4445 print "<div class=\"page_nav\">\n" .
4446 (join " | ",
4447 map { $_ eq $current ?
4448 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4449 } @navs);
4450 print "<br/>\n$extra<br/>\n" .
4451 "</div>\n";
4454 # returns a submenu for the nagivation of the refs views (tags, heads,
4455 # remotes) with the current view disabled and the remotes view only
4456 # available if the feature is enabled
4457 sub format_ref_views {
4458 my ($current) = @_;
4459 my @ref_views = qw{tags heads};
4460 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4461 return join " | ", map {
4462 $_ eq $current ? $_ :
4463 $cgi->a({-href => href(action=>$_)}, $_)
4464 } @ref_views
4467 sub format_paging_nav {
4468 my ($action, $page, $has_next_link) = @_;
4469 my $paging_nav;
4472 if ($page > 0) {
4473 $paging_nav .=
4474 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4475 " &sdot; " .
4476 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4477 -accesskey => "p", -title => "Alt-p"}, "prev");
4478 } else {
4479 $paging_nav .= "first &sdot; prev";
4482 if ($has_next_link) {
4483 $paging_nav .= " &sdot; " .
4484 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4485 -accesskey => "n", -title => "Alt-n"}, "next");
4486 } else {
4487 $paging_nav .= " &sdot; next";
4490 return $paging_nav;
4493 ## ......................................................................
4494 ## functions printing or outputting HTML: div
4496 sub git_print_header_div {
4497 my ($action, $title, $hash, $hash_base) = @_;
4498 my %args = ();
4500 $args{'action'} = $action;
4501 $args{'hash'} = $hash if $hash;
4502 $args{'hash_base'} = $hash_base if $hash_base;
4504 print "<div class=\"header\">\n" .
4505 $cgi->a({-href => href(%args), -class => "title"},
4506 $title ? $title : $action) .
4507 "\n</div>\n";
4510 sub format_repo_url {
4511 my ($name, $url) = @_;
4512 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4515 # Group output by placing it in a DIV element and adding a header.
4516 # Options for start_div() can be provided by passing a hash reference as the
4517 # first parameter to the function.
4518 # Options to git_print_header_div() can be provided by passing an array
4519 # reference. This must follow the options to start_div if they are present.
4520 # The content can be a scalar, which is output as-is, a scalar reference, which
4521 # is output after html escaping, an IO handle passed either as *handle or
4522 # *handle{IO}, or a function reference. In the latter case all following
4523 # parameters will be taken as argument to the content function call.
4524 sub git_print_section {
4525 my ($div_args, $header_args, $content);
4526 my $arg = shift;
4527 if (ref($arg) eq 'HASH') {
4528 $div_args = $arg;
4529 $arg = shift;
4531 if (ref($arg) eq 'ARRAY') {
4532 $header_args = $arg;
4533 $arg = shift;
4535 $content = $arg;
4537 print $cgi->start_div($div_args);
4538 git_print_header_div(@$header_args);
4540 if (ref($content) eq 'CODE') {
4541 $content->(@_);
4542 } elsif (ref($content) eq 'SCALAR') {
4543 print esc_html($$content);
4544 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4545 print map(to_utf8($_), <$content>);
4546 } elsif (!ref($content) && defined($content)) {
4547 print $content;
4550 print $cgi->end_div;
4553 sub format_timestamp_html {
4554 my $date = shift;
4555 my $strtime = $date->{'rfc2822'};
4557 my (undef, undef, $datetime_class) =
4558 gitweb_get_feature('javascript-timezone');
4559 if ($datetime_class) {
4560 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4563 my $localtime_format = '(%02d:%02d %s)';
4564 if ($date->{'hour_local'} < 6) {
4565 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4567 $strtime .= ' ' .
4568 sprintf($localtime_format,
4569 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4571 return $strtime;
4574 # Outputs the author name and date in long form
4575 sub git_print_authorship {
4576 my $co = shift;
4577 my %opts = @_;
4578 my $tag = $opts{-tag} || 'div';
4579 my $author = $co->{'author_name'};
4581 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4582 print "<$tag class=\"author_date\">" .
4583 format_search_author($author, "author", esc_html($author)) .
4584 " [".format_timestamp_html(\%ad)."]".
4585 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4586 "</$tag>\n";
4589 # Outputs table rows containing the full author or committer information,
4590 # in the format expected for 'commit' view (& similar).
4591 # Parameters are a commit hash reference, followed by the list of people
4592 # to output information for. If the list is empty it defaults to both
4593 # author and committer.
4594 sub git_print_authorship_rows {
4595 my $co = shift;
4596 # too bad we can't use @people = @_ || ('author', 'committer')
4597 my @people = @_;
4598 @people = ('author', 'committer') unless @people;
4599 foreach my $who (@people) {
4600 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4601 print "<tr><td>$who</td><td>" .
4602 format_search_author($co->{"${who}_name"}, $who,
4603 esc_html($co->{"${who}_name"})) . " " .
4604 format_search_author($co->{"${who}_email"}, $who,
4605 esc_html("<" . $co->{"${who}_email"} . ">")) .
4606 "</td><td rowspan=\"2\">" .
4607 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4608 "</td></tr>\n" .
4609 "<tr>" .
4610 "<td></td><td>" .
4611 format_timestamp_html(\%wd) .
4612 "</td>" .
4613 "</tr>\n";
4617 sub git_print_page_path {
4618 my $name = shift;
4619 my $type = shift;
4620 my $hb = shift;
4623 print "<div class=\"page_path\">";
4624 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4625 -title => 'tree root'}, to_utf8("[$project]"));
4626 print " / ";
4627 if (defined $name) {
4628 my @dirname = split '/', $name;
4629 my $basename = pop @dirname;
4630 my $fullname = '';
4632 foreach my $dir (@dirname) {
4633 $fullname .= ($fullname ? '/' : '') . $dir;
4634 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4635 hash_base=>$hb),
4636 -title => $fullname}, esc_path($dir));
4637 print " / ";
4639 if (defined $type && $type eq 'blob') {
4640 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4641 hash_base=>$hb),
4642 -title => $name}, esc_path($basename));
4643 } elsif (defined $type && $type eq 'tree') {
4644 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4645 hash_base=>$hb),
4646 -title => $name}, esc_path($basename));
4647 print " / ";
4648 } else {
4649 print esc_path($basename);
4652 print "<br/></div>\n";
4655 sub git_print_log {
4656 my $log = shift;
4657 my %opts = @_;
4659 if ($opts{'-remove_title'}) {
4660 # remove title, i.e. first line of log
4661 shift @$log;
4663 # remove leading empty lines
4664 while (defined $log->[0] && $log->[0] eq "") {
4665 shift @$log;
4668 # print log
4669 my $skip_blank_line = 0;
4670 foreach my $line (@$log) {
4671 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4672 if (! $opts{'-remove_signoff'}) {
4673 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4674 $skip_blank_line = 1;
4676 next;
4679 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4680 if (! $opts{'-remove_signoff'}) {
4681 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4682 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4683 "</span><br/>\n";
4684 $skip_blank_line = 1;
4686 next;
4689 # print only one empty line
4690 # do not print empty line after signoff
4691 if ($line eq "") {
4692 next if ($skip_blank_line);
4693 $skip_blank_line = 1;
4694 } else {
4695 $skip_blank_line = 0;
4698 print format_log_line_html($line) . "<br/>\n";
4701 if ($opts{'-final_empty_line'}) {
4702 # end with single empty line
4703 print "<br/>\n" unless $skip_blank_line;
4707 # return link target (what link points to)
4708 sub git_get_link_target {
4709 my $hash = shift;
4710 my $link_target;
4712 # read link
4713 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
4714 or return;
4716 local $/ = undef;
4717 $link_target = to_utf8(scalar <$fd>);
4719 close $fd
4720 or return;
4722 return $link_target;
4725 # given link target, and the directory (basedir) the link is in,
4726 # return target of link relative to top directory (top tree);
4727 # return undef if it is not possible (including absolute links).
4728 sub normalize_link_target {
4729 my ($link_target, $basedir) = @_;
4731 # absolute symlinks (beginning with '/') cannot be normalized
4732 return if (substr($link_target, 0, 1) eq '/');
4734 # normalize link target to path from top (root) tree (dir)
4735 my $path;
4736 if ($basedir) {
4737 $path = $basedir . '/' . $link_target;
4738 } else {
4739 # we are in top (root) tree (dir)
4740 $path = $link_target;
4743 # remove //, /./, and /../
4744 my @path_parts;
4745 foreach my $part (split('/', $path)) {
4746 # discard '.' and ''
4747 next if (!$part || $part eq '.');
4748 # handle '..'
4749 if ($part eq '..') {
4750 if (@path_parts) {
4751 pop @path_parts;
4752 } else {
4753 # link leads outside repository (outside top dir)
4754 return;
4756 } else {
4757 push @path_parts, $part;
4760 $path = join('/', @path_parts);
4762 return $path;
4765 # print tree entry (row of git_tree), but without encompassing <tr> element
4766 sub git_print_tree_entry {
4767 my ($t, $basedir, $hash_base, $have_blame) = @_;
4769 my %base_key = ();
4770 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4772 # The format of a table row is: mode list link. Where mode is
4773 # the mode of the entry, list is the name of the entry, an href,
4774 # and link is the action links of the entry.
4776 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4777 if (exists $t->{'size'}) {
4778 print "<td class=\"size\">$t->{'size'}</td>\n";
4780 if ($t->{'type'} eq "blob") {
4781 print "<td class=\"list\">" .
4782 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4783 file_name=>"$basedir$t->{'name'}", %base_key),
4784 -class => "list"}, esc_path($t->{'name'}));
4785 if (S_ISLNK(oct $t->{'mode'})) {
4786 my $link_target = git_get_link_target($t->{'hash'});
4787 if ($link_target) {
4788 my $norm_target = normalize_link_target($link_target, $basedir);
4789 if (defined $norm_target) {
4790 print " -> " .
4791 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4792 file_name=>$norm_target),
4793 -title => $norm_target}, esc_path($link_target));
4794 } else {
4795 print " -> " . esc_path($link_target);
4799 print "</td>\n";
4800 print "<td class=\"link\">";
4801 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4802 file_name=>"$basedir$t->{'name'}", %base_key)},
4803 "blob");
4804 if ($have_blame) {
4805 print " | " .
4806 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4807 file_name=>"$basedir$t->{'name'}", %base_key)},
4808 "blame");
4810 if (defined $hash_base) {
4811 print " | " .
4812 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4813 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4814 "history");
4816 print " | " .
4817 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4818 file_name=>"$basedir$t->{'name'}")},
4819 "raw");
4820 print "</td>\n";
4822 } elsif ($t->{'type'} eq "tree") {
4823 print "<td class=\"list\">";
4824 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4825 file_name=>"$basedir$t->{'name'}",
4826 %base_key)},
4827 esc_path($t->{'name'}));
4828 print "</td>\n";
4829 print "<td class=\"link\">";
4830 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4831 file_name=>"$basedir$t->{'name'}",
4832 %base_key)},
4833 "tree");
4834 if (defined $hash_base) {
4835 print " | " .
4836 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4837 file_name=>"$basedir$t->{'name'}")},
4838 "history");
4840 print "</td>\n";
4841 } else {
4842 # unknown object: we can only present history for it
4843 # (this includes 'commit' object, i.e. submodule support)
4844 print "<td class=\"list\">" .
4845 esc_path($t->{'name'}) .
4846 "</td>\n";
4847 print "<td class=\"link\">";
4848 if (defined $hash_base) {
4849 print $cgi->a({-href => href(action=>"history",
4850 hash_base=>$hash_base,
4851 file_name=>"$basedir$t->{'name'}")},
4852 "history");
4854 print "</td>\n";
4858 ## ......................................................................
4859 ## functions printing large fragments of HTML
4861 # get pre-image filenames for merge (combined) diff
4862 sub fill_from_file_info {
4863 my ($diff, @parents) = @_;
4865 $diff->{'from_file'} = [ ];
4866 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4867 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4868 if ($diff->{'status'}[$i] eq 'R' ||
4869 $diff->{'status'}[$i] eq 'C') {
4870 $diff->{'from_file'}[$i] =
4871 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4875 return $diff;
4878 # is current raw difftree line of file deletion
4879 sub is_deleted {
4880 my $diffinfo = shift;
4882 return $diffinfo->{'to_id'} eq ('0' x 40);
4885 # does patch correspond to [previous] difftree raw line
4886 # $diffinfo - hashref of parsed raw diff format
4887 # $patchinfo - hashref of parsed patch diff format
4888 # (the same keys as in $diffinfo)
4889 sub is_patch_split {
4890 my ($diffinfo, $patchinfo) = @_;
4892 return defined $diffinfo && defined $patchinfo
4893 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4897 sub git_difftree_body {
4898 my ($difftree, $hash, @parents) = @_;
4899 my ($parent) = $parents[0];
4900 my $have_blame = gitweb_check_feature('blame');
4901 print "<div class=\"list_head\">\n";
4902 if ($#{$difftree} > 10) {
4903 print(($#{$difftree} + 1) . " files changed:\n");
4905 print "</div>\n";
4907 print "<table class=\"" .
4908 (@parents > 1 ? "combined " : "") .
4909 "diff_tree\">\n";
4911 # header only for combined diff in 'commitdiff' view
4912 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4913 if ($has_header) {
4914 # table header
4915 print "<thead><tr>\n" .
4916 "<th></th><th></th>\n"; # filename, patchN link
4917 for (my $i = 0; $i < @parents; $i++) {
4918 my $par = $parents[$i];
4919 print "<th>" .
4920 $cgi->a({-href => href(action=>"commitdiff",
4921 hash=>$hash, hash_parent=>$par),
4922 -title => 'commitdiff to parent number ' .
4923 ($i+1) . ': ' . substr($par,0,7)},
4924 $i+1) .
4925 "&nbsp;</th>\n";
4927 print "</tr></thead>\n<tbody>\n";
4930 my $alternate = 1;
4931 my $patchno = 0;
4932 foreach my $line (@{$difftree}) {
4933 my $diff = parsed_difftree_line($line);
4935 if ($alternate) {
4936 print "<tr class=\"dark\">\n";
4937 } else {
4938 print "<tr class=\"light\">\n";
4940 $alternate ^= 1;
4942 if (exists $diff->{'nparents'}) { # combined diff
4944 fill_from_file_info($diff, @parents)
4945 unless exists $diff->{'from_file'};
4947 if (!is_deleted($diff)) {
4948 # file exists in the result (child) commit
4949 print "<td>" .
4950 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4951 file_name=>$diff->{'to_file'},
4952 hash_base=>$hash),
4953 -class => "list"}, esc_path($diff->{'to_file'})) .
4954 "</td>\n";
4955 } else {
4956 print "<td>" .
4957 esc_path($diff->{'to_file'}) .
4958 "</td>\n";
4961 if ($action eq 'commitdiff') {
4962 # link to patch
4963 $patchno++;
4964 print "<td class=\"link\">" .
4965 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4966 "patch") .
4967 " | " .
4968 "</td>\n";
4971 my $has_history = 0;
4972 my $not_deleted = 0;
4973 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4974 my $hash_parent = $parents[$i];
4975 my $from_hash = $diff->{'from_id'}[$i];
4976 my $from_path = $diff->{'from_file'}[$i];
4977 my $status = $diff->{'status'}[$i];
4979 $has_history ||= ($status ne 'A');
4980 $not_deleted ||= ($status ne 'D');
4982 if ($status eq 'A') {
4983 print "<td class=\"link\" align=\"right\"> | </td>\n";
4984 } elsif ($status eq 'D') {
4985 print "<td class=\"link\">" .
4986 $cgi->a({-href => href(action=>"blob",
4987 hash_base=>$hash,
4988 hash=>$from_hash,
4989 file_name=>$from_path)},
4990 "blob" . ($i+1)) .
4991 " | </td>\n";
4992 } else {
4993 if ($diff->{'to_id'} eq $from_hash) {
4994 print "<td class=\"link nochange\">";
4995 } else {
4996 print "<td class=\"link\">";
4998 print $cgi->a({-href => href(action=>"blobdiff",
4999 hash=>$diff->{'to_id'},
5000 hash_parent=>$from_hash,
5001 hash_base=>$hash,
5002 hash_parent_base=>$hash_parent,
5003 file_name=>$diff->{'to_file'},
5004 file_parent=>$from_path)},
5005 "diff" . ($i+1)) .
5006 " | </td>\n";
5010 print "<td class=\"link\">";
5011 if ($not_deleted) {
5012 print $cgi->a({-href => href(action=>"blob",
5013 hash=>$diff->{'to_id'},
5014 file_name=>$diff->{'to_file'},
5015 hash_base=>$hash)},
5016 "blob");
5017 print " | " if ($has_history);
5019 if ($has_history) {
5020 print $cgi->a({-href => href(action=>"history",
5021 file_name=>$diff->{'to_file'},
5022 hash_base=>$hash)},
5023 "history");
5025 print "</td>\n";
5027 print "</tr>\n";
5028 next; # instead of 'else' clause, to avoid extra indent
5030 # else ordinary diff
5032 my ($to_mode_oct, $to_mode_str, $to_file_type);
5033 my ($from_mode_oct, $from_mode_str, $from_file_type);
5034 if ($diff->{'to_mode'} ne ('0' x 6)) {
5035 $to_mode_oct = oct $diff->{'to_mode'};
5036 if (S_ISREG($to_mode_oct)) { # only for regular file
5037 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
5039 $to_file_type = file_type($diff->{'to_mode'});
5041 if ($diff->{'from_mode'} ne ('0' x 6)) {
5042 $from_mode_oct = oct $diff->{'from_mode'};
5043 if (S_ISREG($from_mode_oct)) { # only for regular file
5044 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5046 $from_file_type = file_type($diff->{'from_mode'});
5049 if ($diff->{'status'} eq "A") { # created
5050 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5051 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5052 $mode_chng .= "]</span>";
5053 print "<td>";
5054 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5055 hash_base=>$hash, file_name=>$diff->{'file'}),
5056 -class => "list"}, esc_path($diff->{'file'}));
5057 print "</td>\n";
5058 print "<td>$mode_chng</td>\n";
5059 print "<td class=\"link\">";
5060 if ($action eq 'commitdiff') {
5061 # link to patch
5062 $patchno++;
5063 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5064 "patch") .
5065 " | ";
5067 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5068 hash_base=>$hash, file_name=>$diff->{'file'})},
5069 "blob");
5070 print "</td>\n";
5072 } elsif ($diff->{'status'} eq "D") { # deleted
5073 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5074 print "<td>";
5075 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5076 hash_base=>$parent, file_name=>$diff->{'file'}),
5077 -class => "list"}, esc_path($diff->{'file'}));
5078 print "</td>\n";
5079 print "<td>$mode_chng</td>\n";
5080 print "<td class=\"link\">";
5081 if ($action eq 'commitdiff') {
5082 # link to patch
5083 $patchno++;
5084 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5085 "patch") .
5086 " | ";
5088 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5089 hash_base=>$parent, file_name=>$diff->{'file'})},
5090 "blob") . " | ";
5091 if ($have_blame) {
5092 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5093 file_name=>$diff->{'file'})},
5094 "blame") . " | ";
5096 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5097 file_name=>$diff->{'file'})},
5098 "history");
5099 print "</td>\n";
5101 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5102 my $mode_chnge = "";
5103 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5104 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5105 if ($from_file_type ne $to_file_type) {
5106 $mode_chnge .= " from $from_file_type to $to_file_type";
5108 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5109 if ($from_mode_str && $to_mode_str) {
5110 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5111 } elsif ($to_mode_str) {
5112 $mode_chnge .= " mode: $to_mode_str";
5115 $mode_chnge .= "]</span>\n";
5117 print "<td>";
5118 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5119 hash_base=>$hash, file_name=>$diff->{'file'}),
5120 -class => "list"}, esc_path($diff->{'file'}));
5121 print "</td>\n";
5122 print "<td>$mode_chnge</td>\n";
5123 print "<td class=\"link\">";
5124 if ($action eq 'commitdiff') {
5125 # link to patch
5126 $patchno++;
5127 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5128 "patch") .
5129 " | ";
5130 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5131 # "commit" view and modified file (not onlu mode changed)
5132 print $cgi->a({-href => href(action=>"blobdiff",
5133 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5134 hash_base=>$hash, hash_parent_base=>$parent,
5135 file_name=>$diff->{'file'})},
5136 "diff") .
5137 " | ";
5139 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5140 hash_base=>$hash, file_name=>$diff->{'file'})},
5141 "blob") . " | ";
5142 if ($have_blame) {
5143 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5144 file_name=>$diff->{'file'})},
5145 "blame") . " | ";
5147 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5148 file_name=>$diff->{'file'})},
5149 "history");
5150 print "</td>\n";
5152 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5153 my %status_name = ('R' => 'moved', 'C' => 'copied');
5154 my $nstatus = $status_name{$diff->{'status'}};
5155 my $mode_chng = "";
5156 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5157 # mode also for directories, so we cannot use $to_mode_str
5158 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5160 print "<td>" .
5161 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5162 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5163 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5164 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5165 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5166 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5167 -class => "list"}, esc_path($diff->{'from_file'})) .
5168 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5169 "<td class=\"link\">";
5170 if ($action eq 'commitdiff') {
5171 # link to patch
5172 $patchno++;
5173 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5174 "patch") .
5175 " | ";
5176 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5177 # "commit" view and modified file (not only pure rename or copy)
5178 print $cgi->a({-href => href(action=>"blobdiff",
5179 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5180 hash_base=>$hash, hash_parent_base=>$parent,
5181 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5182 "diff") .
5183 " | ";
5185 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5186 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5187 "blob") . " | ";
5188 if ($have_blame) {
5189 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5190 file_name=>$diff->{'to_file'})},
5191 "blame") . " | ";
5193 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5194 file_name=>$diff->{'to_file'})},
5195 "history");
5196 print "</td>\n";
5198 } # we should not encounter Unmerged (U) or Unknown (X) status
5199 print "</tr>\n";
5201 print "</tbody>" if $has_header;
5202 print "</table>\n";
5205 # Print context lines and then rem/add lines in a side-by-side manner.
5206 sub print_sidebyside_diff_lines {
5207 my ($ctx, $rem, $add) = @_;
5209 # print context block before add/rem block
5210 if (@$ctx) {
5211 print join '',
5212 '<div class="chunk_block ctx">',
5213 '<div class="old">',
5214 @$ctx,
5215 '</div>',
5216 '<div class="new">',
5217 @$ctx,
5218 '</div>',
5219 '</div>';
5222 if (!@$add) {
5223 # pure removal
5224 print join '',
5225 '<div class="chunk_block rem">',
5226 '<div class="old">',
5227 @$rem,
5228 '</div>',
5229 '</div>';
5230 } elsif (!@$rem) {
5231 # pure addition
5232 print join '',
5233 '<div class="chunk_block add">',
5234 '<div class="new">',
5235 @$add,
5236 '</div>',
5237 '</div>';
5238 } else {
5239 print join '',
5240 '<div class="chunk_block chg">',
5241 '<div class="old">',
5242 @$rem,
5243 '</div>',
5244 '<div class="new">',
5245 @$add,
5246 '</div>',
5247 '</div>';
5251 # Print context lines and then rem/add lines in inline manner.
5252 sub print_inline_diff_lines {
5253 my ($ctx, $rem, $add) = @_;
5255 print @$ctx, @$rem, @$add;
5258 # Format removed and added line, mark changed part and HTML-format them.
5259 # Implementation is based on contrib/diff-highlight
5260 sub format_rem_add_lines_pair {
5261 my ($rem, $add, $num_parents) = @_;
5263 # We need to untabify lines before split()'ing them;
5264 # otherwise offsets would be invalid.
5265 chomp $rem;
5266 chomp $add;
5267 $rem = untabify($rem);
5268 $add = untabify($add);
5270 my @rem = split(//, $rem);
5271 my @add = split(//, $add);
5272 my ($esc_rem, $esc_add);
5273 # Ignore leading +/- characters for each parent.
5274 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5275 my ($prefix_has_nonspace, $suffix_has_nonspace);
5277 my $shorter = (@rem < @add) ? @rem : @add;
5278 while ($prefix_len < $shorter) {
5279 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5281 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5282 $prefix_len++;
5285 while ($prefix_len + $suffix_len < $shorter) {
5286 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5288 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5289 $suffix_len++;
5292 # Mark lines that are different from each other, but have some common
5293 # part that isn't whitespace. If lines are completely different, don't
5294 # mark them because that would make output unreadable, especially if
5295 # diff consists of multiple lines.
5296 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5297 $esc_rem = esc_html_hl_regions($rem, 'marked',
5298 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5299 $esc_add = esc_html_hl_regions($add, 'marked',
5300 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5301 } else {
5302 $esc_rem = esc_html($rem, -nbsp=>1);
5303 $esc_add = esc_html($add, -nbsp=>1);
5306 return format_diff_line(\$esc_rem, 'rem'),
5307 format_diff_line(\$esc_add, 'add');
5310 # HTML-format diff context, removed and added lines.
5311 sub format_ctx_rem_add_lines {
5312 my ($ctx, $rem, $add, $num_parents) = @_;
5313 my (@new_ctx, @new_rem, @new_add);
5314 my $can_highlight = 0;
5315 my $is_combined = ($num_parents > 1);
5317 # Highlight if every removed line has a corresponding added line.
5318 if (@$add > 0 && @$add == @$rem) {
5319 $can_highlight = 1;
5321 # Highlight lines in combined diff only if the chunk contains
5322 # diff between the same version, e.g.
5324 # - a
5325 # - b
5326 # + c
5327 # + d
5329 # Otherwise the highlightling would be confusing.
5330 if ($is_combined) {
5331 for (my $i = 0; $i < @$add; $i++) {
5332 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5333 my $prefix_add = substr($add->[$i], 0, $num_parents);
5335 $prefix_rem =~ s/-/+/g;
5337 if ($prefix_rem ne $prefix_add) {
5338 $can_highlight = 0;
5339 last;
5345 if ($can_highlight) {
5346 for (my $i = 0; $i < @$add; $i++) {
5347 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5348 $rem->[$i], $add->[$i], $num_parents);
5349 push @new_rem, $line_rem;
5350 push @new_add, $line_add;
5352 } else {
5353 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5354 @new_add = map { format_diff_line($_, 'add') } @$add;
5357 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5359 return (\@new_ctx, \@new_rem, \@new_add);
5362 # Print context lines and then rem/add lines.
5363 sub print_diff_lines {
5364 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5365 my $is_combined = $num_parents > 1;
5367 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5368 $num_parents);
5370 if ($diff_style eq 'sidebyside' && !$is_combined) {
5371 print_sidebyside_diff_lines($ctx, $rem, $add);
5372 } else {
5373 # default 'inline' style and unknown styles
5374 print_inline_diff_lines($ctx, $rem, $add);
5378 sub print_diff_chunk {
5379 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5380 my (@ctx, @rem, @add);
5382 # The class of the previous line.
5383 my $prev_class = '';
5385 return unless @chunk;
5387 # incomplete last line might be among removed or added lines,
5388 # or both, or among context lines: find which
5389 for (my $i = 1; $i < @chunk; $i++) {
5390 if ($chunk[$i][0] eq 'incomplete') {
5391 $chunk[$i][0] = $chunk[$i-1][0];
5395 # guardian
5396 push @chunk, ["", ""];
5398 foreach my $line_info (@chunk) {
5399 my ($class, $line) = @$line_info;
5401 # print chunk headers
5402 if ($class && $class eq 'chunk_header') {
5403 print format_diff_line($line, $class, $from, $to);
5404 next;
5407 ## print from accumulator when have some add/rem lines or end
5408 # of chunk (flush context lines), or when have add and rem
5409 # lines and new block is reached (otherwise add/rem lines could
5410 # be reordered)
5411 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5412 (@rem && @add && $class ne $prev_class)) {
5413 print_diff_lines(\@ctx, \@rem, \@add,
5414 $diff_style, $num_parents);
5415 @ctx = @rem = @add = ();
5418 ## adding lines to accumulator
5419 # guardian value
5420 last unless $line;
5421 # rem, add or change
5422 if ($class eq 'rem') {
5423 push @rem, $line;
5424 } elsif ($class eq 'add') {
5425 push @add, $line;
5427 # context line
5428 if ($class eq 'ctx') {
5429 push @ctx, $line;
5432 $prev_class = $class;
5436 sub git_patchset_body {
5437 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5438 my ($hash_parent) = $hash_parents[0];
5440 my $is_combined = (@hash_parents > 1);
5441 my $patch_idx = 0;
5442 my $patch_number = 0;
5443 my $patch_line;
5444 my $diffinfo;
5445 my $to_name;
5446 my (%from, %to);
5447 my @chunk; # for side-by-side diff
5449 print "<div class=\"patchset\">\n";
5451 # skip to first patch
5452 while ($patch_line = to_utf8(scalar <$fd>)) {
5453 chomp $patch_line;
5455 last if ($patch_line =~ m/^diff /);
5458 PATCH:
5459 while ($patch_line) {
5461 # parse "git diff" header line
5462 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5463 # $1 is from_name, which we do not use
5464 $to_name = unquote($2);
5465 $to_name =~ s!^b/!!;
5466 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5467 # $1 is 'cc' or 'combined', which we do not use
5468 $to_name = unquote($2);
5469 } else {
5470 $to_name = undef;
5473 # check if current patch belong to current raw line
5474 # and parse raw git-diff line if needed
5475 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5476 # this is continuation of a split patch
5477 print "<div class=\"patch cont\">\n";
5478 } else {
5479 # advance raw git-diff output if needed
5480 $patch_idx++ if defined $diffinfo;
5482 # read and prepare patch information
5483 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5485 # compact combined diff output can have some patches skipped
5486 # find which patch (using pathname of result) we are at now;
5487 if ($is_combined) {
5488 while ($to_name ne $diffinfo->{'to_file'}) {
5489 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5490 format_diff_cc_simplified($diffinfo, @hash_parents) .
5491 "</div>\n"; # class="patch"
5493 $patch_idx++;
5494 $patch_number++;
5496 last if $patch_idx > $#$difftree;
5497 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5501 # modifies %from, %to hashes
5502 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5504 # this is first patch for raw difftree line with $patch_idx index
5505 # we index @$difftree array from 0, but number patches from 1
5506 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5509 # git diff header
5510 #assert($patch_line =~ m/^diff /) if DEBUG;
5511 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5512 $patch_number++;
5513 # print "git diff" header
5514 print format_git_diff_header_line($patch_line, $diffinfo,
5515 \%from, \%to);
5517 # print extended diff header
5518 print "<div class=\"diff extended_header\">\n";
5519 EXTENDED_HEADER:
5520 while ($patch_line = to_utf8(scalar<$fd>)) {
5521 chomp $patch_line;
5523 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5525 print format_extended_diff_header_line($patch_line, $diffinfo,
5526 \%from, \%to);
5528 print "</div>\n"; # class="diff extended_header"
5530 # from-file/to-file diff header
5531 if (! $patch_line) {
5532 print "</div>\n"; # class="patch"
5533 last PATCH;
5535 next PATCH if ($patch_line =~ m/^diff /);
5536 #assert($patch_line =~ m/^---/) if DEBUG;
5538 my $last_patch_line = $patch_line;
5539 $patch_line = to_utf8(scalar <$fd>);
5540 chomp $patch_line;
5541 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5543 print format_diff_from_to_header($last_patch_line, $patch_line,
5544 $diffinfo, \%from, \%to,
5545 @hash_parents);
5547 # the patch itself
5548 LINE:
5549 while ($patch_line = to_utf8(scalar <$fd>)) {
5550 chomp $patch_line;
5552 next PATCH if ($patch_line =~ m/^diff /);
5554 my $class = diff_line_class($patch_line, \%from, \%to);
5556 if ($class eq 'chunk_header') {
5557 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5558 @chunk = ();
5561 push @chunk, [ $class, $patch_line ];
5564 } continue {
5565 if (@chunk) {
5566 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5567 @chunk = ();
5569 print "</div>\n"; # class="patch"
5572 # for compact combined (--cc) format, with chunk and patch simplification
5573 # the patchset might be empty, but there might be unprocessed raw lines
5574 for (++$patch_idx if $patch_number > 0;
5575 $patch_idx < @$difftree;
5576 ++$patch_idx) {
5577 # read and prepare patch information
5578 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5580 # generate anchor for "patch" links in difftree / whatchanged part
5581 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5582 format_diff_cc_simplified($diffinfo, @hash_parents) .
5583 "</div>\n"; # class="patch"
5585 $patch_number++;
5588 if ($patch_number == 0) {
5589 if (@hash_parents > 1) {
5590 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5591 } else {
5592 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5596 print "</div>\n"; # class="patchset"
5599 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5601 sub git_project_search_form {
5602 my ($searchtext, $search_use_regexp) = @_;
5604 my $limit = '';
5605 if ($project_filter) {
5606 $limit = " in '$project_filter/'";
5609 print "<div class=\"projsearch\">\n";
5610 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5611 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5612 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5613 if (defined $project_filter);
5614 print $cgi->textfield(-name => 's', -value => $searchtext,
5615 -title => "Search project by name and description$limit",
5616 -size => 60) . "\n" .
5617 "<span title=\"Extended regular expression\">" .
5618 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5619 -checked => $search_use_regexp) .
5620 "</span>\n" .
5621 $cgi->submit(-name => 'btnS', -value => 'Search') .
5622 $cgi->end_form() . "\n" .
5623 $cgi->a({-href => href(project => undef, searchtext => undef,
5624 project_filter => $project_filter)},
5625 esc_html("List all projects$limit")) . "<br />\n";
5626 print "</div>\n";
5629 # entry for given @keys needs filling if at least one of keys in list
5630 # is not present in %$project_info
5631 sub project_info_needs_filling {
5632 my ($project_info, @keys) = @_;
5634 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5635 foreach my $key (@keys) {
5636 if (!exists $project_info->{$key}) {
5637 return 1;
5640 return;
5643 # fills project list info (age, description, owner, category, forks, etc.)
5644 # for each project in the list, removing invalid projects from
5645 # returned list, or fill only specified info.
5647 # Invalid projects are removed from the returned list if and only if you
5648 # ask 'age' or 'age_string' to be filled, because they are the only fields
5649 # that run unconditionally git command that requires repository, and
5650 # therefore do always check if project repository is invalid.
5652 # USAGE:
5653 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5654 # ensures that 'descr_long' and 'ctags' fields are filled
5655 # * @project_list = fill_project_list_info(\@project_list)
5656 # ensures that all fields are filled (and invalid projects removed)
5658 # NOTE: modifies $projlist, but does not remove entries from it
5659 sub fill_project_list_info {
5660 my ($projlist, @wanted_keys) = @_;
5661 my @projects;
5662 my $filter_set = sub { return @_; };
5663 if (@wanted_keys) {
5664 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5665 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5668 my $show_ctags = gitweb_check_feature('ctags');
5669 PROJECT:
5670 foreach my $pr (@$projlist) {
5671 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5672 my (@activity) = git_get_last_activity($pr->{'path'});
5673 unless (@activity) {
5674 next PROJECT;
5676 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5678 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5679 my $descr = git_get_project_description($pr->{'path'}) || "";
5680 $descr = to_utf8($descr);
5681 $pr->{'descr_long'} = $descr;
5682 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5684 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5685 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5687 if ($show_ctags &&
5688 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5689 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5691 if ($projects_list_group_categories &&
5692 project_info_needs_filling($pr, $filter_set->('category'))) {
5693 my $cat = git_get_project_category($pr->{'path'}) ||
5694 $project_list_default_category;
5695 $pr->{'category'} = to_utf8($cat);
5698 push @projects, $pr;
5701 return @projects;
5704 sub sort_projects_list {
5705 my ($projlist, $order) = @_;
5707 sub order_str {
5708 my $key = shift;
5709 return sub { $a->{$key} cmp $b->{$key} };
5712 sub order_num_then_undef {
5713 my $key = shift;
5714 return sub {
5715 defined $a->{$key} ?
5716 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5717 (defined $b->{$key} ? 1 : 0)
5721 my %orderings = (
5722 project => order_str('path'),
5723 descr => order_str('descr_long'),
5724 owner => order_str('owner'),
5725 age => order_num_then_undef('age'),
5728 my $ordering = $orderings{$order};
5729 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5732 # returns a hash of categories, containing the list of project
5733 # belonging to each category
5734 sub build_projlist_by_category {
5735 my ($projlist, $from, $to) = @_;
5736 my %categories;
5738 $from = 0 unless defined $from;
5739 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5741 for (my $i = $from; $i <= $to; $i++) {
5742 my $pr = $projlist->[$i];
5743 push @{$categories{ $pr->{'category'} }}, $pr;
5746 return wantarray ? %categories : \%categories;
5749 # print 'sort by' <th> element, generating 'sort by $name' replay link
5750 # if that order is not selected
5751 sub print_sort_th {
5752 print format_sort_th(@_);
5755 sub format_sort_th {
5756 my ($name, $order, $header) = @_;
5757 my $sort_th = "";
5758 $header ||= ucfirst($name);
5760 if ($order eq $name) {
5761 $sort_th .= "<th>$header</th>\n";
5762 } else {
5763 $sort_th .= "<th>" .
5764 $cgi->a({-href => href(-replay=>1, order=>$name),
5765 -class => "header"}, $header) .
5766 "</th>\n";
5769 return $sort_th;
5772 sub git_project_list_rows {
5773 my ($projlist, $from, $to, $check_forks) = @_;
5775 $from = 0 unless defined $from;
5776 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5778 my $alternate = 1;
5779 for (my $i = $from; $i <= $to; $i++) {
5780 my $pr = $projlist->[$i];
5782 if ($alternate) {
5783 print "<tr class=\"dark\">\n";
5784 } else {
5785 print "<tr class=\"light\">\n";
5787 $alternate ^= 1;
5789 if ($check_forks) {
5790 print "<td>";
5791 if ($pr->{'forks'}) {
5792 my $nforks = scalar @{$pr->{'forks'}};
5793 if ($nforks > 0) {
5794 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5795 -title => "$nforks forks"}, "+");
5796 } else {
5797 print $cgi->span({-title => "$nforks forks"}, "+");
5800 print "</td>\n";
5802 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5803 -class => "list"},
5804 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5805 "</td>\n" .
5806 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5807 -class => "list",
5808 -title => $pr->{'descr_long'}},
5809 $search_regexp
5810 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5811 $pr->{'descr'}, $search_regexp)
5812 : esc_html($pr->{'descr'})) .
5813 "</td>\n";
5814 unless ($omit_owner) {
5815 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5817 unless ($omit_age_column) {
5818 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5819 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5821 print"<td class=\"link\">" .
5822 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5823 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5824 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5825 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5826 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5827 "</td>\n" .
5828 "</tr>\n";
5832 sub git_project_list_body {
5833 # actually uses global variable $project
5834 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5835 my @projects = @$projlist;
5837 my $check_forks = gitweb_check_feature('forks');
5838 my $show_ctags = gitweb_check_feature('ctags');
5839 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5840 $check_forks = undef
5841 if ($tagfilter || $search_regexp);
5843 # filtering out forks before filling info allows to do less work
5844 @projects = filter_forks_from_projects_list(\@projects)
5845 if ($check_forks);
5846 # search_projects_list pre-fills required info
5847 @projects = search_projects_list(\@projects,
5848 'search_regexp' => $search_regexp,
5849 'tagfilter' => $tagfilter)
5850 if ($tagfilter || $search_regexp);
5851 # fill the rest
5852 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5853 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5854 push @all_fields, 'owner' unless($omit_owner);
5855 @projects = fill_project_list_info(\@projects, @all_fields);
5857 $order ||= $default_projects_order;
5858 $from = 0 unless defined $from;
5859 $to = $#projects if (!defined $to || $#projects < $to);
5861 # short circuit
5862 if ($from > $to) {
5863 print "<center>\n".
5864 "<b>No such projects found</b><br />\n".
5865 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5866 "</center>\n<br />\n";
5867 return;
5870 @projects = sort_projects_list(\@projects, $order);
5872 if ($show_ctags) {
5873 my $ctags = git_gather_all_ctags(\@projects);
5874 my $cloud = git_populate_project_tagcloud($ctags);
5875 print git_show_project_tagcloud($cloud, 64);
5878 print "<table class=\"project_list\">\n";
5879 unless ($no_header) {
5880 print "<tr>\n";
5881 if ($check_forks) {
5882 print "<th></th>\n";
5884 print_sort_th('project', $order, 'Project');
5885 print_sort_th('descr', $order, 'Description');
5886 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5887 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5888 print "<th></th>\n" . # for links
5889 "</tr>\n";
5892 if ($projects_list_group_categories) {
5893 # only display categories with projects in the $from-$to window
5894 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5895 my %categories = build_projlist_by_category(\@projects, $from, $to);
5896 foreach my $cat (sort keys %categories) {
5897 unless ($cat eq "") {
5898 print "<tr>\n";
5899 if ($check_forks) {
5900 print "<td></td>\n";
5902 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5903 print "</tr>\n";
5906 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5908 } else {
5909 git_project_list_rows(\@projects, $from, $to, $check_forks);
5912 if (defined $extra) {
5913 print "<tr>\n";
5914 if ($check_forks) {
5915 print "<td></td>\n";
5917 print "<td colspan=\"5\">$extra</td>\n" .
5918 "</tr>\n";
5920 print "</table>\n";
5923 sub git_log_body {
5924 # uses global variable $project
5925 my ($commitlist, $from, $to, $refs, $extra) = @_;
5927 $from = 0 unless defined $from;
5928 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5930 for (my $i = 0; $i <= $to; $i++) {
5931 my %co = %{$commitlist->[$i]};
5932 next if !%co;
5933 my $commit = $co{'id'};
5934 my $ref = format_ref_marker($refs, $commit);
5935 git_print_header_div('commit',
5936 "<span class=\"age\">$co{'age_string'}</span>" .
5937 esc_html($co{'title'}) . $ref,
5938 $commit);
5939 print "<div class=\"title_text\">\n" .
5940 "<div class=\"log_link\">\n" .
5941 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5942 " | " .
5943 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5944 " | " .
5945 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5946 "<br/>\n" .
5947 "</div>\n";
5948 git_print_authorship(\%co, -tag => 'span');
5949 print "<br/>\n</div>\n";
5951 print "<div class=\"log_body\">\n";
5952 git_print_log($co{'comment'}, -final_empty_line=> 1);
5953 print "</div>\n";
5955 if ($extra) {
5956 print "<div class=\"page_nav\">\n";
5957 print "$extra\n";
5958 print "</div>\n";
5962 sub git_shortlog_body {
5963 # uses global variable $project
5964 my ($commitlist, $from, $to, $refs, $extra) = @_;
5966 $from = 0 unless defined $from;
5967 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5969 print "<table class=\"shortlog\">\n";
5970 my $alternate = 1;
5971 for (my $i = $from; $i <= $to; $i++) {
5972 my %co = %{$commitlist->[$i]};
5973 my $commit = $co{'id'};
5974 my $ref = format_ref_marker($refs, $commit);
5975 if ($alternate) {
5976 print "<tr class=\"dark\">\n";
5977 } else {
5978 print "<tr class=\"light\">\n";
5980 $alternate ^= 1;
5981 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5982 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5983 format_author_html('td', \%co, 10) . "<td>";
5984 print format_subject_html($co{'title'}, $co{'title_short'},
5985 href(action=>"commit", hash=>$commit), $ref);
5986 print "</td>\n" .
5987 "<td class=\"link\">" .
5988 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5989 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5990 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5991 my $snapshot_links = format_snapshot_links($commit);
5992 if (defined $snapshot_links) {
5993 print " | " . $snapshot_links;
5995 print "</td>\n" .
5996 "</tr>\n";
5998 if (defined $extra) {
5999 print "<tr>\n" .
6000 "<td colspan=\"4\">$extra</td>\n" .
6001 "</tr>\n";
6003 print "</table>\n";
6006 sub git_history_body {
6007 # Warning: assumes constant type (blob or tree) during history
6008 my ($commitlist, $from, $to, $refs, $extra,
6009 $file_name, $file_hash, $ftype) = @_;
6011 $from = 0 unless defined $from;
6012 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
6014 print "<table class=\"history\">\n";
6015 my $alternate = 1;
6016 for (my $i = $from; $i <= $to; $i++) {
6017 my %co = %{$commitlist->[$i]};
6018 if (!%co) {
6019 next;
6021 my $commit = $co{'id'};
6023 my $ref = format_ref_marker($refs, $commit);
6025 if ($alternate) {
6026 print "<tr class=\"dark\">\n";
6027 } else {
6028 print "<tr class=\"light\">\n";
6030 $alternate ^= 1;
6031 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6032 # shortlog: format_author_html('td', \%co, 10)
6033 format_author_html('td', \%co, 15, 3) . "<td>";
6034 # originally git_history used chop_str($co{'title'}, 50)
6035 print format_subject_html($co{'title'}, $co{'title_short'},
6036 href(action=>"commit", hash=>$commit), $ref);
6037 print "</td>\n" .
6038 "<td class=\"link\">" .
6039 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
6040 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
6042 if ($ftype eq 'blob') {
6043 my $blob_current = $file_hash;
6044 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6045 if (defined $blob_current && defined $blob_parent &&
6046 $blob_current ne $blob_parent) {
6047 print " | " .
6048 $cgi->a({-href => href(action=>"blobdiff",
6049 hash=>$blob_current, hash_parent=>$blob_parent,
6050 hash_base=>$hash_base, hash_parent_base=>$commit,
6051 file_name=>$file_name)},
6052 "diff to current");
6055 print "</td>\n" .
6056 "</tr>\n";
6058 if (defined $extra) {
6059 print "<tr>\n" .
6060 "<td colspan=\"4\">$extra</td>\n" .
6061 "</tr>\n";
6063 print "</table>\n";
6066 sub git_tags_body {
6067 # uses global variable $project
6068 my ($taglist, $from, $to, $extra) = @_;
6069 $from = 0 unless defined $from;
6070 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6072 print "<table class=\"tags\">\n";
6073 my $alternate = 1;
6074 for (my $i = $from; $i <= $to; $i++) {
6075 my $entry = $taglist->[$i];
6076 my %tag = %$entry;
6077 my $comment = $tag{'subject'};
6078 my $comment_short;
6079 if (defined $comment) {
6080 $comment_short = chop_str($comment, 30, 5);
6082 if ($alternate) {
6083 print "<tr class=\"dark\">\n";
6084 } else {
6085 print "<tr class=\"light\">\n";
6087 $alternate ^= 1;
6088 if (defined $tag{'age'}) {
6089 print "<td><i>$tag{'age'}</i></td>\n";
6090 } else {
6091 print "<td></td>\n";
6093 print "<td>" .
6094 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6095 -class => "list name"}, esc_html($tag{'name'})) .
6096 "</td>\n" .
6097 "<td>";
6098 if (defined $comment) {
6099 print format_subject_html($comment, $comment_short,
6100 href(action=>"tag", hash=>$tag{'id'}));
6102 print "</td>\n" .
6103 "<td class=\"selflink\">";
6104 if ($tag{'type'} eq "tag") {
6105 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6106 } else {
6107 print "&nbsp;";
6109 print "</td>\n" .
6110 "<td class=\"link\">" . " | " .
6111 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6112 if ($tag{'reftype'} eq "commit") {
6113 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6114 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6115 } elsif ($tag{'reftype'} eq "blob") {
6116 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6118 print "</td>\n" .
6119 "</tr>";
6121 if (defined $extra) {
6122 print "<tr>\n" .
6123 "<td colspan=\"5\">$extra</td>\n" .
6124 "</tr>\n";
6126 print "</table>\n";
6129 sub git_heads_body {
6130 # uses global variable $project
6131 my ($headlist, $head_at, $from, $to, $extra) = @_;
6132 $from = 0 unless defined $from;
6133 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6135 print "<table class=\"heads\">\n";
6136 my $alternate = 1;
6137 for (my $i = $from; $i <= $to; $i++) {
6138 my $entry = $headlist->[$i];
6139 my %ref = %$entry;
6140 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6141 if ($alternate) {
6142 print "<tr class=\"dark\">\n";
6143 } else {
6144 print "<tr class=\"light\">\n";
6146 $alternate ^= 1;
6147 print "<td><i>$ref{'age'}</i></td>\n" .
6148 ($curr ? "<td class=\"current_head\">" : "<td>") .
6149 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6150 -class => "list name"},esc_html($ref{'name'})) .
6151 "</td>\n" .
6152 "<td class=\"link\">" .
6153 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6154 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6155 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6156 "</td>\n" .
6157 "</tr>";
6159 if (defined $extra) {
6160 print "<tr>\n" .
6161 "<td colspan=\"3\">$extra</td>\n" .
6162 "</tr>\n";
6164 print "</table>\n";
6167 # Display a single remote block
6168 sub git_remote_block {
6169 my ($remote, $rdata, $limit, $head) = @_;
6171 my $heads = $rdata->{'heads'};
6172 my $fetch = $rdata->{'fetch'};
6173 my $push = $rdata->{'push'};
6175 my $urls_table = "<table class=\"projects_list\">\n" ;
6177 if (defined $fetch) {
6178 if ($fetch eq $push) {
6179 $urls_table .= format_repo_url("URL", $fetch);
6180 } else {
6181 $urls_table .= format_repo_url("Fetch URL", $fetch);
6182 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6184 } elsif (defined $push) {
6185 $urls_table .= format_repo_url("Push URL", $push);
6186 } else {
6187 $urls_table .= format_repo_url("", "No remote URL");
6190 $urls_table .= "</table>\n";
6192 my $dots;
6193 if (defined $limit && $limit < @$heads) {
6194 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6197 print $urls_table;
6198 git_heads_body($heads, $head, 0, $limit, $dots);
6201 # Display a list of remote names with the respective fetch and push URLs
6202 sub git_remotes_list {
6203 my ($remotedata, $limit) = @_;
6204 print "<table class=\"heads\">\n";
6205 my $alternate = 1;
6206 my @remotes = sort keys %$remotedata;
6208 my $limited = $limit && $limit < @remotes;
6210 $#remotes = $limit - 1 if $limited;
6212 while (my $remote = shift @remotes) {
6213 my $rdata = $remotedata->{$remote};
6214 my $fetch = $rdata->{'fetch'};
6215 my $push = $rdata->{'push'};
6216 if ($alternate) {
6217 print "<tr class=\"dark\">\n";
6218 } else {
6219 print "<tr class=\"light\">\n";
6221 $alternate ^= 1;
6222 print "<td>" .
6223 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6224 -class=> "list name"},esc_html($remote)) .
6225 "</td>";
6226 print "<td class=\"link\">" .
6227 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6228 " | " .
6229 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6230 "</td>";
6232 print "</tr>\n";
6235 if ($limited) {
6236 print "<tr>\n" .
6237 "<td colspan=\"3\">" .
6238 $cgi->a({-href => href(action=>"remotes")}, "...") .
6239 "</td>\n" . "</tr>\n";
6242 print "</table>";
6245 # Display remote heads grouped by remote, unless there are too many
6246 # remotes, in which case we only display the remote names
6247 sub git_remotes_body {
6248 my ($remotedata, $limit, $head) = @_;
6249 if ($limit and $limit < keys %$remotedata) {
6250 git_remotes_list($remotedata, $limit);
6251 } else {
6252 fill_remote_heads($remotedata);
6253 while (my ($remote, $rdata) = each %$remotedata) {
6254 git_print_section({-class=>"remote", -id=>$remote},
6255 ["remotes", $remote, $remote], sub {
6256 git_remote_block($remote, $rdata, $limit, $head);
6262 sub git_search_message {
6263 my %co = @_;
6265 my $greptype;
6266 if ($searchtype eq 'commit') {
6267 $greptype = "--grep=";
6268 } elsif ($searchtype eq 'author') {
6269 $greptype = "--author=";
6270 } elsif ($searchtype eq 'committer') {
6271 $greptype = "--committer=";
6273 $greptype .= $searchtext;
6274 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6275 $greptype, '--regexp-ignore-case',
6276 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6278 my $paging_nav = '';
6279 if ($page > 0) {
6280 $paging_nav .=
6281 $cgi->a({-href => href(-replay=>1, page=>undef)},
6282 "first") .
6283 " &sdot; " .
6284 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6285 -accesskey => "p", -title => "Alt-p"}, "prev");
6286 } else {
6287 $paging_nav .= "first &sdot; prev";
6289 my $next_link = '';
6290 if ($#commitlist >= 100) {
6291 $next_link =
6292 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6293 -accesskey => "n", -title => "Alt-n"}, "next");
6294 $paging_nav .= " &sdot; $next_link";
6295 } else {
6296 $paging_nav .= " &sdot; next";
6299 git_header_html();
6301 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6302 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6303 if ($page == 0 && !@commitlist) {
6304 print "<p>No match.</p>\n";
6305 } else {
6306 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6309 git_footer_html();
6312 sub git_search_changes {
6313 my %co = @_;
6315 local $/ = "\n";
6316 defined(my $fd = git_cmd_pipe '--no-pager', 'log', @diff_opts,
6317 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6318 ($search_use_regexp ? '--pickaxe-regex' : ()))
6319 or die_error(500, "Open git-log failed");
6321 git_header_html();
6323 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6324 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6326 print "<table class=\"pickaxe search\">\n";
6327 my $alternate = 1;
6328 undef %co;
6329 my @files;
6330 while (my $line = to_utf8(scalar <$fd>)) {
6331 chomp $line;
6332 next unless $line;
6334 my %set = parse_difftree_raw_line($line);
6335 if (defined $set{'commit'}) {
6336 # finish previous commit
6337 if (%co) {
6338 print "</td>\n" .
6339 "<td class=\"link\">" .
6340 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6341 "commit") .
6342 " | " .
6343 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6344 hash_base=>$co{'id'})},
6345 "tree") .
6346 "</td>\n" .
6347 "</tr>\n";
6350 if ($alternate) {
6351 print "<tr class=\"dark\">\n";
6352 } else {
6353 print "<tr class=\"light\">\n";
6355 $alternate ^= 1;
6356 %co = parse_commit($set{'commit'});
6357 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6358 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6359 "<td><i>$author</i></td>\n" .
6360 "<td>" .
6361 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6362 -class => "list subject"},
6363 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6364 } elsif (defined $set{'to_id'}) {
6365 next if ($set{'to_id'} =~ m/^0{40}$/);
6367 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6368 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6369 -class => "list"},
6370 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6371 "<br/>\n";
6374 close $fd;
6376 # finish last commit (warning: repetition!)
6377 if (%co) {
6378 print "</td>\n" .
6379 "<td class=\"link\">" .
6380 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6381 "commit") .
6382 " | " .
6383 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6384 hash_base=>$co{'id'})},
6385 "tree") .
6386 "</td>\n" .
6387 "</tr>\n";
6390 print "</table>\n";
6392 git_footer_html();
6395 sub git_search_files {
6396 my %co = @_;
6398 local $/ = "\n";
6399 defined(my $fd = git_cmd_pipe 'grep', '-n', '-z',
6400 $search_use_regexp ? ('-E', '-i') : '-F',
6401 $searchtext, $co{'tree'})
6402 or die_error(500, "Open git-grep failed");
6404 git_header_html();
6406 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6407 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6409 print "<table class=\"grep_search\">\n";
6410 my $alternate = 1;
6411 my $matches = 0;
6412 my $lastfile = '';
6413 my $file_href;
6414 while (my $line = to_utf8(scalar <$fd>)) {
6415 chomp $line;
6416 my ($file, $lno, $ltext, $binary);
6417 last if ($matches++ > 1000);
6418 if ($line =~ /^Binary file (.+) matches$/) {
6419 $file = $1;
6420 $binary = 1;
6421 } else {
6422 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6423 $file =~ s/^$co{'tree'}://;
6425 if ($file ne $lastfile) {
6426 $lastfile and print "</td></tr>\n";
6427 if ($alternate++) {
6428 print "<tr class=\"dark\">\n";
6429 } else {
6430 print "<tr class=\"light\">\n";
6432 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6433 file_name=>$file);
6434 print "<td class=\"list\">".
6435 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6436 print "</td><td>\n";
6437 $lastfile = $file;
6439 if ($binary) {
6440 print "<div class=\"binary\">Binary file</div>\n";
6441 } else {
6442 $ltext = untabify($ltext);
6443 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6444 $ltext = esc_html($1, -nbsp=>1);
6445 $ltext .= '<span class="match">';
6446 $ltext .= esc_html($2, -nbsp=>1);
6447 $ltext .= '</span>';
6448 $ltext .= esc_html($3, -nbsp=>1);
6449 } else {
6450 $ltext = esc_html($ltext, -nbsp=>1);
6452 print "<div class=\"pre\">" .
6453 $cgi->a({-href => $file_href.'#l'.$lno,
6454 -class => "linenr"}, sprintf('%4i', $lno)) .
6455 ' ' . $ltext . "</div>\n";
6458 if ($lastfile) {
6459 print "</td></tr>\n";
6460 if ($matches > 1000) {
6461 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6463 } else {
6464 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6466 close $fd;
6468 print "</table>\n";
6470 git_footer_html();
6473 sub git_search_grep_body {
6474 my ($commitlist, $from, $to, $extra) = @_;
6475 $from = 0 unless defined $from;
6476 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6478 print "<table class=\"commit_search\">\n";
6479 my $alternate = 1;
6480 for (my $i = $from; $i <= $to; $i++) {
6481 my %co = %{$commitlist->[$i]};
6482 if (!%co) {
6483 next;
6485 my $commit = $co{'id'};
6486 if ($alternate) {
6487 print "<tr class=\"dark\">\n";
6488 } else {
6489 print "<tr class=\"light\">\n";
6491 $alternate ^= 1;
6492 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6493 format_author_html('td', \%co, 15, 5) .
6494 "<td>" .
6495 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6496 -class => "list subject"},
6497 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6498 my $comment = $co{'comment'};
6499 foreach my $line (@$comment) {
6500 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6501 my ($lead, $match, $trail) = ($1, $2, $3);
6502 $match = chop_str($match, 70, 5, 'center');
6503 my $contextlen = int((80 - length($match))/2);
6504 $contextlen = 30 if ($contextlen > 30);
6505 $lead = chop_str($lead, $contextlen, 10, 'left');
6506 $trail = chop_str($trail, $contextlen, 10, 'right');
6508 $lead = esc_html($lead);
6509 $match = esc_html($match);
6510 $trail = esc_html($trail);
6512 print "$lead<span class=\"match\">$match</span>$trail<br />";
6515 print "</td>\n" .
6516 "<td class=\"link\">" .
6517 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6518 " | " .
6519 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6520 " | " .
6521 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6522 print "</td>\n" .
6523 "</tr>\n";
6525 if (defined $extra) {
6526 print "<tr>\n" .
6527 "<td colspan=\"3\">$extra</td>\n" .
6528 "</tr>\n";
6530 print "</table>\n";
6533 ## ======================================================================
6534 ## ======================================================================
6535 ## actions
6537 sub git_project_list {
6538 my $order = $input_params{'order'};
6539 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6540 die_error(400, "Unknown order parameter");
6543 my @list = git_get_projects_list($project_filter, $strict_export);
6544 if (!@list) {
6545 die_error(404, "No projects found");
6548 git_header_html();
6549 if (defined $home_text && -f $home_text) {
6550 print "<div class=\"index_include\">\n";
6551 insert_file($home_text);
6552 print "</div>\n";
6555 git_project_search_form($searchtext, $search_use_regexp);
6556 git_project_list_body(\@list, $order);
6557 git_footer_html();
6560 sub git_forks {
6561 my $order = $input_params{'order'};
6562 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6563 die_error(400, "Unknown order parameter");
6566 my $filter = $project;
6567 $filter =~ s/\.git$//;
6568 my @list = git_get_projects_list($filter);
6569 if (!@list) {
6570 die_error(404, "No forks found");
6573 git_header_html();
6574 git_print_page_nav('','');
6575 git_print_header_div('summary', "$project forks");
6576 git_project_list_body(\@list, $order);
6577 git_footer_html();
6580 sub git_project_index {
6581 my @projects = git_get_projects_list($project_filter, $strict_export);
6582 if (!@projects) {
6583 die_error(404, "No projects found");
6586 print $cgi->header(
6587 -type => 'text/plain',
6588 -charset => 'utf-8',
6589 -content_disposition => 'inline; filename="index.aux"');
6591 foreach my $pr (@projects) {
6592 if (!exists $pr->{'owner'}) {
6593 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6596 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6597 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6598 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6599 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6600 $path =~ s/ /\+/g;
6601 $owner =~ s/ /\+/g;
6603 print "$path $owner\n";
6607 sub git_summary {
6608 my $descr = git_get_project_description($project) || "none";
6609 my %co = parse_commit("HEAD");
6610 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6611 my $head = $co{'id'};
6612 my $remote_heads = gitweb_check_feature('remote_heads');
6614 my $owner = git_get_project_owner($project);
6616 my $refs = git_get_references();
6617 # These get_*_list functions return one more to allow us to see if
6618 # there are more ...
6619 my @taglist = git_get_tags_list(16);
6620 my @headlist = git_get_heads_list(16);
6621 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6622 my @forklist;
6623 my $check_forks = gitweb_check_feature('forks');
6625 if ($check_forks) {
6626 # find forks of a project
6627 my $filter = $project;
6628 $filter =~ s/\.git$//;
6629 @forklist = git_get_projects_list($filter);
6630 # filter out forks of forks
6631 @forklist = filter_forks_from_projects_list(\@forklist)
6632 if (@forklist);
6635 git_header_html();
6636 git_print_page_nav('summary','', $head);
6638 print "<div class=\"title\">&nbsp;</div>\n";
6639 print "<table class=\"projects_list\">\n" .
6640 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6641 if ($owner and not $omit_owner) {
6642 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6644 if (defined $cd{'rfc2822'}) {
6645 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6646 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6649 # use per project git URL list in $projectroot/$project/cloneurl
6650 # or make project git URL from git base URL and project name
6651 my $url_tag = "URL";
6652 my @url_list = git_get_project_url_list($project);
6653 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6654 foreach my $git_url (@url_list) {
6655 next unless $git_url;
6656 print format_repo_url($url_tag, $git_url);
6657 $url_tag = "";
6660 # Tag cloud
6661 my $show_ctags = gitweb_check_feature('ctags');
6662 if ($show_ctags) {
6663 my $ctags = git_get_project_ctags($project);
6664 if (%$ctags) {
6665 # without ability to add tags, don't show if there are none
6666 my $cloud = git_populate_project_tagcloud($ctags);
6667 print "<tr id=\"metadata_ctags\">" .
6668 "<td>content tags</td>" .
6669 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6670 "</tr>\n";
6674 print "</table>\n";
6676 # If XSS prevention is on, we don't include README.html.
6677 # TODO: Allow a readme in some safe format.
6678 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6679 print "<div class=\"title\">readme</div>\n" .
6680 "<div class=\"readme\">\n";
6681 insert_file("$projectroot/$project/README.html");
6682 print "\n</div>\n"; # class="readme"
6685 # we need to request one more than 16 (0..15) to check if
6686 # those 16 are all
6687 my @commitlist = $head ? parse_commits($head, 17) : ();
6688 if (@commitlist) {
6689 git_print_header_div('shortlog');
6690 git_shortlog_body(\@commitlist, 0, 15, $refs,
6691 $#commitlist <= 15 ? undef :
6692 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6695 if (@taglist) {
6696 git_print_header_div('tags');
6697 git_tags_body(\@taglist, 0, 15,
6698 $#taglist <= 15 ? undef :
6699 $cgi->a({-href => href(action=>"tags")}, "..."));
6702 if (@headlist) {
6703 git_print_header_div('heads');
6704 git_heads_body(\@headlist, $head, 0, 15,
6705 $#headlist <= 15 ? undef :
6706 $cgi->a({-href => href(action=>"heads")}, "..."));
6709 if (%remotedata) {
6710 git_print_header_div('remotes');
6711 git_remotes_body(\%remotedata, 15, $head);
6714 if (@forklist) {
6715 git_print_header_div('forks');
6716 git_project_list_body(\@forklist, 'age', 0, 15,
6717 $#forklist <= 15 ? undef :
6718 $cgi->a({-href => href(action=>"forks")}, "..."),
6719 'no_header');
6722 git_footer_html();
6725 sub git_tag {
6726 my %tag = parse_tag($hash);
6728 if (! %tag) {
6729 die_error(404, "Unknown tag object");
6732 my $head = git_get_head_hash($project);
6733 git_header_html();
6734 git_print_page_nav('','', $head,undef,$head);
6735 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6736 print "<div class=\"title_text\">\n" .
6737 "<table class=\"object_header\">\n" .
6738 "<tr>\n" .
6739 "<td>object</td>\n" .
6740 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6741 $tag{'object'}) . "</td>\n" .
6742 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6743 $tag{'type'}) . "</td>\n" .
6744 "</tr>\n";
6745 if (defined($tag{'author'})) {
6746 git_print_authorship_rows(\%tag, 'author');
6748 print "</table>\n\n" .
6749 "</div>\n";
6750 print "<div class=\"page_body\">";
6751 my $comment = $tag{'comment'};
6752 foreach my $line (@$comment) {
6753 chomp $line;
6754 print esc_html($line, -nbsp=>1) . "<br/>\n";
6756 print "</div>\n";
6757 git_footer_html();
6760 sub git_blame_common {
6761 my $format = shift || 'porcelain';
6762 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6763 $format = 'incremental';
6764 $action = 'blame_incremental'; # for page title etc
6767 # permissions
6768 gitweb_check_feature('blame')
6769 or die_error(403, "Blame view not allowed");
6771 # error checking
6772 die_error(400, "No file name given") unless $file_name;
6773 $hash_base ||= git_get_head_hash($project);
6774 die_error(404, "Couldn't find base commit") unless $hash_base;
6775 my %co = parse_commit($hash_base)
6776 or die_error(404, "Commit not found");
6777 my $ftype = "blob";
6778 if (!defined $hash) {
6779 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6780 or die_error(404, "Error looking up file");
6781 } else {
6782 $ftype = git_get_type($hash);
6783 if ($ftype !~ "blob") {
6784 die_error(400, "Object is not a blob");
6788 my $fd;
6789 if ($format eq 'incremental') {
6790 # get file contents (as base)
6791 defined($fd = git_cmd_pipe 'cat-file', 'blob', $hash)
6792 or die_error(500, "Open git-cat-file failed");
6793 } elsif ($format eq 'data') {
6794 # run git-blame --incremental
6795 defined($fd = git_cmd_pipe "blame", "--incremental",
6796 $hash_base, "--", $file_name)
6797 or die_error(500, "Open git-blame --incremental failed");
6798 } else {
6799 # run git-blame --porcelain
6800 defined($fd = git_cmd_pipe "blame", '-p',
6801 $hash_base, '--', $file_name)
6802 or die_error(500, "Open git-blame --porcelain failed");
6805 # incremental blame data returns early
6806 if ($format eq 'data') {
6807 print $cgi->header(
6808 -type=>"text/plain", -charset => "utf-8",
6809 -status=> "200 OK");
6810 local $| = 1; # output autoflush
6811 while (my $line = <$fd>) {
6812 print to_utf8($line);
6814 close $fd
6815 or print "ERROR $!\n";
6817 print 'END';
6818 if (defined $t0 && gitweb_check_feature('timed')) {
6819 print ' '.
6820 tv_interval($t0, [ gettimeofday() ]).
6821 ' '.$number_of_git_cmds;
6823 print "\n";
6825 return;
6828 # page header
6829 git_header_html();
6830 my $formats_nav =
6831 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6832 "blob") .
6833 " | ";
6834 if ($format eq 'incremental') {
6835 $formats_nav .=
6836 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6837 "blame") . " (non-incremental)";
6838 } else {
6839 $formats_nav .=
6840 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6841 "blame") . " (incremental)";
6843 $formats_nav .=
6844 " | " .
6845 $cgi->a({-href => href(action=>"history", -replay=>1)},
6846 "history") .
6847 " | " .
6848 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6849 "HEAD");
6850 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6851 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6852 git_print_page_path($file_name, $ftype, $hash_base);
6854 # page body
6855 if ($format eq 'incremental') {
6856 print "<noscript>\n<div class=\"error\"><center><b>\n".
6857 "This page requires JavaScript to run.\n Use ".
6858 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6859 'this page').
6860 " instead.\n".
6861 "</b></center></div>\n</noscript>\n";
6863 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6866 print qq!<div class="page_body">\n!;
6867 print qq!<div id="progress_info">... / ...</div>\n!
6868 if ($format eq 'incremental');
6869 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6870 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6871 qq!<thead>\n!.
6872 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6873 qq!</thead>\n!.
6874 qq!<tbody>\n!;
6876 my @rev_color = qw(light dark);
6877 my $num_colors = scalar(@rev_color);
6878 my $current_color = 0;
6880 if ($format eq 'incremental') {
6881 my $color_class = $rev_color[$current_color];
6883 #contents of a file
6884 my $linenr = 0;
6885 LINE:
6886 while (my $line = to_utf8(scalar <$fd>)) {
6887 chomp $line;
6888 $linenr++;
6890 print qq!<tr id="l$linenr" class="$color_class">!.
6891 qq!<td class="sha1"><a href=""> </a></td>!.
6892 qq!<td class="linenr">!.
6893 qq!<a class="linenr" href="">$linenr</a></td>!;
6894 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6895 print qq!</tr>\n!;
6898 } else { # porcelain, i.e. ordinary blame
6899 my %metainfo = (); # saves information about commits
6901 # blame data
6902 LINE:
6903 while (my $line = to_utf8(scalar <$fd>)) {
6904 chomp $line;
6905 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6906 # no <lines in group> for subsequent lines in group of lines
6907 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6908 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6909 if (!exists $metainfo{$full_rev}) {
6910 $metainfo{$full_rev} = { 'nprevious' => 0 };
6912 my $meta = $metainfo{$full_rev};
6913 my $data;
6914 while ($data = to_utf8(scalar <$fd>)) {
6915 chomp $data;
6916 last if ($data =~ s/^\t//); # contents of line
6917 if ($data =~ /^(\S+)(?: (.*))?$/) {
6918 $meta->{$1} = $2 unless exists $meta->{$1};
6920 if ($data =~ /^previous /) {
6921 $meta->{'nprevious'}++;
6924 my $short_rev = substr($full_rev, 0, 8);
6925 my $author = $meta->{'author'};
6926 my %date =
6927 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6928 my $date = $date{'iso-tz'};
6929 if ($group_size) {
6930 $current_color = ($current_color + 1) % $num_colors;
6932 my $tr_class = $rev_color[$current_color];
6933 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6934 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6935 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6936 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6937 if ($group_size) {
6938 print "<td class=\"sha1\"";
6939 print " title=\"". esc_html($author) . ", $date\"";
6940 print " rowspan=\"$group_size\"" if ($group_size > 1);
6941 print ">";
6942 print $cgi->a({-href => href(action=>"commit",
6943 hash=>$full_rev,
6944 file_name=>$file_name)},
6945 esc_html($short_rev));
6946 if ($group_size >= 2) {
6947 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6948 if (@author_initials) {
6949 print "<br />" .
6950 esc_html(join('', @author_initials));
6951 # or join('.', ...)
6954 print "</td>\n";
6956 # 'previous' <sha1 of parent commit> <filename at commit>
6957 if (exists $meta->{'previous'} &&
6958 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6959 $meta->{'parent'} = $1;
6960 $meta->{'file_parent'} = unquote($2);
6962 my $linenr_commit =
6963 exists($meta->{'parent'}) ?
6964 $meta->{'parent'} : $full_rev;
6965 my $linenr_filename =
6966 exists($meta->{'file_parent'}) ?
6967 $meta->{'file_parent'} : unquote($meta->{'filename'});
6968 my $blamed = href(action => 'blame',
6969 file_name => $linenr_filename,
6970 hash_base => $linenr_commit);
6971 print "<td class=\"linenr\">";
6972 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6973 -class => "linenr" },
6974 esc_html($lineno));
6975 print "</td>";
6976 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6977 print "</tr>\n";
6978 } # end while
6982 # footer
6983 print "</tbody>\n".
6984 "</table>\n"; # class="blame"
6985 print "</div>\n"; # class="blame_body"
6986 close $fd
6987 or print "Reading blob failed\n";
6989 git_footer_html();
6992 sub git_blame {
6993 git_blame_common();
6996 sub git_blame_incremental {
6997 git_blame_common('incremental');
7000 sub git_blame_data {
7001 git_blame_common('data');
7004 sub git_tags {
7005 my $head = git_get_head_hash($project);
7006 git_header_html();
7007 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
7008 git_print_header_div('summary', $project);
7010 my @tagslist = git_get_tags_list();
7011 if (@tagslist) {
7012 git_tags_body(\@tagslist);
7014 git_footer_html();
7017 sub git_heads {
7018 my $head = git_get_head_hash($project);
7019 git_header_html();
7020 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
7021 git_print_header_div('summary', $project);
7023 my @headslist = git_get_heads_list();
7024 if (@headslist) {
7025 git_heads_body(\@headslist, $head);
7027 git_footer_html();
7030 # used both for single remote view and for list of all the remotes
7031 sub git_remotes {
7032 gitweb_check_feature('remote_heads')
7033 or die_error(403, "Remote heads view is disabled");
7035 my $head = git_get_head_hash($project);
7036 my $remote = $input_params{'hash'};
7038 my $remotedata = git_get_remotes_list($remote);
7039 die_error(500, "Unable to get remote information") unless defined $remotedata;
7041 unless (%$remotedata) {
7042 die_error(404, defined $remote ?
7043 "Remote $remote not found" :
7044 "No remotes found");
7047 git_header_html(undef, undef, -action_extra => $remote);
7048 git_print_page_nav('', '', $head, undef, $head,
7049 format_ref_views($remote ? '' : 'remotes'));
7051 fill_remote_heads($remotedata);
7052 if (defined $remote) {
7053 git_print_header_div('remotes', "$remote remote for $project");
7054 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7055 } else {
7056 git_print_header_div('summary', "$project remotes");
7057 git_remotes_body($remotedata, undef, $head);
7060 git_footer_html();
7063 sub git_blob_plain {
7064 my $type = shift;
7065 my $expires;
7067 if (!defined $hash) {
7068 if (defined $file_name) {
7069 my $base = $hash_base || git_get_head_hash($project);
7070 $hash = git_get_hash_by_path($base, $file_name, "blob")
7071 or die_error(404, "Cannot find file");
7072 } else {
7073 die_error(400, "No file name defined");
7075 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7076 # blobs defined by non-textual hash id's can be cached
7077 $expires = "+1d";
7080 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
7081 or die_error(500, "Open git-cat-file blob '$hash' failed");
7082 binmode($fd);
7084 # content-type (can include charset)
7085 my $leader;
7086 ($type, $leader) = blob_contenttype($fd, $file_name, $type);
7088 # "save as" filename, even when no $file_name is given
7089 my $save_as = "$hash";
7090 if (defined $file_name) {
7091 $save_as = $file_name;
7092 } elsif ($type =~ m/^text\//) {
7093 $save_as .= '.txt';
7096 # With XSS prevention on, blobs of all types except a few known safe
7097 # ones are served with "Content-Disposition: attachment" to make sure
7098 # they don't run in our security domain. For certain image types,
7099 # blob view writes an <img> tag referring to blob_plain view, and we
7100 # want to be sure not to break that by serving the image as an
7101 # attachment (though Firefox 3 doesn't seem to care).
7102 my $sandbox = $prevent_xss &&
7103 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7105 # serve text/* as text/plain
7106 if ($prevent_xss &&
7107 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7108 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7109 my $rest = $1;
7110 $rest = defined $rest ? $rest : '';
7111 $type = "text/plain$rest";
7114 print $cgi->header(
7115 -type => $type,
7116 -expires => $expires,
7117 -content_disposition =>
7118 ($sandbox ? 'attachment' : 'inline')
7119 . '; filename="' . $save_as . '"');
7120 binmode STDOUT, ':raw';
7121 print $leader if defined $leader;
7122 my $buf;
7123 while (read($fd, $buf, 32768)) {
7124 print $buf;
7126 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7127 close $fd;
7130 sub git_blob {
7131 my $expires;
7133 if (!defined $hash) {
7134 if (defined $file_name) {
7135 my $base = $hash_base || git_get_head_hash($project);
7136 $hash = git_get_hash_by_path($base, $file_name, "blob")
7137 or die_error(404, "Cannot find file");
7138 } else {
7139 die_error(400, "No file name defined");
7141 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7142 # blobs defined by non-textual hash id's can be cached
7143 $expires = "+1d";
7146 my $have_blame = gitweb_check_feature('blame');
7147 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
7148 or die_error(500, "Couldn't cat $file_name, $hash");
7149 binmode($fd);
7150 my $mimetype = blob_mimetype($fd, $file_name);
7151 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7152 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7153 close $fd;
7154 return git_blob_plain($mimetype);
7156 # we can have blame only for text/* mimetype
7157 $have_blame &&= ($mimetype =~ m!^text/!);
7159 my $highlight = gitweb_check_feature('highlight');
7160 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7161 $fd = run_highlighter($fd, $highlight, $syntax)
7162 if $syntax;
7164 git_header_html(undef, $expires);
7165 my $formats_nav = '';
7166 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7167 if (defined $file_name) {
7168 if ($have_blame) {
7169 $formats_nav .=
7170 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7171 "blame") .
7172 " | ";
7174 $formats_nav .=
7175 $cgi->a({-href => href(action=>"history", -replay=>1)},
7176 "history") .
7177 " | " .
7178 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7179 "raw") .
7180 " | " .
7181 $cgi->a({-href => href(action=>"blob",
7182 hash_base=>"HEAD", file_name=>$file_name)},
7183 "HEAD");
7184 } else {
7185 $formats_nav .=
7186 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7187 "raw");
7189 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7190 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7191 } else {
7192 print "<div class=\"page_nav\">\n" .
7193 "<br/><br/></div>\n" .
7194 "<div class=\"title\">".esc_html($hash)."</div>\n";
7196 git_print_page_path($file_name, "blob", $hash_base);
7197 print "<div class=\"page_body\">\n";
7198 if ($mimetype =~ m!^image/!) {
7199 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7200 if ($file_name) {
7201 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7203 print qq! src="! .
7204 href(action=>"blob_plain", hash=>$hash,
7205 hash_base=>$hash_base, file_name=>$file_name) .
7206 qq!" />\n!;
7207 } else {
7208 my $nr;
7209 while (my $line = to_utf8(scalar <$fd>)) {
7210 chomp $line;
7211 $nr++;
7212 $line = untabify($line);
7213 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7214 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7215 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7218 close $fd
7219 or print "Reading blob failed.\n";
7220 print "</div>";
7221 git_footer_html();
7224 sub git_tree {
7225 if (!defined $hash_base) {
7226 $hash_base = "HEAD";
7228 if (!defined $hash) {
7229 if (defined $file_name) {
7230 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7231 } else {
7232 $hash = $hash_base;
7235 die_error(404, "No such tree") unless defined($hash);
7237 my $show_sizes = gitweb_check_feature('show-sizes');
7238 my $have_blame = gitweb_check_feature('blame');
7240 my @entries = ();
7242 local $/ = "\0";
7243 defined(my $fd = git_cmd_pipe "ls-tree", '-z',
7244 ($show_sizes ? '-l' : ()), @extra_options, $hash)
7245 or die_error(500, "Open git-ls-tree failed");
7246 @entries = map { chomp; to_utf8($_) } <$fd>;
7247 close $fd
7248 or die_error(404, "Reading tree failed");
7251 my $refs = git_get_references();
7252 my $ref = format_ref_marker($refs, $hash_base);
7253 git_header_html();
7254 my $basedir = '';
7255 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7256 my @views_nav = ();
7257 if (defined $file_name) {
7258 push @views_nav,
7259 $cgi->a({-href => href(action=>"history", -replay=>1)},
7260 "history"),
7261 $cgi->a({-href => href(action=>"tree",
7262 hash_base=>"HEAD", file_name=>$file_name)},
7263 "HEAD"),
7265 my $snapshot_links = format_snapshot_links($hash);
7266 if (defined $snapshot_links) {
7267 # FIXME: Should be available when we have no hash base as well.
7268 push @views_nav, $snapshot_links;
7270 git_print_page_nav('tree','', $hash_base, undef, undef,
7271 join(' | ', @views_nav));
7272 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7273 } else {
7274 undef $hash_base;
7275 print "<div class=\"page_nav\">\n";
7276 print "<br/><br/></div>\n";
7277 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7279 if (defined $file_name) {
7280 $basedir = $file_name;
7281 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7282 $basedir .= '/';
7284 git_print_page_path($file_name, 'tree', $hash_base);
7286 print "<div class=\"page_body\">\n";
7287 print "<table class=\"tree\">\n";
7288 my $alternate = 1;
7289 # '..' (top directory) link if possible
7290 if (defined $hash_base &&
7291 defined $file_name && $file_name =~ m![^/]+$!) {
7292 if ($alternate) {
7293 print "<tr class=\"dark\">\n";
7294 } else {
7295 print "<tr class=\"light\">\n";
7297 $alternate ^= 1;
7299 my $up = $file_name;
7300 $up =~ s!/?[^/]+$!!;
7301 undef $up unless $up;
7302 # based on git_print_tree_entry
7303 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7304 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7305 print '<td class="list">';
7306 print $cgi->a({-href => href(action=>"tree",
7307 hash_base=>$hash_base,
7308 file_name=>$up)},
7309 "..");
7310 print "</td>\n";
7311 print "<td class=\"link\"></td>\n";
7313 print "</tr>\n";
7315 foreach my $line (@entries) {
7316 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7318 if ($alternate) {
7319 print "<tr class=\"dark\">\n";
7320 } else {
7321 print "<tr class=\"light\">\n";
7323 $alternate ^= 1;
7325 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7327 print "</tr>\n";
7329 print "</table>\n" .
7330 "</div>";
7331 git_footer_html();
7334 sub sanitize_for_filename {
7335 my $name = shift;
7337 $name =~ s!/!-!g;
7338 $name =~ s/[^[:alnum:]_.-]//g;
7340 return $name;
7343 sub snapshot_name {
7344 my ($project, $hash) = @_;
7346 # path/to/project.git -> project
7347 # path/to/project/.git -> project
7348 my $name = to_utf8($project);
7349 $name =~ s,([^/])/*\.git$,$1,;
7350 $name = sanitize_for_filename(basename($name));
7352 my $ver = $hash;
7353 if ($hash =~ /^[0-9a-fA-F]+$/) {
7354 # shorten SHA-1 hash
7355 my $full_hash = git_get_full_hash($project, $hash);
7356 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7357 $ver = git_get_short_hash($project, $hash);
7359 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7360 # tags don't need shortened SHA-1 hash
7361 $ver = $1;
7362 } else {
7363 # branches and other need shortened SHA-1 hash
7364 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7365 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7366 my $ref_dir = (defined $1) ? $1 : '';
7367 $ver = $2;
7369 $ref_dir = sanitize_for_filename($ref_dir);
7370 # for refs neither in heads nor remotes we want to
7371 # add a ref dir to archive name
7372 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7373 $ver = $ref_dir . '-' . $ver;
7376 $ver .= '-' . git_get_short_hash($project, $hash);
7378 # special case of sanitization for filename - we change
7379 # slashes to dots instead of dashes
7380 # in case of hierarchical branch names
7381 $ver =~ s!/!.!g;
7382 $ver =~ s/[^[:alnum:]_.-]//g;
7384 # name = project-version_string
7385 $name = "$name-$ver";
7387 return wantarray ? ($name, $name) : $name;
7390 sub exit_if_unmodified_since {
7391 my ($latest_epoch) = @_;
7392 our $cgi;
7394 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7395 if (defined $if_modified) {
7396 my $since;
7397 if (eval { require HTTP::Date; 1; }) {
7398 $since = HTTP::Date::str2time($if_modified);
7399 } elsif (eval { require Time::ParseDate; 1; }) {
7400 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7402 if (defined $since && $latest_epoch <= $since) {
7403 my %latest_date = parse_date($latest_epoch);
7404 print $cgi->header(
7405 -last_modified => $latest_date{'rfc2822'},
7406 -status => '304 Not Modified');
7407 goto DONE_GITWEB;
7412 sub git_snapshot {
7413 my $format = $input_params{'snapshot_format'};
7414 if (!@snapshot_fmts) {
7415 die_error(403, "Snapshots not allowed");
7417 # default to first supported snapshot format
7418 $format ||= $snapshot_fmts[0];
7419 if ($format !~ m/^[a-z0-9]+$/) {
7420 die_error(400, "Invalid snapshot format parameter");
7421 } elsif (!exists($known_snapshot_formats{$format})) {
7422 die_error(400, "Unknown snapshot format");
7423 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7424 die_error(403, "Snapshot format not allowed");
7425 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7426 die_error(403, "Unsupported snapshot format");
7429 my $type = git_get_type("$hash^{}");
7430 if (!$type) {
7431 die_error(404, 'Object does not exist');
7432 } elsif ($type eq 'blob') {
7433 die_error(400, 'Object is not a tree-ish');
7436 my ($name, $prefix) = snapshot_name($project, $hash);
7437 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7439 my %co = parse_commit($hash);
7440 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7442 my @cmd = (
7443 git_cmd(), 'archive',
7444 "--format=$known_snapshot_formats{$format}{'format'}",
7445 "--prefix=$prefix/", $hash);
7446 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7447 @cmd = ($posix_shell_bin, '-c', quote_command(@cmd) .
7448 ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}}));
7451 $filename =~ s/(["\\])/\\$1/g;
7452 my %latest_date;
7453 if (%co) {
7454 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7457 print $cgi->header(
7458 -type => $known_snapshot_formats{$format}{'type'},
7459 -content_disposition => 'inline; filename="' . $filename . '"',
7460 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7461 -status => '200 OK');
7463 defined(my $fd = cmd_pipe @cmd)
7464 or die_error(500, "Execute git-archive failed");
7465 binmode($fd);
7466 binmode STDOUT, ':raw';
7467 my $buf;
7468 while (read($fd, $buf, 16384)) {
7469 print $buf;
7471 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7472 close $fd;
7475 sub git_log_generic {
7476 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7478 my $head = git_get_head_hash($project);
7479 if (!defined $base) {
7480 $base = $head;
7482 if (!defined $page) {
7483 $page = 0;
7485 my $refs = git_get_references();
7487 my $commit_hash = $base;
7488 if (defined $parent) {
7489 $commit_hash = "$parent..$base";
7491 my @commitlist =
7492 parse_commits($commit_hash, 101, (100 * $page),
7493 defined $file_name ? ($file_name, "--full-history") : ());
7495 my $ftype;
7496 if (!defined $file_hash && defined $file_name) {
7497 # some commits could have deleted file in question,
7498 # and not have it in tree, but one of them has to have it
7499 for (my $i = 0; $i < @commitlist; $i++) {
7500 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7501 last if defined $file_hash;
7504 if (defined $file_hash) {
7505 $ftype = git_get_type($file_hash);
7507 if (defined $file_name && !defined $ftype) {
7508 die_error(500, "Unknown type of object");
7510 my %co;
7511 if (defined $file_name) {
7512 %co = parse_commit($base)
7513 or die_error(404, "Unknown commit object");
7517 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7518 my $next_link = '';
7519 if ($#commitlist >= 100) {
7520 $next_link =
7521 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7522 -accesskey => "n", -title => "Alt-n"}, "next");
7524 my $patch_max = gitweb_get_feature('patches');
7525 if ($patch_max && !defined $file_name) {
7526 if ($patch_max < 0 || @commitlist <= $patch_max) {
7527 $paging_nav .= " &sdot; " .
7528 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7529 "patches");
7533 git_header_html();
7534 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7535 if (defined $file_name) {
7536 git_print_header_div('commit', esc_html($co{'title'}), $base);
7537 } else {
7538 git_print_header_div('summary', $project)
7540 git_print_page_path($file_name, $ftype, $hash_base)
7541 if (defined $file_name);
7543 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7544 $file_name, $file_hash, $ftype);
7546 git_footer_html();
7549 sub git_log {
7550 git_log_generic('log', \&git_log_body,
7551 $hash, $hash_parent);
7554 sub git_commit {
7555 $hash ||= $hash_base || "HEAD";
7556 my %co = parse_commit($hash)
7557 or die_error(404, "Unknown commit object");
7559 my $parent = $co{'parent'};
7560 my $parents = $co{'parents'}; # listref
7562 # we need to prepare $formats_nav before any parameter munging
7563 my $formats_nav;
7564 if (!defined $parent) {
7565 # --root commitdiff
7566 $formats_nav .= '(initial)';
7567 } elsif (@$parents == 1) {
7568 # single parent commit
7569 $formats_nav .=
7570 '(parent: ' .
7571 $cgi->a({-href => href(action=>"commit",
7572 hash=>$parent)},
7573 esc_html(substr($parent, 0, 7))) .
7574 ')';
7575 } else {
7576 # merge commit
7577 $formats_nav .=
7578 '(merge: ' .
7579 join(' ', map {
7580 $cgi->a({-href => href(action=>"commit",
7581 hash=>$_)},
7582 esc_html(substr($_, 0, 7)));
7583 } @$parents ) .
7584 ')';
7586 if (gitweb_check_feature('patches') && @$parents <= 1) {
7587 $formats_nav .= " | " .
7588 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7589 "patch");
7592 if (!defined $parent) {
7593 $parent = "--root";
7595 my @difftree;
7596 defined(my $fd = git_cmd_pipe "diff-tree", '-r', "--no-commit-id",
7597 @diff_opts,
7598 (@$parents <= 1 ? $parent : '-c'),
7599 $hash, "--")
7600 or die_error(500, "Open git-diff-tree failed");
7601 @difftree = map { chomp; to_utf8($_) } <$fd>;
7602 close $fd or die_error(404, "Reading git-diff-tree failed");
7604 # non-textual hash id's can be cached
7605 my $expires;
7606 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7607 $expires = "+1d";
7609 my $refs = git_get_references();
7610 my $ref = format_ref_marker($refs, $co{'id'});
7612 git_header_html(undef, $expires);
7613 git_print_page_nav('commit', '',
7614 $hash, $co{'tree'}, $hash,
7615 $formats_nav);
7617 if (defined $co{'parent'}) {
7618 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7619 } else {
7620 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7622 print "<div class=\"title_text\">\n" .
7623 "<table class=\"object_header\">\n";
7624 git_print_authorship_rows(\%co);
7625 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7626 print "<tr>" .
7627 "<td>tree</td>" .
7628 "<td class=\"sha1\">" .
7629 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7630 class => "list"}, $co{'tree'}) .
7631 "</td>" .
7632 "<td class=\"link\">" .
7633 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7634 "tree");
7635 my $snapshot_links = format_snapshot_links($hash);
7636 if (defined $snapshot_links) {
7637 print " | " . $snapshot_links;
7639 print "</td>" .
7640 "</tr>\n";
7642 foreach my $par (@$parents) {
7643 print "<tr>" .
7644 "<td>parent</td>" .
7645 "<td class=\"sha1\">" .
7646 $cgi->a({-href => href(action=>"commit", hash=>$par),
7647 class => "list"}, $par) .
7648 "</td>" .
7649 "<td class=\"link\">" .
7650 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7651 " | " .
7652 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7653 "</td>" .
7654 "</tr>\n";
7656 print "</table>".
7657 "</div>\n";
7659 print "<div class=\"page_body\">\n";
7660 git_print_log($co{'comment'});
7661 print "</div>\n";
7663 git_difftree_body(\@difftree, $hash, @$parents);
7665 git_footer_html();
7668 sub git_object {
7669 # object is defined by:
7670 # - hash or hash_base alone
7671 # - hash_base and file_name
7672 my $type;
7674 # - hash or hash_base alone
7675 if ($hash || ($hash_base && !defined $file_name)) {
7676 my $object_id = $hash || $hash_base;
7678 defined(my $fd = git_cmd_pipe 'cat-file', '-t', $object_id)
7679 or die_error(404, "Object does not exist");
7680 $type = <$fd>;
7681 chomp $type;
7682 close $fd
7683 or die_error(404, "Object does not exist");
7685 # - hash_base and file_name
7686 } elsif ($hash_base && defined $file_name) {
7687 $file_name =~ s,/+$,,;
7689 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7690 or die_error(404, "Base object does not exist");
7692 # here errors should not happen
7693 defined(my $fd = git_cmd_pipe "ls-tree", $hash_base, "--", $file_name)
7694 or die_error(500, "Open git-ls-tree failed");
7695 my $line = to_utf8(scalar <$fd>);
7696 close $fd;
7698 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7699 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7700 die_error(404, "File or directory for given base does not exist");
7702 $type = $2;
7703 $hash = $3;
7704 } else {
7705 die_error(400, "Not enough information to find object");
7708 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7709 hash=>$hash, hash_base=>$hash_base,
7710 file_name=>$file_name),
7711 -status => '302 Found');
7714 sub git_blobdiff {
7715 my $format = shift || 'html';
7716 my $diff_style = $input_params{'diff_style'} || 'inline';
7718 my $fd;
7719 my @difftree;
7720 my %diffinfo;
7721 my $expires;
7723 # preparing $fd and %diffinfo for git_patchset_body
7724 # new style URI
7725 if (defined $hash_base && defined $hash_parent_base) {
7726 if (defined $file_name) {
7727 # read raw output
7728 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
7729 $hash_parent_base, $hash_base,
7730 "--", (defined $file_parent ? $file_parent : ()), $file_name)
7731 or die_error(500, "Open git-diff-tree failed");
7732 @difftree = map { chomp; to_utf8($_) } <$fd>;
7733 close $fd
7734 or die_error(404, "Reading git-diff-tree failed");
7735 @difftree
7736 or die_error(404, "Blob diff not found");
7738 } elsif (defined $hash &&
7739 $hash =~ /[0-9a-fA-F]{40}/) {
7740 # try to find filename from $hash
7742 # read filtered raw output
7743 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
7744 $hash_parent_base, $hash_base, "--")
7745 or die_error(500, "Open git-diff-tree failed");
7746 @difftree =
7747 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7748 # $hash == to_id
7749 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7750 map { chomp; to_utf8($_) } <$fd>;
7751 close $fd
7752 or die_error(404, "Reading git-diff-tree failed");
7753 @difftree
7754 or die_error(404, "Blob diff not found");
7756 } else {
7757 die_error(400, "Missing one of the blob diff parameters");
7760 if (@difftree > 1) {
7761 die_error(400, "Ambiguous blob diff specification");
7764 %diffinfo = parse_difftree_raw_line($difftree[0]);
7765 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7766 $file_name ||= $diffinfo{'to_file'};
7768 $hash_parent ||= $diffinfo{'from_id'};
7769 $hash ||= $diffinfo{'to_id'};
7771 # non-textual hash id's can be cached
7772 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7773 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7774 $expires = '+1d';
7777 # open patch output
7778 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
7779 '-p', ($format eq 'html' ? "--full-index" : ()),
7780 $hash_parent_base, $hash_base,
7781 "--", (defined $file_parent ? $file_parent : ()), $file_name)
7782 or die_error(500, "Open git-diff-tree failed");
7785 # old/legacy style URI -- not generated anymore since 1.4.3.
7786 if (!%diffinfo) {
7787 die_error('404 Not Found', "Missing one of the blob diff parameters")
7790 # header
7791 if ($format eq 'html') {
7792 my $formats_nav =
7793 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7794 "raw");
7795 $formats_nav .= diff_style_nav($diff_style);
7796 git_header_html(undef, $expires);
7797 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7798 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7799 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7800 } else {
7801 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7802 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7804 if (defined $file_name) {
7805 git_print_page_path($file_name, "blob", $hash_base);
7806 } else {
7807 print "<div class=\"page_path\"></div>\n";
7810 } elsif ($format eq 'plain') {
7811 print $cgi->header(
7812 -type => 'text/plain',
7813 -charset => 'utf-8',
7814 -expires => $expires,
7815 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7817 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7819 } else {
7820 die_error(400, "Unknown blobdiff format");
7823 # patch
7824 if ($format eq 'html') {
7825 print "<div class=\"page_body\">\n";
7827 git_patchset_body($fd, $diff_style,
7828 [ \%diffinfo ], $hash_base, $hash_parent_base);
7829 close $fd;
7831 print "</div>\n"; # class="page_body"
7832 git_footer_html();
7834 } else {
7835 while (my $line = to_utf8(scalar <$fd>)) {
7836 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7837 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7839 print $line;
7841 last if $line =~ m!^\+\+\+!;
7843 while (<$fd>) {
7844 print to_utf8($_);
7846 close $fd;
7850 sub git_blobdiff_plain {
7851 git_blobdiff('plain');
7854 # assumes that it is added as later part of already existing navigation,
7855 # so it returns "| foo | bar" rather than just "foo | bar"
7856 sub diff_style_nav {
7857 my ($diff_style, $is_combined) = @_;
7858 $diff_style ||= 'inline';
7860 return "" if ($is_combined);
7862 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7863 my %styles = @styles;
7864 @styles =
7865 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7867 return join '',
7868 map { " | ".$_ }
7869 map {
7870 $_ eq $diff_style ? $styles{$_} :
7871 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7872 } @styles;
7875 sub git_commitdiff {
7876 my %params = @_;
7877 my $format = $params{-format} || 'html';
7878 my $diff_style = $input_params{'diff_style'} || 'inline';
7880 my ($patch_max) = gitweb_get_feature('patches');
7881 if ($format eq 'patch') {
7882 die_error(403, "Patch view not allowed") unless $patch_max;
7885 $hash ||= $hash_base || "HEAD";
7886 my %co = parse_commit($hash)
7887 or die_error(404, "Unknown commit object");
7889 # choose format for commitdiff for merge
7890 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7891 $hash_parent = '--cc';
7893 # we need to prepare $formats_nav before almost any parameter munging
7894 my $formats_nav;
7895 if ($format eq 'html') {
7896 $formats_nav =
7897 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7898 "raw");
7899 if ($patch_max && @{$co{'parents'}} <= 1) {
7900 $formats_nav .= " | " .
7901 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7902 "patch");
7904 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7906 if (defined $hash_parent &&
7907 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7908 # commitdiff with two commits given
7909 my $hash_parent_short = $hash_parent;
7910 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7911 $hash_parent_short = substr($hash_parent, 0, 7);
7913 $formats_nav .=
7914 ' (from';
7915 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7916 if ($co{'parents'}[$i] eq $hash_parent) {
7917 $formats_nav .= ' parent ' . ($i+1);
7918 last;
7921 $formats_nav .= ': ' .
7922 $cgi->a({-href => href(-replay=>1,
7923 hash=>$hash_parent, hash_base=>undef)},
7924 esc_html($hash_parent_short)) .
7925 ')';
7926 } elsif (!$co{'parent'}) {
7927 # --root commitdiff
7928 $formats_nav .= ' (initial)';
7929 } elsif (scalar @{$co{'parents'}} == 1) {
7930 # single parent commit
7931 $formats_nav .=
7932 ' (parent: ' .
7933 $cgi->a({-href => href(-replay=>1,
7934 hash=>$co{'parent'}, hash_base=>undef)},
7935 esc_html(substr($co{'parent'}, 0, 7))) .
7936 ')';
7937 } else {
7938 # merge commit
7939 if ($hash_parent eq '--cc') {
7940 $formats_nav .= ' | ' .
7941 $cgi->a({-href => href(-replay=>1,
7942 hash=>$hash, hash_parent=>'-c')},
7943 'combined');
7944 } else { # $hash_parent eq '-c'
7945 $formats_nav .= ' | ' .
7946 $cgi->a({-href => href(-replay=>1,
7947 hash=>$hash, hash_parent=>'--cc')},
7948 'compact');
7950 $formats_nav .=
7951 ' (merge: ' .
7952 join(' ', map {
7953 $cgi->a({-href => href(-replay=>1,
7954 hash=>$_, hash_base=>undef)},
7955 esc_html(substr($_, 0, 7)));
7956 } @{$co{'parents'}} ) .
7957 ')';
7961 my $hash_parent_param = $hash_parent;
7962 if (!defined $hash_parent_param) {
7963 # --cc for multiple parents, --root for parentless
7964 $hash_parent_param =
7965 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7968 # read commitdiff
7969 my $fd;
7970 my @difftree;
7971 if ($format eq 'html') {
7972 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
7973 "--no-commit-id", "--patch-with-raw", "--full-index",
7974 $hash_parent_param, $hash, "--")
7975 or die_error(500, "Open git-diff-tree failed");
7977 while (my $line = to_utf8(scalar <$fd>)) {
7978 chomp $line;
7979 # empty line ends raw part of diff-tree output
7980 last unless $line;
7981 push @difftree, scalar parse_difftree_raw_line($line);
7984 } elsif ($format eq 'plain') {
7985 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
7986 '-p', $hash_parent_param, $hash, "--")
7987 or die_error(500, "Open git-diff-tree failed");
7988 } elsif ($format eq 'patch') {
7989 # For commit ranges, we limit the output to the number of
7990 # patches specified in the 'patches' feature.
7991 # For single commits, we limit the output to a single patch,
7992 # diverging from the git-format-patch default.
7993 my @commit_spec = ();
7994 if ($hash_parent) {
7995 if ($patch_max > 0) {
7996 push @commit_spec, "-$patch_max";
7998 push @commit_spec, '-n', "$hash_parent..$hash";
7999 } else {
8000 if ($params{-single}) {
8001 push @commit_spec, '-1';
8002 } else {
8003 if ($patch_max > 0) {
8004 push @commit_spec, "-$patch_max";
8006 push @commit_spec, "-n";
8008 push @commit_spec, '--root', $hash;
8010 defined($fd = git_cmd_pipe "format-patch", @diff_opts,
8011 '--encoding=utf8', '--stdout', @commit_spec)
8012 or die_error(500, "Open git-format-patch failed");
8013 } else {
8014 die_error(400, "Unknown commitdiff format");
8017 # non-textual hash id's can be cached
8018 my $expires;
8019 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8020 $expires = "+1d";
8023 # write commit message
8024 if ($format eq 'html') {
8025 my $refs = git_get_references();
8026 my $ref = format_ref_marker($refs, $co{'id'});
8028 git_header_html(undef, $expires);
8029 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
8030 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
8031 print "<div class=\"title_text\">\n" .
8032 "<table class=\"object_header\">\n";
8033 git_print_authorship_rows(\%co);
8034 print "</table>".
8035 "</div>\n";
8036 print "<div class=\"page_body\">\n";
8037 if (@{$co{'comment'}} > 1) {
8038 print "<div class=\"log\">\n";
8039 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
8040 print "</div>\n"; # class="log"
8043 } elsif ($format eq 'plain') {
8044 my $refs = git_get_references("tags");
8045 my $tagname = git_get_rev_name_tags($hash);
8046 my $filename = basename($project) . "-$hash.patch";
8048 print $cgi->header(
8049 -type => 'text/plain',
8050 -charset => 'utf-8',
8051 -expires => $expires,
8052 -content_disposition => 'inline; filename="' . "$filename" . '"');
8053 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8054 print "From: " . to_utf8($co{'author'}) . "\n";
8055 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8056 print "Subject: " . to_utf8($co{'title'}) . "\n";
8058 print "X-Git-Tag: $tagname\n" if $tagname;
8059 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8061 foreach my $line (@{$co{'comment'}}) {
8062 print to_utf8($line) . "\n";
8064 print "---\n\n";
8065 } elsif ($format eq 'patch') {
8066 my $filename = basename($project) . "-$hash.patch";
8068 print $cgi->header(
8069 -type => 'text/plain',
8070 -charset => 'utf-8',
8071 -expires => $expires,
8072 -content_disposition => 'inline; filename="' . "$filename" . '"');
8075 # write patch
8076 if ($format eq 'html') {
8077 my $use_parents = !defined $hash_parent ||
8078 $hash_parent eq '-c' || $hash_parent eq '--cc';
8079 git_difftree_body(\@difftree, $hash,
8080 $use_parents ? @{$co{'parents'}} : $hash_parent);
8081 print "<br/>\n";
8083 git_patchset_body($fd, $diff_style,
8084 \@difftree, $hash,
8085 $use_parents ? @{$co{'parents'}} : $hash_parent);
8086 close $fd;
8087 print "</div>\n"; # class="page_body"
8088 git_footer_html();
8090 } elsif ($format eq 'plain') {
8091 while (<$fd>) {
8092 print to_utf8($_);
8094 close $fd
8095 or print "Reading git-diff-tree failed\n";
8096 } elsif ($format eq 'patch') {
8097 while (<$fd>) {
8098 print to_utf8($_);
8100 close $fd
8101 or print "Reading git-format-patch failed\n";
8105 sub git_commitdiff_plain {
8106 git_commitdiff(-format => 'plain');
8109 # format-patch-style patches
8110 sub git_patch {
8111 git_commitdiff(-format => 'patch', -single => 1);
8114 sub git_patches {
8115 git_commitdiff(-format => 'patch');
8118 sub git_history {
8119 git_log_generic('history', \&git_history_body,
8120 $hash_base, $hash_parent_base,
8121 $file_name, $hash);
8124 sub git_search {
8125 $searchtype ||= 'commit';
8127 # check if appropriate features are enabled
8128 gitweb_check_feature('search')
8129 or die_error(403, "Search is disabled");
8130 if ($searchtype eq 'pickaxe') {
8131 # pickaxe may take all resources of your box and run for several minutes
8132 # with every query - so decide by yourself how public you make this feature
8133 gitweb_check_feature('pickaxe')
8134 or die_error(403, "Pickaxe search is disabled");
8136 if ($searchtype eq 'grep') {
8137 # grep search might be potentially CPU-intensive, too
8138 gitweb_check_feature('grep')
8139 or die_error(403, "Grep search is disabled");
8142 if (!defined $searchtext) {
8143 die_error(400, "Text field is empty");
8145 if (!defined $hash) {
8146 $hash = git_get_head_hash($project);
8148 my %co = parse_commit($hash);
8149 if (!%co) {
8150 die_error(404, "Unknown commit object");
8152 if (!defined $page) {
8153 $page = 0;
8156 if ($searchtype eq 'commit' ||
8157 $searchtype eq 'author' ||
8158 $searchtype eq 'committer') {
8159 git_search_message(%co);
8160 } elsif ($searchtype eq 'pickaxe') {
8161 git_search_changes(%co);
8162 } elsif ($searchtype eq 'grep') {
8163 git_search_files(%co);
8164 } else {
8165 die_error(400, "Unknown search type");
8169 sub git_search_help {
8170 git_header_html();
8171 git_print_page_nav('','', $hash,$hash,$hash);
8172 print <<EOT;
8173 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8174 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8175 the pattern entered is recognized as the POSIX extended
8176 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8177 insensitive).</p>
8178 <dl>
8179 <dt><b>commit</b></dt>
8180 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8182 my $have_grep = gitweb_check_feature('grep');
8183 if ($have_grep) {
8184 print <<EOT;
8185 <dt><b>grep</b></dt>
8186 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8187 a different one) are searched for the given pattern. On large trees, this search can take
8188 a while and put some strain on the server, so please use it with some consideration. Note that
8189 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8190 case-sensitive.</dd>
8193 print <<EOT;
8194 <dt><b>author</b></dt>
8195 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8196 <dt><b>committer</b></dt>
8197 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8199 my $have_pickaxe = gitweb_check_feature('pickaxe');
8200 if ($have_pickaxe) {
8201 print <<EOT;
8202 <dt><b>pickaxe</b></dt>
8203 <dd>All commits that caused the string to appear or disappear from any file (changes that
8204 added, removed or "modified" the string) will be listed. This search can take a while and
8205 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8206 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8209 print "</dl>\n";
8210 git_footer_html();
8213 sub git_shortlog {
8214 git_log_generic('shortlog', \&git_shortlog_body,
8215 $hash, $hash_parent);
8218 ## ......................................................................
8219 ## feeds (RSS, Atom; OPML)
8221 sub git_feed {
8222 my $format = shift || 'atom';
8223 my $have_blame = gitweb_check_feature('blame');
8225 # Atom: http://www.atomenabled.org/developers/syndication/
8226 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8227 if ($format ne 'rss' && $format ne 'atom') {
8228 die_error(400, "Unknown web feed format");
8231 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8232 my $head = $hash || 'HEAD';
8233 my @commitlist = parse_commits($head, 150, 0, $file_name);
8235 my %latest_commit;
8236 my %latest_date;
8237 my $content_type = "application/$format+xml";
8238 if (defined $cgi->http('HTTP_ACCEPT') &&
8239 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8240 # browser (feed reader) prefers text/xml
8241 $content_type = 'text/xml';
8243 if (defined($commitlist[0])) {
8244 %latest_commit = %{$commitlist[0]};
8245 my $latest_epoch = $latest_commit{'committer_epoch'};
8246 exit_if_unmodified_since($latest_epoch);
8247 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8249 print $cgi->header(
8250 -type => $content_type,
8251 -charset => 'utf-8',
8252 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8253 -status => '200 OK');
8255 # Optimization: skip generating the body if client asks only
8256 # for Last-Modified date.
8257 return if ($cgi->request_method() eq 'HEAD');
8259 # header variables
8260 my $title = "$site_name - $project/$action";
8261 my $feed_type = 'log';
8262 if (defined $hash) {
8263 $title .= " - '$hash'";
8264 $feed_type = 'branch log';
8265 if (defined $file_name) {
8266 $title .= " :: $file_name";
8267 $feed_type = 'history';
8269 } elsif (defined $file_name) {
8270 $title .= " - $file_name";
8271 $feed_type = 'history';
8273 $title .= " $feed_type";
8274 $title = esc_html($title);
8275 my $descr = git_get_project_description($project);
8276 if (defined $descr) {
8277 $descr = esc_html($descr);
8278 } else {
8279 $descr = "$project " .
8280 ($format eq 'rss' ? 'RSS' : 'Atom') .
8281 " feed";
8283 my $owner = git_get_project_owner($project);
8284 $owner = esc_html($owner);
8286 #header
8287 my $alt_url;
8288 if (defined $file_name) {
8289 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8290 } elsif (defined $hash) {
8291 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8292 } else {
8293 $alt_url = href(-full=>1, action=>"summary");
8295 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8296 if ($format eq 'rss') {
8297 print <<XML;
8298 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8299 <channel>
8301 print "<title>$title</title>\n" .
8302 "<link>$alt_url</link>\n" .
8303 "<description>$descr</description>\n" .
8304 "<language>en</language>\n" .
8305 # project owner is responsible for 'editorial' content
8306 "<managingEditor>$owner</managingEditor>\n";
8307 if (defined $logo || defined $favicon) {
8308 # prefer the logo to the favicon, since RSS
8309 # doesn't allow both
8310 my $img = esc_url($logo || $favicon);
8311 print "<image>\n" .
8312 "<url>$img</url>\n" .
8313 "<title>$title</title>\n" .
8314 "<link>$alt_url</link>\n" .
8315 "</image>\n";
8317 if (%latest_date) {
8318 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8319 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8321 print "<generator>gitweb v.$version/$git_version</generator>\n";
8322 } elsif ($format eq 'atom') {
8323 print <<XML;
8324 <feed xmlns="http://www.w3.org/2005/Atom">
8326 print "<title>$title</title>\n" .
8327 "<subtitle>$descr</subtitle>\n" .
8328 '<link rel="alternate" type="text/html" href="' .
8329 $alt_url . '" />' . "\n" .
8330 '<link rel="self" type="' . $content_type . '" href="' .
8331 $cgi->self_url() . '" />' . "\n" .
8332 "<id>" . href(-full=>1) . "</id>\n" .
8333 # use project owner for feed author
8334 "<author><name>$owner</name></author>\n";
8335 if (defined $favicon) {
8336 print "<icon>" . esc_url($favicon) . "</icon>\n";
8338 if (defined $logo) {
8339 # not twice as wide as tall: 72 x 27 pixels
8340 print "<logo>" . esc_url($logo) . "</logo>\n";
8342 if (! %latest_date) {
8343 # dummy date to keep the feed valid until commits trickle in:
8344 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8345 } else {
8346 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8348 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8351 # contents
8352 for (my $i = 0; $i <= $#commitlist; $i++) {
8353 my %co = %{$commitlist[$i]};
8354 my $commit = $co{'id'};
8355 # we read 150, we always show 30 and the ones more recent than 48 hours
8356 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8357 last;
8359 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8361 # get list of changed files
8362 defined(my $fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8363 $co{'parent'} || "--root",
8364 $co{'id'}, "--", (defined $file_name ? $file_name : ()))
8365 or next;
8366 my @difftree = map { chomp; to_utf8($_) } <$fd>;
8367 close $fd
8368 or next;
8370 # print element (entry, item)
8371 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8372 if ($format eq 'rss') {
8373 print "<item>\n" .
8374 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8375 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8376 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8377 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8378 "<link>$co_url</link>\n" .
8379 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8380 "<content:encoded>" .
8381 "<![CDATA[\n";
8382 } elsif ($format eq 'atom') {
8383 print "<entry>\n" .
8384 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8385 "<updated>$cd{'iso-8601'}</updated>\n" .
8386 "<author>\n" .
8387 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8388 if ($co{'author_email'}) {
8389 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8391 print "</author>\n" .
8392 # use committer for contributor
8393 "<contributor>\n" .
8394 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8395 if ($co{'committer_email'}) {
8396 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8398 print "</contributor>\n" .
8399 "<published>$cd{'iso-8601'}</published>\n" .
8400 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8401 "<id>$co_url</id>\n" .
8402 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8403 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8405 my $comment = $co{'comment'};
8406 print "<pre>\n";
8407 foreach my $line (@$comment) {
8408 $line = esc_html($line);
8409 print "$line\n";
8411 print "</pre><ul>\n";
8412 foreach my $difftree_line (@difftree) {
8413 my %difftree = parse_difftree_raw_line($difftree_line);
8414 next if !$difftree{'from_id'};
8416 my $file = $difftree{'file'} || $difftree{'to_file'};
8418 print "<li>" .
8419 "[" .
8420 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8421 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8422 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8423 file_name=>$file, file_parent=>$difftree{'from_file'}),
8424 -title => "diff"}, 'D');
8425 if ($have_blame) {
8426 print $cgi->a({-href => href(-full=>1, action=>"blame",
8427 file_name=>$file, hash_base=>$commit),
8428 -title => "blame"}, 'B');
8430 # if this is not a feed of a file history
8431 if (!defined $file_name || $file_name ne $file) {
8432 print $cgi->a({-href => href(-full=>1, action=>"history",
8433 file_name=>$file, hash=>$commit),
8434 -title => "history"}, 'H');
8436 $file = esc_path($file);
8437 print "] ".
8438 "$file</li>\n";
8440 if ($format eq 'rss') {
8441 print "</ul>]]>\n" .
8442 "</content:encoded>\n" .
8443 "</item>\n";
8444 } elsif ($format eq 'atom') {
8445 print "</ul>\n</div>\n" .
8446 "</content>\n" .
8447 "</entry>\n";
8451 # end of feed
8452 if ($format eq 'rss') {
8453 print "</channel>\n</rss>\n";
8454 } elsif ($format eq 'atom') {
8455 print "</feed>\n";
8459 sub git_rss {
8460 git_feed('rss');
8463 sub git_atom {
8464 git_feed('atom');
8467 sub git_opml {
8468 my @list = git_get_projects_list($project_filter, $strict_export);
8469 if (!@list) {
8470 die_error(404, "No projects found");
8473 print $cgi->header(
8474 -type => 'text/xml',
8475 -charset => 'utf-8',
8476 -content_disposition => 'inline; filename="opml.xml"');
8478 my $title = esc_html($site_name);
8479 my $filter = " within subdirectory ";
8480 if (defined $project_filter) {
8481 $filter .= esc_html($project_filter);
8482 } else {
8483 $filter = "";
8485 print <<XML;
8486 <?xml version="1.0" encoding="utf-8"?>
8487 <opml version="1.0">
8488 <head>
8489 <title>$title OPML Export$filter</title>
8490 </head>
8491 <body>
8492 <outline text="git RSS feeds">
8495 foreach my $pr (@list) {
8496 my %proj = %$pr;
8497 my $head = git_get_head_hash($proj{'path'});
8498 if (!defined $head) {
8499 next;
8501 $git_dir = "$projectroot/$proj{'path'}";
8502 my %co = parse_commit($head);
8503 if (!%co) {
8504 next;
8507 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8508 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8509 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8510 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8512 print <<XML;
8513 </outline>
8514 </body>
8515 </opml>