Merge commit 'refs/top-bases/t/misc/encoding-opt' into t/misc/encoding-opt
[git/gitweb.git] / gitweb / gitweb.perl
blob6d1771cd65a6ec7fa300a6b8f5a27a15075e1c5e
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use 5.008;
11 use strict;
12 use warnings;
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
19 use File::Basename qw(basename);
20 use Time::HiRes qw(gettimeofday tv_interval);
21 binmode STDOUT, ':utf8';
23 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
24 eval 'sub CGI::multi_param { CGI::param(@_) }'
27 our $t0 = [ gettimeofday() ];
28 our $number_of_git_cmds = 0;
30 BEGIN {
31 CGI->compile() if $ENV{'MOD_PERL'};
34 our $version = "++GIT_VERSION++";
36 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
37 sub evaluate_uri {
38 our $cgi;
40 our $my_url = $cgi->url();
41 our $my_uri = $cgi->url(-absolute => 1);
43 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
44 # needed and used only for URLs with nonempty PATH_INFO
45 our $base_url = $my_url;
47 # When the script is used as DirectoryIndex, the URL does not contain the name
48 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
49 # have to do it ourselves. We make $path_info global because it's also used
50 # later on.
52 # Another issue with the script being the DirectoryIndex is that the resulting
53 # $my_url data is not the full script URL: this is good, because we want
54 # generated links to keep implying the script name if it wasn't explicitly
55 # indicated in the URL we're handling, but it means that $my_url cannot be used
56 # as base URL.
57 # Therefore, if we needed to strip PATH_INFO, then we know that we have
58 # to build the base URL ourselves:
59 our $path_info = decode_utf8($ENV{"PATH_INFO"});
60 if ($path_info) {
61 # $path_info has already been URL-decoded by the web server, but
62 # $my_url and $my_uri have not. URL-decode them so we can properly
63 # strip $path_info.
64 $my_url = unescape($my_url);
65 $my_uri = unescape($my_uri);
66 if ($my_url =~ s,\Q$path_info\E$,, &&
67 $my_uri =~ s,\Q$path_info\E$,, &&
68 defined $ENV{'SCRIPT_NAME'}) {
69 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
73 # target of the home link on top of all pages
74 our $home_link = $my_uri || "/";
77 # core git executable to use
78 # this can just be "git" if your webserver has a sensible PATH
79 our $GIT = "++GIT_BINDIR++/git";
81 # absolute fs-path which will be prepended to the project path
82 #our $projectroot = "/pub/scm";
83 our $projectroot = "++GITWEB_PROJECTROOT++";
85 # fs traversing limit for getting project list
86 # the number is relative to the projectroot
87 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
89 # string of the home link on top of all pages
90 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
92 # extra breadcrumbs preceding the home link
93 our @extra_breadcrumbs = ();
95 # name of your site or organization to appear in page titles
96 # replace this with something more descriptive for clearer bookmarks
97 our $site_name = "++GITWEB_SITENAME++"
98 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
100 # html snippet to include in the <head> section of each page
101 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
102 # filename of html text to include at top of each page
103 our $site_header = "++GITWEB_SITE_HEADER++";
104 # html text to include at home page
105 our $home_text = "++GITWEB_HOMETEXT++";
106 # filename of html text to include at bottom of each page
107 our $site_footer = "++GITWEB_SITE_FOOTER++";
109 # URI of stylesheets
110 our @stylesheets = ("++GITWEB_CSS++");
111 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
112 our $stylesheet = undef;
113 # URI of GIT logo (72x27 size)
114 our $logo = "++GITWEB_LOGO++";
115 # URI of GIT favicon, assumed to be image/png type
116 our $favicon = "++GITWEB_FAVICON++";
117 # URI of gitweb.js (JavaScript code for gitweb)
118 our $javascript = "++GITWEB_JS++";
120 # URI and label (title) of GIT logo link
121 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
122 #our $logo_label = "git documentation";
123 our $logo_url = "http://git-scm.com/";
124 our $logo_label = "git homepage";
126 # source of projects list
127 our $projects_list = "++GITWEB_LIST++";
129 # the width (in characters) of the projects list "Description" column
130 our $projects_list_description_width = 25;
132 # group projects by category on the projects list
133 # (enabled if this variable evaluates to true)
134 our $projects_list_group_categories = 0;
136 # default category if none specified
137 # (leave the empty string for no category)
138 our $project_list_default_category = "";
140 # default order of projects list
141 # valid values are none, project, descr, owner, and age
142 our $default_projects_order = "project";
144 # show repository only if this file exists
145 # (only effective if this variable evaluates to true)
146 our $export_ok = "++GITWEB_EXPORT_OK++";
148 # don't generate age column on the projects list page
149 our $omit_age_column = 0;
151 # don't generate information about owners of repositories
152 our $omit_owner=0;
154 # show repository only if this subroutine returns true
155 # when given the path to the project, for example:
156 # sub { return -e "$_[0]/git-daemon-export-ok"; }
157 our $export_auth_hook = undef;
159 # only allow viewing of repositories also shown on the overview page
160 our $strict_export = "++GITWEB_STRICT_EXPORT++";
162 # list of git base URLs used for URL to where fetch project from,
163 # i.e. full URL is "$git_base_url/$project"
164 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
166 # default blob_plain mimetype and default charset for text/plain blob
167 our $default_blob_plain_mimetype = 'text/plain';
168 our $default_text_plain_charset = undef;
170 # file to use for guessing MIME types before trying /etc/mime.types
171 # (relative to the current git repository)
172 our $mimetypes_file = undef;
174 # assume this charset if line contains non-UTF-8 characters;
175 # it should be valid encoding (see Encoding::Supported(3pm) for list),
176 # for which encoding all byte sequences are valid, for example
177 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
178 # could be even 'utf-8' for the old behavior)
179 our $fallback_encoding = 'latin1';
181 # rename detection options for git-diff and git-diff-tree
182 # - default is '-M', with the cost proportional to
183 # (number of removed files) * (number of new files).
184 # - more costly is '-C' (which implies '-M'), with the cost proportional to
185 # (number of changed files + number of removed files) * (number of new files)
186 # - even more costly is '-C', '--find-copies-harder' with cost
187 # (number of files in the original tree) * (number of new files)
188 # - one might want to include '-B' option, e.g. '-B', '-M'
189 our @diff_opts = ('-M'); # taken from git_commit
191 # Disables features that would allow repository owners to inject script into
192 # the gitweb domain.
193 our $prevent_xss = 0;
195 # Path to the highlight executable to use (must be the one from
196 # http://www.andre-simon.de due to assumptions about parameters and output).
197 # Useful if highlight is not installed on your webserver's PATH.
198 # [Default: highlight]
199 our $highlight_bin = "++HIGHLIGHT_BIN++";
201 # information about snapshot formats that gitweb is capable of serving
202 our %known_snapshot_formats = (
203 # name => {
204 # 'display' => display name,
205 # 'type' => mime type,
206 # 'suffix' => filename suffix,
207 # 'format' => --format for git-archive,
208 # 'compressor' => [compressor command and arguments]
209 # (array reference, optional)
210 # 'disabled' => boolean (optional)}
212 'tgz' => {
213 'display' => 'tar.gz',
214 'type' => 'application/x-gzip',
215 'suffix' => '.tar.gz',
216 'format' => 'tar',
217 'compressor' => ['gzip', '-n']},
219 'tbz2' => {
220 'display' => 'tar.bz2',
221 'type' => 'application/x-bzip2',
222 'suffix' => '.tar.bz2',
223 'format' => 'tar',
224 'compressor' => ['bzip2']},
226 'txz' => {
227 'display' => 'tar.xz',
228 'type' => 'application/x-xz',
229 'suffix' => '.tar.xz',
230 'format' => 'tar',
231 'compressor' => ['xz'],
232 'disabled' => 1},
234 'zip' => {
235 'display' => 'zip',
236 'type' => 'application/x-zip',
237 'suffix' => '.zip',
238 'format' => 'zip'},
241 # Aliases so we understand old gitweb.snapshot values in repository
242 # configuration.
243 our %known_snapshot_format_aliases = (
244 'gzip' => 'tgz',
245 'bzip2' => 'tbz2',
246 'xz' => 'txz',
248 # backward compatibility: legacy gitweb config support
249 'x-gzip' => undef, 'gz' => undef,
250 'x-bzip2' => undef, 'bz2' => undef,
251 'x-zip' => undef, '' => undef,
254 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
255 # are changed, it may be appropriate to change these values too via
256 # $GITWEB_CONFIG.
257 our %avatar_size = (
258 'default' => 16,
259 'double' => 32
262 # Used to set the maximum load that we will still respond to gitweb queries.
263 # If server load exceed this value then return "503 server busy" error.
264 # If gitweb cannot determined server load, it is taken to be 0.
265 # Leave it undefined (or set to 'undef') to turn off load checking.
266 our $maxload = 300;
268 # configuration for 'highlight' (http://www.andre-simon.de/)
269 # match by basename
270 our %highlight_basename = (
271 #'Program' => 'py',
272 #'Library' => 'py',
273 'SConstruct' => 'py', # SCons equivalent of Makefile
274 'Makefile' => 'make',
276 # match by extension
277 our %highlight_ext = (
278 # main extensions, defining name of syntax;
279 # see files in /usr/share/highlight/langDefs/ directory
280 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
281 # alternate extensions, see /etc/highlight/filetypes.conf
282 (map { $_ => 'c' } qw(c h)),
283 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
284 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
285 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
286 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
287 (map { $_ => 'make'} qw(make mak mk)),
288 (map { $_ => 'xml' } qw(xml xhtml html htm)),
291 # You define site-wide feature defaults here; override them with
292 # $GITWEB_CONFIG as necessary.
293 our %feature = (
294 # feature => {
295 # 'sub' => feature-sub (subroutine),
296 # 'override' => allow-override (boolean),
297 # 'default' => [ default options...] (array reference)}
299 # if feature is overridable (it means that allow-override has true value),
300 # then feature-sub will be called with default options as parameters;
301 # return value of feature-sub indicates if to enable specified feature
303 # if there is no 'sub' key (no feature-sub), then feature cannot be
304 # overridden
306 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
307 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
308 # is enabled
310 # Enable the 'blame' blob view, showing the last commit that modified
311 # each line in the file. This can be very CPU-intensive.
313 # To enable system wide have in $GITWEB_CONFIG
314 # $feature{'blame'}{'default'} = [1];
315 # To have project specific config enable override in $GITWEB_CONFIG
316 # $feature{'blame'}{'override'} = 1;
317 # and in project config gitweb.blame = 0|1;
318 'blame' => {
319 'sub' => sub { feature_bool('blame', @_) },
320 'override' => 0,
321 'default' => [0]},
323 # Enable the 'snapshot' link, providing a compressed archive of any
324 # tree. This can potentially generate high traffic if you have large
325 # project.
327 # Value is a list of formats defined in %known_snapshot_formats that
328 # you wish to offer.
329 # To disable system wide have in $GITWEB_CONFIG
330 # $feature{'snapshot'}{'default'} = [];
331 # To have project specific config enable override in $GITWEB_CONFIG
332 # $feature{'snapshot'}{'override'} = 1;
333 # and in project config, a comma-separated list of formats or "none"
334 # to disable. Example: gitweb.snapshot = tbz2,zip;
335 'snapshot' => {
336 'sub' => \&feature_snapshot,
337 'override' => 0,
338 'default' => ['tgz']},
340 # Enable text search, which will list the commits which match author,
341 # committer or commit text to a given string. Enabled by default.
342 # Project specific override is not supported.
344 # Note that this controls all search features, which means that if
345 # it is disabled, then 'grep' and 'pickaxe' search would also be
346 # disabled.
347 'search' => {
348 'override' => 0,
349 'default' => [1]},
351 # Enable grep search, which will list the files in currently selected
352 # tree containing the given string. Enabled by default. This can be
353 # potentially CPU-intensive, of course.
354 # Note that you need to have 'search' feature enabled too.
356 # To enable system wide have in $GITWEB_CONFIG
357 # $feature{'grep'}{'default'} = [1];
358 # To have project specific config enable override in $GITWEB_CONFIG
359 # $feature{'grep'}{'override'} = 1;
360 # and in project config gitweb.grep = 0|1;
361 'grep' => {
362 'sub' => sub { feature_bool('grep', @_) },
363 'override' => 0,
364 'default' => [1]},
366 # Enable the pickaxe search, which will list the commits that modified
367 # a given string in a file. This can be practical and quite faster
368 # alternative to 'blame', but still potentially CPU-intensive.
369 # Note that you need to have 'search' feature enabled too.
371 # To enable system wide have in $GITWEB_CONFIG
372 # $feature{'pickaxe'}{'default'} = [1];
373 # To have project specific config enable override in $GITWEB_CONFIG
374 # $feature{'pickaxe'}{'override'} = 1;
375 # and in project config gitweb.pickaxe = 0|1;
376 'pickaxe' => {
377 'sub' => sub { feature_bool('pickaxe', @_) },
378 'override' => 0,
379 'default' => [1]},
381 # Enable showing size of blobs in a 'tree' view, in a separate
382 # column, similar to what 'ls -l' does. This cost a bit of IO.
384 # To disable system wide have in $GITWEB_CONFIG
385 # $feature{'show-sizes'}{'default'} = [0];
386 # To have project specific config enable override in $GITWEB_CONFIG
387 # $feature{'show-sizes'}{'override'} = 1;
388 # and in project config gitweb.showsizes = 0|1;
389 'show-sizes' => {
390 'sub' => sub { feature_bool('showsizes', @_) },
391 'override' => 0,
392 'default' => [1]},
394 # Make gitweb use an alternative format of the URLs which can be
395 # more readable and natural-looking: project name is embedded
396 # directly in the path and the query string contains other
397 # auxiliary information. All gitweb installations recognize
398 # URL in either format; this configures in which formats gitweb
399 # generates links.
401 # To enable system wide have in $GITWEB_CONFIG
402 # $feature{'pathinfo'}{'default'} = [1];
403 # Project specific override is not supported.
405 # Note that you will need to change the default location of CSS,
406 # favicon, logo and possibly other files to an absolute URL. Also,
407 # if gitweb.cgi serves as your indexfile, you will need to force
408 # $my_uri to contain the script name in your $GITWEB_CONFIG (and you
409 # will also likely want to set $home_link if you're setting $my_uri).
410 'pathinfo' => {
411 'override' => 0,
412 'default' => [0]},
414 # Make gitweb consider projects in project root subdirectories
415 # to be forks of existing projects. Given project $projname.git,
416 # projects matching $projname/*.git will not be shown in the main
417 # projects list, instead a '+' mark will be added to $projname
418 # there and a 'forks' view will be enabled for the project, listing
419 # all the forks. If project list is taken from a file, forks have
420 # to be listed after the main project.
422 # To enable system wide have in $GITWEB_CONFIG
423 # $feature{'forks'}{'default'} = [1];
424 # Project specific override is not supported.
425 'forks' => {
426 'override' => 0,
427 'default' => [0]},
429 # Insert custom links to the action bar of all project pages.
430 # This enables you mainly to link to third-party scripts integrating
431 # into gitweb; e.g. git-browser for graphical history representation
432 # or custom web-based repository administration interface.
434 # The 'default' value consists of a list of triplets in the form
435 # (label, link, position) where position is the label after which
436 # to insert the link and link is a format string where %n expands
437 # to the project name, %f to the project path within the filesystem,
438 # %h to the current hash (h gitweb parameter) and %b to the current
439 # hash base (hb gitweb parameter); %% expands to %.
441 # To enable system wide have in $GITWEB_CONFIG e.g.
442 # $feature{'actions'}{'default'} = [('graphiclog',
443 # '/git-browser/by-commit.html?r=%n', 'summary')];
444 # Project specific override is not supported.
445 'actions' => {
446 'override' => 0,
447 'default' => []},
449 # Allow gitweb scan project content tags of project repository,
450 # and display the popular Web 2.0-ish "tag cloud" near the projects
451 # list. Note that this is something COMPLETELY different from the
452 # normal Git tags.
454 # gitweb by itself can show existing tags, but it does not handle
455 # tagging itself; you need to do it externally, outside gitweb.
456 # The format is described in git_get_project_ctags() subroutine.
457 # You may want to install the HTML::TagCloud Perl module to get
458 # a pretty tag cloud instead of just a list of tags.
460 # To enable system wide have in $GITWEB_CONFIG
461 # $feature{'ctags'}{'default'} = [1];
462 # Project specific override is not supported.
464 # In the future whether ctags editing is enabled might depend
465 # on the value, but using 1 should always mean no editing of ctags.
466 'ctags' => {
467 'override' => 0,
468 'default' => [0]},
470 # The maximum number of patches in a patchset generated in patch
471 # view. Set this to 0 or undef to disable patch view, or to a
472 # negative number to remove any limit.
474 # To disable system wide have in $GITWEB_CONFIG
475 # $feature{'patches'}{'default'} = [0];
476 # To have project specific config enable override in $GITWEB_CONFIG
477 # $feature{'patches'}{'override'} = 1;
478 # and in project config gitweb.patches = 0|n;
479 # where n is the maximum number of patches allowed in a patchset.
480 'patches' => {
481 'sub' => \&feature_patches,
482 'override' => 0,
483 'default' => [16]},
485 # Avatar support. When this feature is enabled, views such as
486 # shortlog or commit will display an avatar associated with
487 # the email of the committer(s) and/or author(s).
489 # Currently available providers are gravatar and picon.
490 # If an unknown provider is specified, the feature is disabled.
492 # Gravatar depends on Digest::MD5.
493 # Picon currently relies on the indiana.edu database.
495 # To enable system wide have in $GITWEB_CONFIG
496 # $feature{'avatar'}{'default'} = ['<provider>'];
497 # where <provider> is either gravatar or picon.
498 # To have project specific config enable override in $GITWEB_CONFIG
499 # $feature{'avatar'}{'override'} = 1;
500 # and in project config gitweb.avatar = <provider>;
501 'avatar' => {
502 'sub' => \&feature_avatar,
503 'override' => 0,
504 'default' => ['']},
506 # Enable displaying how much time and how many git commands
507 # it took to generate and display page. Disabled by default.
508 # Project specific override is not supported.
509 'timed' => {
510 'override' => 0,
511 'default' => [0]},
513 # Enable turning some links into links to actions which require
514 # JavaScript to run (like 'blame_incremental'). Not enabled by
515 # default. Project specific override is currently not supported.
516 'javascript-actions' => {
517 'override' => 0,
518 'default' => [0]},
520 # Enable and configure ability to change common timezone for dates
521 # in gitweb output via JavaScript. Enabled by default.
522 # Project specific override is not supported.
523 'javascript-timezone' => {
524 'override' => 0,
525 'default' => [
526 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
527 # or undef to turn off this feature
528 'gitweb_tz', # name of cookie where to store selected timezone
529 'datetime', # CSS class used to mark up dates for manipulation
532 # Syntax highlighting support. This is based on Daniel Svensson's
533 # and Sham Chukoury's work in gitweb-xmms2.git.
534 # It requires the 'highlight' program present in $PATH,
535 # and therefore is disabled by default.
537 # To enable system wide have in $GITWEB_CONFIG
538 # $feature{'highlight'}{'default'} = [1];
540 'highlight' => {
541 'sub' => sub { feature_bool('highlight', @_) },
542 'override' => 0,
543 'default' => [0]},
545 # Enable displaying of remote heads in the heads list
547 # To enable system wide have in $GITWEB_CONFIG
548 # $feature{'remote_heads'}{'default'} = [1];
549 # To have project specific config enable override in $GITWEB_CONFIG
550 # $feature{'remote_heads'}{'override'} = 1;
551 # and in project config gitweb.remoteheads = 0|1;
552 'remote_heads' => {
553 'sub' => sub { feature_bool('remote_heads', @_) },
554 'override' => 0,
555 'default' => [0]},
557 # Enable showing branches under other refs in addition to heads
559 # To set system wide extra branch refs have in $GITWEB_CONFIG
560 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
561 # To have project specific config enable override in $GITWEB_CONFIG
562 # $feature{'extra-branch-refs'}{'override'} = 1;
563 # and in project config gitweb.extrabranchrefs = dirs of choice
564 # Every directory is separated with whitespace.
566 'extra-branch-refs' => {
567 'sub' => \&feature_extra_branch_refs,
568 'override' => 0,
569 'default' => []},
572 sub gitweb_get_feature {
573 my ($name) = @_;
574 return unless exists $feature{$name};
575 my ($sub, $override, @defaults) = (
576 $feature{$name}{'sub'},
577 $feature{$name}{'override'},
578 @{$feature{$name}{'default'}});
579 # project specific override is possible only if we have project
580 our $git_dir; # global variable, declared later
581 if (!$override || !defined $git_dir) {
582 return @defaults;
584 if (!defined $sub) {
585 warn "feature $name is not overridable";
586 return @defaults;
588 return $sub->(@defaults);
591 # A wrapper to check if a given feature is enabled.
592 # With this, you can say
594 # my $bool_feat = gitweb_check_feature('bool_feat');
595 # gitweb_check_feature('bool_feat') or somecode;
597 # instead of
599 # my ($bool_feat) = gitweb_get_feature('bool_feat');
600 # (gitweb_get_feature('bool_feat'))[0] or somecode;
602 sub gitweb_check_feature {
603 return (gitweb_get_feature(@_))[0];
607 sub feature_bool {
608 my $key = shift;
609 my ($val) = git_get_project_config($key, '--bool');
611 if (!defined $val) {
612 return ($_[0]);
613 } elsif ($val eq 'true') {
614 return (1);
615 } elsif ($val eq 'false') {
616 return (0);
620 sub feature_snapshot {
621 my (@fmts) = @_;
623 my ($val) = git_get_project_config('snapshot');
625 if ($val) {
626 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
629 return @fmts;
632 sub feature_patches {
633 my @val = (git_get_project_config('patches', '--int'));
635 if (@val) {
636 return @val;
639 return ($_[0]);
642 sub feature_avatar {
643 my @val = (git_get_project_config('avatar'));
645 return @val ? @val : @_;
648 sub feature_extra_branch_refs {
649 my (@branch_refs) = @_;
650 my $values = git_get_project_config('extrabranchrefs');
652 if ($values) {
653 $values = config_to_multi ($values);
654 @branch_refs = ();
655 foreach my $value (@{$values}) {
656 push @branch_refs, split /\s+/, $value;
660 return @branch_refs;
663 # checking HEAD file with -e is fragile if the repository was
664 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
665 # and then pruned.
666 sub check_head_link {
667 my ($dir) = @_;
668 my $headfile = "$dir/HEAD";
669 return ((-e $headfile) ||
670 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
673 sub check_export_ok {
674 my ($dir) = @_;
675 return (check_head_link($dir) &&
676 (!$export_ok || -e "$dir/$export_ok") &&
677 (!$export_auth_hook || $export_auth_hook->($dir)));
680 # process alternate names for backward compatibility
681 # filter out unsupported (unknown) snapshot formats
682 sub filter_snapshot_fmts {
683 my @fmts = @_;
685 @fmts = map {
686 exists $known_snapshot_format_aliases{$_} ?
687 $known_snapshot_format_aliases{$_} : $_} @fmts;
688 @fmts = grep {
689 exists $known_snapshot_formats{$_} &&
690 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
693 sub filter_and_validate_refs {
694 my @refs = @_;
695 my %unique_refs = ();
697 foreach my $ref (@refs) {
698 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
699 # 'heads' are added implicitly in get_branch_refs().
700 $unique_refs{$ref} = 1 if ($ref ne 'heads');
702 return sort keys %unique_refs;
705 # If it is set to code reference, it is code that it is to be run once per
706 # request, allowing updating configurations that change with each request,
707 # while running other code in config file only once.
709 # Otherwise, if it is false then gitweb would process config file only once;
710 # if it is true then gitweb config would be run for each request.
711 our $per_request_config = 1;
713 # If true and fileno STDIN is 0 and getsockname succeeds, then FCGI mode will
714 # be activated automatically as though the --fcgi option was given.
715 our $auto_fcgi = 0;
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 our $encode_object;
757 sub evaluate_encoding {
758 my $requested = $fallback_encoding || 'ISO-8859-1';
759 my $obj = Encode::find_encoding($requested) or
760 die_error(400, "Requested fallback encoding not found");
761 if ($obj->name eq 'iso-8859-1') {
762 # Use Windows-1252 instead as required by the HTML 5 standard
763 my $altobj = Encode::find_encoding('Windows-1252');
764 $obj = $altobj if $altobj;
766 $encode_object = $obj;
769 # Get loadavg of system, to compare against $maxload.
770 # Currently it requires '/proc/loadavg' present to get loadavg;
771 # if it is not present it returns 0, which means no load checking.
772 sub get_loadavg {
773 if( -e '/proc/loadavg' ){
774 open my $fd, '<', '/proc/loadavg'
775 or return 0;
776 my @load = split(/\s+/, scalar <$fd>);
777 close $fd;
779 # The first three columns measure CPU and IO utilization of the last one,
780 # five, and 10 minute periods. The fourth column shows the number of
781 # currently running processes and the total number of processes in the m/n
782 # format. The last column displays the last process ID used.
783 return $load[0] || 0;
785 # additional checks for load average should go here for things that don't export
786 # /proc/loadavg
788 return 0;
791 # version of the core git binary
792 our $git_version;
793 sub evaluate_git_version {
794 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
795 $number_of_git_cmds++;
798 sub check_loadavg {
799 if (defined $maxload && get_loadavg() > $maxload) {
800 die_error(503, "The load average on the server is too high");
804 # ======================================================================
805 # input validation and dispatch
807 # input parameters can be collected from a variety of sources (presently, CGI
808 # and PATH_INFO), so we define an %input_params hash that collects them all
809 # together during validation: this allows subsequent uses (e.g. href()) to be
810 # agnostic of the parameter origin
812 our %input_params = ();
814 # input parameters are stored with the long parameter name as key. This will
815 # also be used in the href subroutine to convert parameters to their CGI
816 # equivalent, and since the href() usage is the most frequent one, we store
817 # the name -> CGI key mapping here, instead of the reverse.
819 # XXX: Warning: If you touch this, check the search form for updating,
820 # too.
822 our @cgi_param_mapping = (
823 project => "p",
824 action => "a",
825 file_name => "f",
826 file_parent => "fp",
827 hash => "h",
828 hash_parent => "hp",
829 hash_base => "hb",
830 hash_parent_base => "hpb",
831 page => "pg",
832 order => "o",
833 searchtext => "s",
834 searchtype => "st",
835 snapshot_format => "sf",
836 extra_options => "opt",
837 search_use_regexp => "sr",
838 ctag => "by_tag",
839 diff_style => "ds",
840 project_filter => "pf",
841 # this must be last entry (for manipulation from JavaScript)
842 javascript => "js"
844 our %cgi_param_mapping = @cgi_param_mapping;
846 # we will also need to know the possible actions, for validation
847 our %actions = (
848 "blame" => \&git_blame,
849 "blame_incremental" => \&git_blame_incremental,
850 "blame_data" => \&git_blame_data,
851 "blobdiff" => \&git_blobdiff,
852 "blobdiff_plain" => \&git_blobdiff_plain,
853 "blob" => \&git_blob,
854 "blob_plain" => \&git_blob_plain,
855 "commitdiff" => \&git_commitdiff,
856 "commitdiff_plain" => \&git_commitdiff_plain,
857 "commit" => \&git_commit,
858 "forks" => \&git_forks,
859 "heads" => \&git_heads,
860 "history" => \&git_history,
861 "log" => \&git_log,
862 "patch" => \&git_patch,
863 "patches" => \&git_patches,
864 "remotes" => \&git_remotes,
865 "rss" => \&git_rss,
866 "atom" => \&git_atom,
867 "search" => \&git_search,
868 "search_help" => \&git_search_help,
869 "shortlog" => \&git_shortlog,
870 "summary" => \&git_summary,
871 "tag" => \&git_tag,
872 "tags" => \&git_tags,
873 "tree" => \&git_tree,
874 "snapshot" => \&git_snapshot,
875 "object" => \&git_object,
876 # those below don't need $project
877 "opml" => \&git_opml,
878 "project_list" => \&git_project_list,
879 "project_index" => \&git_project_index,
882 # finally, we have the hash of allowed extra_options for the commands that
883 # allow them
884 our %allowed_options = (
885 "--no-merges" => [ qw(rss atom log shortlog history) ],
888 # fill %input_params with the CGI parameters. All values except for 'opt'
889 # should be single values, but opt can be an array. We should probably
890 # build an array of parameters that can be multi-valued, but since for the time
891 # being it's only this one, we just single it out
892 sub evaluate_query_params {
893 our $cgi;
895 while (my ($name, $symbol) = each %cgi_param_mapping) {
896 if ($symbol eq 'opt') {
897 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
898 } else {
899 $input_params{$name} = decode_utf8($cgi->param($symbol));
904 # now read PATH_INFO and update the parameter list for missing parameters
905 sub evaluate_path_info {
906 return if defined $input_params{'project'};
907 return if !$path_info;
908 $path_info =~ s,^/+,,;
909 return if !$path_info;
911 # find which part of PATH_INFO is project
912 my $project = $path_info;
913 $project =~ s,/+$,,;
914 while ($project && !check_head_link("$projectroot/$project")) {
915 $project =~ s,/*[^/]*$,,;
917 return unless $project;
918 $input_params{'project'} = $project;
920 # do not change any parameters if an action is given using the query string
921 return if $input_params{'action'};
922 $path_info =~ s,^\Q$project\E/*,,;
924 # next, check if we have an action
925 my $action = $path_info;
926 $action =~ s,/.*$,,;
927 if (exists $actions{$action}) {
928 $path_info =~ s,^$action/*,,;
929 $input_params{'action'} = $action;
932 # list of actions that want hash_base instead of hash, but can have no
933 # pathname (f) parameter
934 my @wants_base = (
935 'tree',
936 'history',
939 # we want to catch, among others
940 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
941 my ($parentrefname, $parentpathname, $refname, $pathname) =
942 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
944 # first, analyze the 'current' part
945 if (defined $pathname) {
946 # we got "branch:filename" or "branch:dir/"
947 # we could use git_get_type(branch:pathname), but:
948 # - it needs $git_dir
949 # - it does a git() call
950 # - the convention of terminating directories with a slash
951 # makes it superfluous
952 # - embedding the action in the PATH_INFO would make it even
953 # more superfluous
954 $pathname =~ s,^/+,,;
955 if (!$pathname || substr($pathname, -1) eq "/") {
956 $input_params{'action'} ||= "tree";
957 $pathname =~ s,/$,,;
958 } else {
959 # the default action depends on whether we had parent info
960 # or not
961 if ($parentrefname) {
962 $input_params{'action'} ||= "blobdiff_plain";
963 } else {
964 $input_params{'action'} ||= "blob_plain";
967 $input_params{'hash_base'} ||= $refname;
968 $input_params{'file_name'} ||= $pathname;
969 } elsif (defined $refname) {
970 # we got "branch". In this case we have to choose if we have to
971 # set hash or hash_base.
973 # Most of the actions without a pathname only want hash to be
974 # set, except for the ones specified in @wants_base that want
975 # hash_base instead. It should also be noted that hand-crafted
976 # links having 'history' as an action and no pathname or hash
977 # set will fail, but that happens regardless of PATH_INFO.
978 if (defined $parentrefname) {
979 # if there is parent let the default be 'shortlog' action
980 # (for http://git.example.com/repo.git/A..B links); if there
981 # is no parent, dispatch will detect type of object and set
982 # action appropriately if required (if action is not set)
983 $input_params{'action'} ||= "shortlog";
985 if ($input_params{'action'} &&
986 grep { $_ eq $input_params{'action'} } @wants_base) {
987 $input_params{'hash_base'} ||= $refname;
988 } else {
989 $input_params{'hash'} ||= $refname;
993 # next, handle the 'parent' part, if present
994 if (defined $parentrefname) {
995 # a missing pathspec defaults to the 'current' filename, allowing e.g.
996 # someproject/blobdiff/oldrev..newrev:/filename
997 if ($parentpathname) {
998 $parentpathname =~ s,^/+,,;
999 $parentpathname =~ s,/$,,;
1000 $input_params{'file_parent'} ||= $parentpathname;
1001 } else {
1002 $input_params{'file_parent'} ||= $input_params{'file_name'};
1004 # we assume that hash_parent_base is wanted if a path was specified,
1005 # or if the action wants hash_base instead of hash
1006 if (defined $input_params{'file_parent'} ||
1007 grep { $_ eq $input_params{'action'} } @wants_base) {
1008 $input_params{'hash_parent_base'} ||= $parentrefname;
1009 } else {
1010 $input_params{'hash_parent'} ||= $parentrefname;
1014 # for the snapshot action, we allow URLs in the form
1015 # $project/snapshot/$hash.ext
1016 # where .ext determines the snapshot and gets removed from the
1017 # passed $refname to provide the $hash.
1019 # To be able to tell that $refname includes the format extension, we
1020 # require the following two conditions to be satisfied:
1021 # - the hash input parameter MUST have been set from the $refname part
1022 # of the URL (i.e. they must be equal)
1023 # - the snapshot format MUST NOT have been defined already (e.g. from
1024 # CGI parameter sf)
1025 # It's also useless to try any matching unless $refname has a dot,
1026 # so we check for that too
1027 if (defined $input_params{'action'} &&
1028 $input_params{'action'} eq 'snapshot' &&
1029 defined $refname && index($refname, '.') != -1 &&
1030 $refname eq $input_params{'hash'} &&
1031 !defined $input_params{'snapshot_format'}) {
1032 # We loop over the known snapshot formats, checking for
1033 # extensions. Allowed extensions are both the defined suffix
1034 # (which includes the initial dot already) and the snapshot
1035 # format key itself, with a prepended dot
1036 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1037 my $hash = $refname;
1038 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1039 next;
1041 my $sfx = $1;
1042 # a valid suffix was found, so set the snapshot format
1043 # and reset the hash parameter
1044 $input_params{'snapshot_format'} = $fmt;
1045 $input_params{'hash'} = $hash;
1046 # we also set the format suffix to the one requested
1047 # in the URL: this way a request for e.g. .tgz returns
1048 # a .tgz instead of a .tar.gz
1049 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1050 last;
1055 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1056 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1057 $searchtext, $search_regexp, $project_filter);
1058 sub evaluate_and_validate_params {
1059 our $action = $input_params{'action'};
1060 if (defined $action) {
1061 if (!is_valid_action($action)) {
1062 die_error(400, "Invalid action parameter");
1066 # parameters which are pathnames
1067 our $project = $input_params{'project'};
1068 if (defined $project) {
1069 if (!is_valid_project($project)) {
1070 undef $project;
1071 die_error(404, "No such project");
1075 our $project_filter = $input_params{'project_filter'};
1076 if (defined $project_filter) {
1077 if (!is_valid_pathname($project_filter)) {
1078 die_error(404, "Invalid project_filter parameter");
1082 our $file_name = $input_params{'file_name'};
1083 if (defined $file_name) {
1084 if (!is_valid_pathname($file_name)) {
1085 die_error(400, "Invalid file parameter");
1089 our $file_parent = $input_params{'file_parent'};
1090 if (defined $file_parent) {
1091 if (!is_valid_pathname($file_parent)) {
1092 die_error(400, "Invalid file parent parameter");
1096 # parameters which are refnames
1097 our $hash = $input_params{'hash'};
1098 if (defined $hash) {
1099 if (!is_valid_refname($hash)) {
1100 die_error(400, "Invalid hash parameter");
1104 our $hash_parent = $input_params{'hash_parent'};
1105 if (defined $hash_parent) {
1106 if (!is_valid_refname($hash_parent)) {
1107 die_error(400, "Invalid hash parent parameter");
1111 our $hash_base = $input_params{'hash_base'};
1112 if (defined $hash_base) {
1113 if (!is_valid_refname($hash_base)) {
1114 die_error(400, "Invalid hash base parameter");
1118 our @extra_options = @{$input_params{'extra_options'}};
1119 # @extra_options is always defined, since it can only be (currently) set from
1120 # CGI, and $cgi->param() returns the empty array in array context if the param
1121 # is not set
1122 foreach my $opt (@extra_options) {
1123 if (not exists $allowed_options{$opt}) {
1124 die_error(400, "Invalid option parameter");
1126 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1127 die_error(400, "Invalid option parameter for this action");
1131 our $hash_parent_base = $input_params{'hash_parent_base'};
1132 if (defined $hash_parent_base) {
1133 if (!is_valid_refname($hash_parent_base)) {
1134 die_error(400, "Invalid hash parent base parameter");
1138 # other parameters
1139 our $page = $input_params{'page'};
1140 if (defined $page) {
1141 if ($page =~ m/[^0-9]/) {
1142 die_error(400, "Invalid page parameter");
1146 our $searchtype = $input_params{'searchtype'};
1147 if (defined $searchtype) {
1148 if ($searchtype =~ m/[^a-z]/) {
1149 die_error(400, "Invalid searchtype parameter");
1153 our $search_use_regexp = $input_params{'search_use_regexp'};
1155 our $searchtext = $input_params{'searchtext'};
1156 our $search_regexp = undef;
1157 if (defined $searchtext) {
1158 if (length($searchtext) < 2) {
1159 die_error(403, "At least two characters are required for search parameter");
1161 if ($search_use_regexp) {
1162 $search_regexp = $searchtext;
1163 if (!eval { qr/$search_regexp/; 1; }) {
1164 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1165 die_error(400, "Invalid search regexp '$search_regexp'",
1166 esc_html($error));
1168 } else {
1169 $search_regexp = quotemeta $searchtext;
1174 # path to the current git repository
1175 our $git_dir;
1176 sub evaluate_git_dir {
1177 our $git_dir = "$projectroot/$project" if $project;
1180 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1181 sub configure_gitweb_features {
1182 # list of supported snapshot formats
1183 our @snapshot_fmts = gitweb_get_feature('snapshot');
1184 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1186 # check that the avatar feature is set to a known provider name,
1187 # and for each provider check if the dependencies are satisfied.
1188 # if the provider name is invalid or the dependencies are not met,
1189 # reset $git_avatar to the empty string.
1190 our ($git_avatar) = gitweb_get_feature('avatar');
1191 if ($git_avatar eq 'gravatar') {
1192 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1193 } elsif ($git_avatar eq 'picon') {
1194 # no dependencies
1195 } else {
1196 $git_avatar = '';
1199 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1200 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1203 sub get_branch_refs {
1204 return ('heads', @extra_branch_refs);
1207 # custom error handler: 'die <message>' is Internal Server Error
1208 sub handle_errors_html {
1209 my $msg = shift; # it is already HTML escaped
1211 # to avoid infinite loop where error occurs in die_error,
1212 # change handler to default handler, disabling handle_errors_html
1213 set_message("Error occurred when inside die_error:\n$msg");
1215 # you cannot jump out of die_error when called as error handler;
1216 # the subroutine set via CGI::Carp::set_message is called _after_
1217 # HTTP headers are already written, so it cannot write them itself
1218 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1220 set_message(\&handle_errors_html);
1222 # dispatch
1223 sub dispatch {
1224 if (!defined $action) {
1225 if (defined $hash) {
1226 $action = git_get_type($hash);
1227 $action or die_error(404, "Object does not exist");
1228 } elsif (defined $hash_base && defined $file_name) {
1229 $action = git_get_type("$hash_base:$file_name");
1230 $action or die_error(404, "File or directory does not exist");
1231 } elsif (defined $project) {
1232 $action = 'summary';
1233 } else {
1234 $action = 'project_list';
1237 if (!defined($actions{$action})) {
1238 die_error(400, "Unknown action");
1240 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1241 !$project) {
1242 die_error(400, "Project needed");
1244 $actions{$action}->();
1247 sub reset_timer {
1248 our $t0 = [ gettimeofday() ]
1249 if defined $t0;
1250 our $number_of_git_cmds = 0;
1253 our $first_request = 1;
1254 our $evaluate_uri_force = undef;
1255 sub run_request {
1256 reset_timer();
1258 # Only allow GET and HEAD methods
1259 if (!$ENV{'REQUEST_METHOD'} || ($ENV{'REQUEST_METHOD'} ne 'GET' && $ENV{'REQUEST_METHOD'} ne 'HEAD')) {
1260 print <<EOT;
1261 Status: 405 Method Not Allowed
1262 Content-Type: text/plain
1263 Allow: GET,HEAD
1265 405 Method Not Allowed
1267 return;
1270 evaluate_uri();
1271 &$evaluate_uri_force() if $evaluate_uri_force;
1272 if ($per_request_config) {
1273 if (ref($per_request_config) eq 'CODE') {
1274 $per_request_config->();
1275 } elsif (!$first_request) {
1276 evaluate_gitweb_config();
1279 check_loadavg();
1281 # $projectroot and $projects_list might be set in gitweb config file
1282 $projects_list ||= $projectroot;
1284 evaluate_query_params();
1285 evaluate_path_info();
1286 evaluate_and_validate_params();
1287 evaluate_git_dir();
1289 configure_gitweb_features();
1291 dispatch();
1294 our $is_last_request = sub { 1 };
1295 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1296 our $CGI = 'CGI';
1297 our $cgi;
1298 our $fcgi_mode = 0;
1299 our $fcgi_nproc_active = 0;
1300 sub configure_as_fcgi {
1301 return if $fcgi_mode;
1303 require CGI::Fast;
1304 our $CGI = 'CGI::Fast';
1306 $fcgi_mode = 1;
1307 $first_request = 0;
1308 my $request_number = 0;
1309 # let each child service 100 requests
1310 our $is_last_request = sub { ++$request_number > 100 };
1312 sub evaluate_argv {
1313 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1314 configure_as_fcgi()
1315 if $script_name =~ /\.fcgi$/
1316 or $auto_fcgi && defined fileno STDIN && fileno STDIN == 0 && getsockname(STDIN);
1318 my $nproc_sub = sub {
1319 my ($arg, $val) = @_;
1320 return unless eval { require FCGI::ProcManager; 1; };
1321 $fcgi_nproc_active = 1;
1322 my $proc_manager = FCGI::ProcManager->new({
1323 n_processes => $val,
1325 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1326 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1327 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1329 if (@ARGV) {
1330 require Getopt::Long;
1331 Getopt::Long::GetOptions(
1332 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1333 'nproc|n=i' => $nproc_sub,
1336 if (!$fcgi_nproc_active && defined $ENV{'GITWEB_FCGI_NPROC'} && $ENV{'GITWEB_FCGI_NPROC'} =~ /^\d+$/) {
1337 &$nproc_sub('nproc', $ENV{'GITWEB_FCGI_NPROC'});
1341 sub run {
1342 evaluate_gitweb_config();
1343 evaluate_encoding();
1344 evaluate_git_version();
1345 my ($mu, $hl, $subroutine) = ($my_uri, $home_link, '');
1346 $subroutine .= '$my_uri = $mu;' if defined $my_uri && $my_uri ne '';
1347 $subroutine .= '$home_link = $hl;' if defined $home_link && $home_link ne '';
1348 $evaluate_uri_force = eval "sub {$subroutine}" if $subroutine;
1349 $first_request = 1;
1350 evaluate_argv();
1352 $pre_listen_hook->()
1353 if $pre_listen_hook;
1355 REQUEST:
1356 while ($cgi = $CGI->new()) {
1357 $pre_dispatch_hook->()
1358 if $pre_dispatch_hook;
1360 run_request();
1362 $post_dispatch_hook->()
1363 if $post_dispatch_hook;
1364 $first_request = 0;
1366 last REQUEST if ($is_last_request->());
1369 DONE_GITWEB:
1373 run();
1375 if (defined caller) {
1376 # wrapped in a subroutine processing requests,
1377 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1378 return;
1379 } else {
1380 # pure CGI script, serving single request
1381 exit;
1384 ## ======================================================================
1385 ## action links
1387 # possible values of extra options
1388 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1389 # -replay => 1 - start from a current view (replay with modifications)
1390 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1391 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1392 sub href {
1393 my %params = @_;
1394 # default is to use -absolute url() i.e. $my_uri
1395 my $href = $params{-full} ? $my_url : $my_uri;
1397 # implicit -replay, must be first of implicit params
1398 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1400 $params{'project'} = $project unless exists $params{'project'};
1402 if ($params{-replay}) {
1403 while (my ($name, $symbol) = each %cgi_param_mapping) {
1404 if (!exists $params{$name}) {
1405 $params{$name} = $input_params{$name};
1410 my $use_pathinfo = gitweb_check_feature('pathinfo');
1411 if (defined $params{'project'} &&
1412 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1413 # try to put as many parameters as possible in PATH_INFO:
1414 # - project name
1415 # - action
1416 # - hash_parent or hash_parent_base:/file_parent
1417 # - hash or hash_base:/filename
1418 # - the snapshot_format as an appropriate suffix
1420 # When the script is the root DirectoryIndex for the domain,
1421 # $href here would be something like http://gitweb.example.com/
1422 # Thus, we strip any trailing / from $href, to spare us double
1423 # slashes in the final URL
1424 $href =~ s,/$,,;
1426 # Then add the project name, if present
1427 $href .= "/".esc_path_info($params{'project'});
1428 delete $params{'project'};
1430 # since we destructively absorb parameters, we keep this
1431 # boolean that remembers if we're handling a snapshot
1432 my $is_snapshot = $params{'action'} eq 'snapshot';
1434 # Summary just uses the project path URL, any other action is
1435 # added to the URL
1436 if (defined $params{'action'}) {
1437 $href .= "/".esc_path_info($params{'action'})
1438 unless $params{'action'} eq 'summary';
1439 delete $params{'action'};
1442 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1443 # stripping nonexistent or useless pieces
1444 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1445 || $params{'hash_parent'} || $params{'hash'});
1446 if (defined $params{'hash_base'}) {
1447 if (defined $params{'hash_parent_base'}) {
1448 $href .= esc_path_info($params{'hash_parent_base'});
1449 # skip the file_parent if it's the same as the file_name
1450 if (defined $params{'file_parent'}) {
1451 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1452 delete $params{'file_parent'};
1453 } elsif ($params{'file_parent'} !~ /\.\./) {
1454 $href .= ":/".esc_path_info($params{'file_parent'});
1455 delete $params{'file_parent'};
1458 $href .= "..";
1459 delete $params{'hash_parent'};
1460 delete $params{'hash_parent_base'};
1461 } elsif (defined $params{'hash_parent'}) {
1462 $href .= esc_path_info($params{'hash_parent'}). "..";
1463 delete $params{'hash_parent'};
1466 $href .= esc_path_info($params{'hash_base'});
1467 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1468 $href .= ":/".esc_path_info($params{'file_name'});
1469 delete $params{'file_name'};
1471 delete $params{'hash'};
1472 delete $params{'hash_base'};
1473 } elsif (defined $params{'hash'}) {
1474 $href .= esc_path_info($params{'hash'});
1475 delete $params{'hash'};
1478 # If the action was a snapshot, we can absorb the
1479 # snapshot_format parameter too
1480 if ($is_snapshot) {
1481 my $fmt = $params{'snapshot_format'};
1482 # snapshot_format should always be defined when href()
1483 # is called, but just in case some code forgets, we
1484 # fall back to the default
1485 $fmt ||= $snapshot_fmts[0];
1486 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1487 delete $params{'snapshot_format'};
1491 # now encode the parameters explicitly
1492 my @result = ();
1493 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1494 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1495 if (defined $params{$name}) {
1496 if (ref($params{$name}) eq "ARRAY") {
1497 foreach my $par (@{$params{$name}}) {
1498 push @result, $symbol . "=" . esc_param($par);
1500 } else {
1501 push @result, $symbol . "=" . esc_param($params{$name});
1505 $href .= "?" . join(';', @result) if scalar @result;
1507 # final transformation: trailing spaces must be escaped (URI-encoded)
1508 $href =~ s/(\s+)$/CGI::escape($1)/e;
1510 if ($params{-anchor}) {
1511 $href .= "#".esc_param($params{-anchor});
1514 return $href;
1518 ## ======================================================================
1519 ## validation, quoting/unquoting and escaping
1521 sub is_valid_action {
1522 my $input = shift;
1523 return undef unless exists $actions{$input};
1524 return 1;
1527 sub is_valid_project {
1528 my $input = shift;
1530 return unless defined $input;
1531 if (!is_valid_pathname($input) ||
1532 !(-d "$projectroot/$input") ||
1533 !check_export_ok("$projectroot/$input") ||
1534 ($strict_export && !project_in_list($input))) {
1535 return undef;
1536 } else {
1537 return 1;
1541 sub is_valid_pathname {
1542 my $input = shift;
1544 return undef unless defined $input;
1545 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1546 # at the beginning, at the end, and between slashes.
1547 # also this catches doubled slashes
1548 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1549 return undef;
1551 # no null characters
1552 if ($input =~ m!\0!) {
1553 return undef;
1555 return 1;
1558 sub is_valid_ref_format {
1559 my $input = shift;
1561 return undef unless defined $input;
1562 # restrictions on ref name according to git-check-ref-format
1563 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1564 return undef;
1566 return 1;
1569 sub is_valid_refname {
1570 my $input = shift;
1572 return undef unless defined $input;
1573 # textual hashes are O.K.
1574 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1575 return 1;
1577 # it must be correct pathname
1578 is_valid_pathname($input) or return undef;
1579 # check git-check-ref-format restrictions
1580 is_valid_ref_format($input) or return undef;
1581 return 1;
1584 # decode sequences of octets in utf8 into Perl's internal form,
1585 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1586 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1587 sub to_utf8 {
1588 my $str = shift;
1589 return undef unless defined $str;
1591 if (utf8::is_utf8($str) || utf8::decode($str)) {
1592 return $str;
1593 } else {
1594 return $encode_object->decode($str, Encode::FB_DEFAULT);
1598 # quote unsafe chars, but keep the slash, even when it's not
1599 # correct, but quoted slashes look too horrible in bookmarks
1600 sub esc_param {
1601 my $str = shift;
1602 return undef unless defined $str;
1603 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1604 $str =~ s/ /\+/g;
1605 return $str;
1608 # the quoting rules for path_info fragment are slightly different
1609 sub esc_path_info {
1610 my $str = shift;
1611 return undef unless defined $str;
1613 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1614 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1616 return $str;
1619 # quote unsafe chars in whole URL, so some characters cannot be quoted
1620 sub esc_url {
1621 my $str = shift;
1622 return undef unless defined $str;
1623 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1624 $str =~ s/ /\+/g;
1625 return $str;
1628 # quote unsafe characters in HTML attributes
1629 sub esc_attr {
1631 # for XHTML conformance escaping '"' to '&quot;' is not enough
1632 return esc_html(@_);
1635 # replace invalid utf8 character with SUBSTITUTION sequence
1636 sub esc_html {
1637 my $str = shift;
1638 my %opts = @_;
1640 return undef unless defined $str;
1642 $str = to_utf8($str);
1643 $str = $cgi->escapeHTML($str);
1644 if ($opts{'-nbsp'}) {
1645 $str =~ s/ /&nbsp;/g;
1647 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1648 return $str;
1651 # quote control characters and escape filename to HTML
1652 sub esc_path {
1653 my $str = shift;
1654 my %opts = @_;
1656 return undef unless defined $str;
1658 $str = to_utf8($str);
1659 $str = $cgi->escapeHTML($str);
1660 if ($opts{'-nbsp'}) {
1661 $str =~ s/ /&nbsp;/g;
1663 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1664 return $str;
1667 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1668 sub sanitize {
1669 my $str = shift;
1671 return undef unless defined $str;
1673 $str = to_utf8($str);
1674 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1675 return $str;
1678 # Make control characters "printable", using character escape codes (CEC)
1679 sub quot_cec {
1680 my $cntrl = shift;
1681 my %opts = @_;
1682 my %es = ( # character escape codes, aka escape sequences
1683 "\t" => '\t', # tab (HT)
1684 "\n" => '\n', # line feed (LF)
1685 "\r" => '\r', # carrige return (CR)
1686 "\f" => '\f', # form feed (FF)
1687 "\b" => '\b', # backspace (BS)
1688 "\a" => '\a', # alarm (bell) (BEL)
1689 "\e" => '\e', # escape (ESC)
1690 "\013" => '\v', # vertical tab (VT)
1691 "\000" => '\0', # nul character (NUL)
1693 my $chr = ( (exists $es{$cntrl})
1694 ? $es{$cntrl}
1695 : sprintf('\%2x', ord($cntrl)) );
1696 if ($opts{-nohtml}) {
1697 return $chr;
1698 } else {
1699 return "<span class=\"cntrl\">$chr</span>";
1703 # Alternatively use unicode control pictures codepoints,
1704 # Unicode "printable representation" (PR)
1705 sub quot_upr {
1706 my $cntrl = shift;
1707 my %opts = @_;
1709 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1710 if ($opts{-nohtml}) {
1711 return $chr;
1712 } else {
1713 return "<span class=\"cntrl\">$chr</span>";
1717 # git may return quoted and escaped filenames
1718 sub unquote {
1719 my $str = shift;
1721 sub unq {
1722 my $seq = shift;
1723 my %es = ( # character escape codes, aka escape sequences
1724 't' => "\t", # tab (HT, TAB)
1725 'n' => "\n", # newline (NL)
1726 'r' => "\r", # return (CR)
1727 'f' => "\f", # form feed (FF)
1728 'b' => "\b", # backspace (BS)
1729 'a' => "\a", # alarm (bell) (BEL)
1730 'e' => "\e", # escape (ESC)
1731 'v' => "\013", # vertical tab (VT)
1734 if ($seq =~ m/^[0-7]{1,3}$/) {
1735 # octal char sequence
1736 return chr(oct($seq));
1737 } elsif (exists $es{$seq}) {
1738 # C escape sequence, aka character escape code
1739 return $es{$seq};
1741 # quoted ordinary character
1742 return $seq;
1745 if ($str =~ m/^"(.*)"$/) {
1746 # needs unquoting
1747 $str = $1;
1748 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1750 return $str;
1753 # escape tabs (convert tabs to spaces)
1754 sub untabify {
1755 my $line = shift;
1757 while ((my $pos = index($line, "\t")) != -1) {
1758 if (my $count = (8 - ($pos % 8))) {
1759 my $spaces = ' ' x $count;
1760 $line =~ s/\t/$spaces/;
1764 return $line;
1767 sub project_in_list {
1768 my $project = shift;
1769 my @list = git_get_projects_list();
1770 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1773 ## ----------------------------------------------------------------------
1774 ## HTML aware string manipulation
1776 # Try to chop given string on a word boundary between position
1777 # $len and $len+$add_len. If there is no word boundary there,
1778 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1779 # (marking chopped part) would be longer than given string.
1780 sub chop_str {
1781 my $str = shift;
1782 my $len = shift;
1783 my $add_len = shift || 10;
1784 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1786 # Make sure perl knows it is utf8 encoded so we don't
1787 # cut in the middle of a utf8 multibyte char.
1788 $str = to_utf8($str);
1790 # allow only $len chars, but don't cut a word if it would fit in $add_len
1791 # if it doesn't fit, cut it if it's still longer than the dots we would add
1792 # remove chopped character entities entirely
1794 # when chopping in the middle, distribute $len into left and right part
1795 # return early if chopping wouldn't make string shorter
1796 if ($where eq 'center') {
1797 return $str if ($len + 5 >= length($str)); # filler is length 5
1798 $len = int($len/2);
1799 } else {
1800 return $str if ($len + 4 >= length($str)); # filler is length 4
1803 # regexps: ending and beginning with word part up to $add_len
1804 my $endre = qr/.{$len}\w{0,$add_len}/;
1805 my $begre = qr/\w{0,$add_len}.{$len}/;
1807 if ($where eq 'left') {
1808 $str =~ m/^(.*?)($begre)$/;
1809 my ($lead, $body) = ($1, $2);
1810 if (length($lead) > 4) {
1811 $lead = " ...";
1813 return "$lead$body";
1815 } elsif ($where eq 'center') {
1816 $str =~ m/^($endre)(.*)$/;
1817 my ($left, $str) = ($1, $2);
1818 $str =~ m/^(.*?)($begre)$/;
1819 my ($mid, $right) = ($1, $2);
1820 if (length($mid) > 5) {
1821 $mid = " ... ";
1823 return "$left$mid$right";
1825 } else {
1826 $str =~ m/^($endre)(.*)$/;
1827 my $body = $1;
1828 my $tail = $2;
1829 if (length($tail) > 4) {
1830 $tail = "... ";
1832 return "$body$tail";
1836 # takes the same arguments as chop_str, but also wraps a <span> around the
1837 # result with a title attribute if it does get chopped. Additionally, the
1838 # string is HTML-escaped.
1839 sub chop_and_escape_str {
1840 my ($str) = @_;
1842 my $chopped = chop_str(@_);
1843 $str = to_utf8($str);
1844 if ($chopped eq $str) {
1845 return esc_html($chopped);
1846 } else {
1847 $str =~ s/[[:cntrl:]]/?/g;
1848 return $cgi->span({-title=>$str}, esc_html($chopped));
1852 # Highlight selected fragments of string, using given CSS class,
1853 # and escape HTML. It is assumed that fragments do not overlap.
1854 # Regions are passed as list of pairs (array references).
1856 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1857 # '<span class="mark">foo</span>bar'
1858 sub esc_html_hl_regions {
1859 my ($str, $css_class, @sel) = @_;
1860 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1861 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1862 return esc_html($str, %opts) unless @sel;
1864 my $out = '';
1865 my $pos = 0;
1867 for my $s (@sel) {
1868 my ($begin, $end) = @$s;
1870 # Don't create empty <span> elements.
1871 next if $end <= $begin;
1873 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1874 %opts);
1876 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1877 if ($begin - $pos > 0);
1878 $out .= $cgi->span({-class => $css_class}, $escaped);
1880 $pos = $end;
1882 $out .= esc_html(substr($str, $pos), %opts)
1883 if ($pos < length($str));
1885 return $out;
1888 # return positions of beginning and end of each match
1889 sub matchpos_list {
1890 my ($str, $regexp) = @_;
1891 return unless (defined $str && defined $regexp);
1893 my @matches;
1894 while ($str =~ /$regexp/g) {
1895 push @matches, [$-[0], $+[0]];
1897 return @matches;
1900 # highlight match (if any), and escape HTML
1901 sub esc_html_match_hl {
1902 my ($str, $regexp) = @_;
1903 return esc_html($str) unless defined $regexp;
1905 my @matches = matchpos_list($str, $regexp);
1906 return esc_html($str) unless @matches;
1908 return esc_html_hl_regions($str, 'match', @matches);
1912 # highlight match (if any) of shortened string, and escape HTML
1913 sub esc_html_match_hl_chopped {
1914 my ($str, $chopped, $regexp) = @_;
1915 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1917 my @matches = matchpos_list($str, $regexp);
1918 return esc_html($chopped) unless @matches;
1920 # filter matches so that we mark chopped string
1921 my $tail = "... "; # see chop_str
1922 unless ($chopped =~ s/\Q$tail\E$//) {
1923 $tail = '';
1925 my $chop_len = length($chopped);
1926 my $tail_len = length($tail);
1927 my @filtered;
1929 for my $m (@matches) {
1930 if ($m->[0] > $chop_len) {
1931 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1932 last;
1933 } elsif ($m->[1] > $chop_len) {
1934 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1935 last;
1937 push @filtered, $m;
1940 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1943 ## ----------------------------------------------------------------------
1944 ## functions returning short strings
1946 # CSS class for given age value (in seconds)
1947 sub age_class {
1948 my $age = shift;
1950 if (!defined $age) {
1951 return "noage";
1952 } elsif ($age < 60*60*2) {
1953 return "age0";
1954 } elsif ($age < 60*60*24*2) {
1955 return "age1";
1956 } else {
1957 return "age2";
1961 # convert age in seconds to "nn units ago" string
1962 sub age_string {
1963 my $age = shift;
1964 my $age_str;
1966 if ($age > 60*60*24*365*2) {
1967 $age_str = (int $age/60/60/24/365);
1968 $age_str .= " years ago";
1969 } elsif ($age > 60*60*24*(365/12)*2) {
1970 $age_str = int $age/60/60/24/(365/12);
1971 $age_str .= " months ago";
1972 } elsif ($age > 60*60*24*7*2) {
1973 $age_str = int $age/60/60/24/7;
1974 $age_str .= " weeks ago";
1975 } elsif ($age > 60*60*24*2) {
1976 $age_str = int $age/60/60/24;
1977 $age_str .= " days ago";
1978 } elsif ($age > 60*60*2) {
1979 $age_str = int $age/60/60;
1980 $age_str .= " hours ago";
1981 } elsif ($age > 60*2) {
1982 $age_str = int $age/60;
1983 $age_str .= " min ago";
1984 } elsif ($age > 2) {
1985 $age_str = int $age;
1986 $age_str .= " sec ago";
1987 } else {
1988 $age_str .= " right now";
1990 return $age_str;
1993 use constant {
1994 S_IFINVALID => 0030000,
1995 S_IFGITLINK => 0160000,
1998 # submodule/subproject, a commit object reference
1999 sub S_ISGITLINK {
2000 my $mode = shift;
2002 return (($mode & S_IFMT) == S_IFGITLINK)
2005 # convert file mode in octal to symbolic file mode string
2006 sub mode_str {
2007 my $mode = oct shift;
2009 if (S_ISGITLINK($mode)) {
2010 return 'm---------';
2011 } elsif (S_ISDIR($mode & S_IFMT)) {
2012 return 'drwxr-xr-x';
2013 } elsif (S_ISLNK($mode)) {
2014 return 'lrwxrwxrwx';
2015 } elsif (S_ISREG($mode)) {
2016 # git cares only about the executable bit
2017 if ($mode & S_IXUSR) {
2018 return '-rwxr-xr-x';
2019 } else {
2020 return '-rw-r--r--';
2022 } else {
2023 return '----------';
2027 # convert file mode in octal to file type string
2028 sub file_type {
2029 my $mode = shift;
2031 if ($mode !~ m/^[0-7]+$/) {
2032 return $mode;
2033 } else {
2034 $mode = oct $mode;
2037 if (S_ISGITLINK($mode)) {
2038 return "submodule";
2039 } elsif (S_ISDIR($mode & S_IFMT)) {
2040 return "directory";
2041 } elsif (S_ISLNK($mode)) {
2042 return "symlink";
2043 } elsif (S_ISREG($mode)) {
2044 return "file";
2045 } else {
2046 return "unknown";
2050 # convert file mode in octal to file type description string
2051 sub file_type_long {
2052 my $mode = shift;
2054 if ($mode !~ m/^[0-7]+$/) {
2055 return $mode;
2056 } else {
2057 $mode = oct $mode;
2060 if (S_ISGITLINK($mode)) {
2061 return "submodule";
2062 } elsif (S_ISDIR($mode & S_IFMT)) {
2063 return "directory";
2064 } elsif (S_ISLNK($mode)) {
2065 return "symlink";
2066 } elsif (S_ISREG($mode)) {
2067 if ($mode & S_IXUSR) {
2068 return "executable";
2069 } else {
2070 return "file";
2072 } else {
2073 return "unknown";
2078 ## ----------------------------------------------------------------------
2079 ## functions returning short HTML fragments, or transforming HTML fragments
2080 ## which don't belong to other sections
2082 # format line of commit message.
2083 sub format_log_line_html {
2084 my $line = shift;
2086 $line = esc_html($line, -nbsp=>1);
2087 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2088 $cgi->a({-href => href(action=>"object", hash=>$1),
2089 -class => "text"}, $1);
2090 }eg;
2092 return $line;
2095 # format marker of refs pointing to given object
2097 # the destination action is chosen based on object type and current context:
2098 # - for annotated tags, we choose the tag view unless it's the current view
2099 # already, in which case we go to shortlog view
2100 # - for other refs, we keep the current view if we're in history, shortlog or
2101 # log view, and select shortlog otherwise
2102 sub format_ref_marker {
2103 my ($refs, $id) = @_;
2104 my $markers = '';
2106 if (defined $refs->{$id}) {
2107 foreach my $ref (@{$refs->{$id}}) {
2108 # this code exploits the fact that non-lightweight tags are the
2109 # only indirect objects, and that they are the only objects for which
2110 # we want to use tag instead of shortlog as action
2111 my ($type, $name) = qw();
2112 my $indirect = ($ref =~ s/\^\{\}$//);
2113 # e.g. tags/v2.6.11 or heads/next
2114 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2115 $type = $1;
2116 $name = $2;
2117 } else {
2118 $type = "ref";
2119 $name = $ref;
2122 my $class = $type;
2123 $class .= " indirect" if $indirect;
2125 my $dest_action = "shortlog";
2127 if ($indirect) {
2128 $dest_action = "tag" unless $action eq "tag";
2129 } elsif ($action =~ /^(history|(short)?log)$/) {
2130 $dest_action = $action;
2133 my $dest = "";
2134 $dest .= "refs/" unless $ref =~ m!^refs/!;
2135 $dest .= $ref;
2137 my $link = $cgi->a({
2138 -href => href(
2139 action=>$dest_action,
2140 hash=>$dest
2141 )}, $name);
2143 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2144 $link . "</span>";
2148 if ($markers) {
2149 return ' <span class="refs">'. $markers . '</span>';
2150 } else {
2151 return "";
2155 # format, perhaps shortened and with markers, title line
2156 sub format_subject_html {
2157 my ($long, $short, $href, $extra) = @_;
2158 $extra = '' unless defined($extra);
2160 if (length($short) < length($long)) {
2161 $long =~ s/[[:cntrl:]]/?/g;
2162 return $cgi->a({-href => $href, -class => "list subject",
2163 -title => to_utf8($long)},
2164 esc_html($short)) . $extra;
2165 } else {
2166 return $cgi->a({-href => $href, -class => "list subject"},
2167 esc_html($long)) . $extra;
2171 # Rather than recomputing the url for an email multiple times, we cache it
2172 # after the first hit. This gives a visible benefit in views where the avatar
2173 # for the same email is used repeatedly (e.g. shortlog).
2174 # The cache is shared by all avatar engines (currently gravatar only), which
2175 # are free to use it as preferred. Since only one avatar engine is used for any
2176 # given page, there's no risk for cache conflicts.
2177 our %avatar_cache = ();
2179 # Compute the picon url for a given email, by using the picon search service over at
2180 # http://www.cs.indiana.edu/picons/search.html
2181 sub picon_url {
2182 my $email = lc shift;
2183 if (!$avatar_cache{$email}) {
2184 my ($user, $domain) = split('@', $email);
2185 $avatar_cache{$email} =
2186 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2187 "$domain/$user/" .
2188 "users+domains+unknown/up/single";
2190 return $avatar_cache{$email};
2193 # Compute the gravatar url for a given email, if it's not in the cache already.
2194 # Gravatar stores only the part of the URL before the size, since that's the
2195 # one computationally more expensive. This also allows reuse of the cache for
2196 # different sizes (for this particular engine).
2197 sub gravatar_url {
2198 my $email = lc shift;
2199 my $size = shift;
2200 $avatar_cache{$email} ||=
2201 "//www.gravatar.com/avatar/" .
2202 Digest::MD5::md5_hex($email) . "?s=";
2203 return $avatar_cache{$email} . $size;
2206 # Insert an avatar for the given $email at the given $size if the feature
2207 # is enabled.
2208 sub git_get_avatar {
2209 my ($email, %opts) = @_;
2210 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2211 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2212 $opts{-size} ||= 'default';
2213 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2214 my $url = "";
2215 if ($git_avatar eq 'gravatar') {
2216 $url = gravatar_url($email, $size);
2217 } elsif ($git_avatar eq 'picon') {
2218 $url = picon_url($email);
2220 # Other providers can be added by extending the if chain, defining $url
2221 # as needed. If no variant puts something in $url, we assume avatars
2222 # are completely disabled/unavailable.
2223 if ($url) {
2224 return $pre_white .
2225 "<img width=\"$size\" " .
2226 "class=\"avatar\" " .
2227 "src=\"".esc_url($url)."\" " .
2228 "alt=\"\" " .
2229 "/>" . $post_white;
2230 } else {
2231 return "";
2235 sub format_search_author {
2236 my ($author, $searchtype, $displaytext) = @_;
2237 my $have_search = gitweb_check_feature('search');
2239 if ($have_search) {
2240 my $performed = "";
2241 if ($searchtype eq 'author') {
2242 $performed = "authored";
2243 } elsif ($searchtype eq 'committer') {
2244 $performed = "committed";
2247 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2248 searchtext=>$author,
2249 searchtype=>$searchtype), class=>"list",
2250 title=>"Search for commits $performed by $author"},
2251 $displaytext);
2253 } else {
2254 return $displaytext;
2258 # format the author name of the given commit with the given tag
2259 # the author name is chopped and escaped according to the other
2260 # optional parameters (see chop_str).
2261 sub format_author_html {
2262 my $tag = shift;
2263 my $co = shift;
2264 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2265 return "<$tag class=\"author\">" .
2266 format_search_author($co->{'author_name'}, "author",
2267 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2268 $author) .
2269 "</$tag>";
2272 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2273 sub format_git_diff_header_line {
2274 my $line = shift;
2275 my $diffinfo = shift;
2276 my ($from, $to) = @_;
2278 if ($diffinfo->{'nparents'}) {
2279 # combined diff
2280 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2281 if ($to->{'href'}) {
2282 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2283 esc_path($to->{'file'}));
2284 } else { # file was deleted (no href)
2285 $line .= esc_path($to->{'file'});
2287 } else {
2288 # "ordinary" diff
2289 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2290 if ($from->{'href'}) {
2291 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2292 'a/' . esc_path($from->{'file'}));
2293 } else { # file was added (no href)
2294 $line .= 'a/' . esc_path($from->{'file'});
2296 $line .= ' ';
2297 if ($to->{'href'}) {
2298 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2299 'b/' . esc_path($to->{'file'}));
2300 } else { # file was deleted
2301 $line .= 'b/' . esc_path($to->{'file'});
2305 return "<div class=\"diff header\">$line</div>\n";
2308 # format extended diff header line, before patch itself
2309 sub format_extended_diff_header_line {
2310 my $line = shift;
2311 my $diffinfo = shift;
2312 my ($from, $to) = @_;
2314 # match <path>
2315 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2316 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2317 esc_path($from->{'file'}));
2319 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2320 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2321 esc_path($to->{'file'}));
2323 # match single <mode>
2324 if ($line =~ m/\s(\d{6})$/) {
2325 $line .= '<span class="info"> (' .
2326 file_type_long($1) .
2327 ')</span>';
2329 # match <hash>
2330 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2331 # can match only for combined diff
2332 $line = 'index ';
2333 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2334 if ($from->{'href'}[$i]) {
2335 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2336 -class=>"hash"},
2337 substr($diffinfo->{'from_id'}[$i],0,7));
2338 } else {
2339 $line .= '0' x 7;
2341 # separator
2342 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2344 $line .= '..';
2345 if ($to->{'href'}) {
2346 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2347 substr($diffinfo->{'to_id'},0,7));
2348 } else {
2349 $line .= '0' x 7;
2352 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2353 # can match only for ordinary diff
2354 my ($from_link, $to_link);
2355 if ($from->{'href'}) {
2356 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2357 substr($diffinfo->{'from_id'},0,7));
2358 } else {
2359 $from_link = '0' x 7;
2361 if ($to->{'href'}) {
2362 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2363 substr($diffinfo->{'to_id'},0,7));
2364 } else {
2365 $to_link = '0' x 7;
2367 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2368 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2371 return $line . "<br/>\n";
2374 # format from-file/to-file diff header
2375 sub format_diff_from_to_header {
2376 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2377 my $line;
2378 my $result = '';
2380 $line = $from_line;
2381 #assert($line =~ m/^---/) if DEBUG;
2382 # no extra formatting for "^--- /dev/null"
2383 if (! $diffinfo->{'nparents'}) {
2384 # ordinary (single parent) diff
2385 if ($line =~ m!^--- "?a/!) {
2386 if ($from->{'href'}) {
2387 $line = '--- a/' .
2388 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2389 esc_path($from->{'file'}));
2390 } else {
2391 $line = '--- a/' .
2392 esc_path($from->{'file'});
2395 $result .= qq!<div class="diff from_file">$line</div>\n!;
2397 } else {
2398 # combined diff (merge commit)
2399 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2400 if ($from->{'href'}[$i]) {
2401 $line = '--- ' .
2402 $cgi->a({-href=>href(action=>"blobdiff",
2403 hash_parent=>$diffinfo->{'from_id'}[$i],
2404 hash_parent_base=>$parents[$i],
2405 file_parent=>$from->{'file'}[$i],
2406 hash=>$diffinfo->{'to_id'},
2407 hash_base=>$hash,
2408 file_name=>$to->{'file'}),
2409 -class=>"path",
2410 -title=>"diff" . ($i+1)},
2411 $i+1) .
2412 '/' .
2413 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2414 esc_path($from->{'file'}[$i]));
2415 } else {
2416 $line = '--- /dev/null';
2418 $result .= qq!<div class="diff from_file">$line</div>\n!;
2422 $line = $to_line;
2423 #assert($line =~ m/^\+\+\+/) if DEBUG;
2424 # no extra formatting for "^+++ /dev/null"
2425 if ($line =~ m!^\+\+\+ "?b/!) {
2426 if ($to->{'href'}) {
2427 $line = '+++ b/' .
2428 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2429 esc_path($to->{'file'}));
2430 } else {
2431 $line = '+++ b/' .
2432 esc_path($to->{'file'});
2435 $result .= qq!<div class="diff to_file">$line</div>\n!;
2437 return $result;
2440 # create note for patch simplified by combined diff
2441 sub format_diff_cc_simplified {
2442 my ($diffinfo, @parents) = @_;
2443 my $result = '';
2445 $result .= "<div class=\"diff header\">" .
2446 "diff --cc ";
2447 if (!is_deleted($diffinfo)) {
2448 $result .= $cgi->a({-href => href(action=>"blob",
2449 hash_base=>$hash,
2450 hash=>$diffinfo->{'to_id'},
2451 file_name=>$diffinfo->{'to_file'}),
2452 -class => "path"},
2453 esc_path($diffinfo->{'to_file'}));
2454 } else {
2455 $result .= esc_path($diffinfo->{'to_file'});
2457 $result .= "</div>\n" . # class="diff header"
2458 "<div class=\"diff nodifferences\">" .
2459 "Simple merge" .
2460 "</div>\n"; # class="diff nodifferences"
2462 return $result;
2465 sub diff_line_class {
2466 my ($line, $from, $to) = @_;
2468 # ordinary diff
2469 my $num_sign = 1;
2470 # combined diff
2471 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2472 $num_sign = scalar @{$from->{'href'}};
2475 my @diff_line_classifier = (
2476 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2477 { regexp => qr/^\\/, class => "incomplete" },
2478 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2479 # classifier for context must come before classifier add/rem,
2480 # or we would have to use more complicated regexp, for example
2481 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2482 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2483 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2485 for my $clsfy (@diff_line_classifier) {
2486 return $clsfy->{'class'}
2487 if ($line =~ $clsfy->{'regexp'});
2490 # fallback
2491 return "";
2494 # assumes that $from and $to are defined and correctly filled,
2495 # and that $line holds a line of chunk header for unified diff
2496 sub format_unidiff_chunk_header {
2497 my ($line, $from, $to) = @_;
2499 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2500 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2502 $from_lines = 0 unless defined $from_lines;
2503 $to_lines = 0 unless defined $to_lines;
2505 if ($from->{'href'}) {
2506 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2507 -class=>"list"}, $from_text);
2509 if ($to->{'href'}) {
2510 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2511 -class=>"list"}, $to_text);
2513 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2514 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2515 return $line;
2518 # assumes that $from and $to are defined and correctly filled,
2519 # and that $line holds a line of chunk header for combined diff
2520 sub format_cc_diff_chunk_header {
2521 my ($line, $from, $to) = @_;
2523 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2524 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2526 @from_text = split(' ', $ranges);
2527 for (my $i = 0; $i < @from_text; ++$i) {
2528 ($from_start[$i], $from_nlines[$i]) =
2529 (split(',', substr($from_text[$i], 1)), 0);
2532 $to_text = pop @from_text;
2533 $to_start = pop @from_start;
2534 $to_nlines = pop @from_nlines;
2536 $line = "<span class=\"chunk_info\">$prefix ";
2537 for (my $i = 0; $i < @from_text; ++$i) {
2538 if ($from->{'href'}[$i]) {
2539 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2540 -class=>"list"}, $from_text[$i]);
2541 } else {
2542 $line .= $from_text[$i];
2544 $line .= " ";
2546 if ($to->{'href'}) {
2547 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2548 -class=>"list"}, $to_text);
2549 } else {
2550 $line .= $to_text;
2552 $line .= " $prefix</span>" .
2553 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2554 return $line;
2557 # process patch (diff) line (not to be used for diff headers),
2558 # returning HTML-formatted (but not wrapped) line.
2559 # If the line is passed as a reference, it is treated as HTML and not
2560 # esc_html()'ed.
2561 sub format_diff_line {
2562 my ($line, $diff_class, $from, $to) = @_;
2564 if (ref($line)) {
2565 $line = $$line;
2566 } else {
2567 chomp $line;
2568 $line = untabify($line);
2570 if ($from && $to && $line =~ m/^\@{2} /) {
2571 $line = format_unidiff_chunk_header($line, $from, $to);
2572 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2573 $line = format_cc_diff_chunk_header($line, $from, $to);
2574 } else {
2575 $line = esc_html($line, -nbsp=>1);
2579 my $diff_classes = "diff";
2580 $diff_classes .= " $diff_class" if ($diff_class);
2581 $line = "<div class=\"$diff_classes\">$line</div>\n";
2583 return $line;
2586 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2587 # linked. Pass the hash of the tree/commit to snapshot.
2588 sub format_snapshot_links {
2589 my ($hash) = @_;
2590 my $num_fmts = @snapshot_fmts;
2591 if ($num_fmts > 1) {
2592 # A parenthesized list of links bearing format names.
2593 # e.g. "snapshot (_tar.gz_ _zip_)"
2594 return "snapshot (" . join(' ', map
2595 $cgi->a({
2596 -href => href(
2597 action=>"snapshot",
2598 hash=>$hash,
2599 snapshot_format=>$_
2601 }, $known_snapshot_formats{$_}{'display'})
2602 , @snapshot_fmts) . ")";
2603 } elsif ($num_fmts == 1) {
2604 # A single "snapshot" link whose tooltip bears the format name.
2605 # i.e. "_snapshot_"
2606 my ($fmt) = @snapshot_fmts;
2607 return
2608 $cgi->a({
2609 -href => href(
2610 action=>"snapshot",
2611 hash=>$hash,
2612 snapshot_format=>$fmt
2614 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2615 }, "snapshot");
2616 } else { # $num_fmts == 0
2617 return undef;
2621 ## ......................................................................
2622 ## functions returning values to be passed, perhaps after some
2623 ## transformation, to other functions; e.g. returning arguments to href()
2625 # returns hash to be passed to href to generate gitweb URL
2626 # in -title key it returns description of link
2627 sub get_feed_info {
2628 my $format = shift || 'Atom';
2629 my %res = (action => lc($format));
2630 my $matched_ref = 0;
2632 # feed links are possible only for project views
2633 return unless (defined $project);
2634 # some views should link to OPML, or to generic project feed,
2635 # or don't have specific feed yet (so they should use generic)
2636 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2638 my $branch = undef;
2639 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2640 # (fullname) to differentiate from tag links; this also makes
2641 # possible to detect branch links
2642 for my $ref (get_branch_refs()) {
2643 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2644 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2645 $branch = $1;
2646 $matched_ref = $ref;
2647 last;
2650 # find log type for feed description (title)
2651 my $type = 'log';
2652 if (defined $file_name) {
2653 $type = "history of $file_name";
2654 $type .= "/" if ($action eq 'tree');
2655 $type .= " on '$branch'" if (defined $branch);
2656 } else {
2657 $type = "log of $branch" if (defined $branch);
2660 $res{-title} = $type;
2661 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2662 $res{'file_name'} = $file_name;
2664 return %res;
2667 ## ----------------------------------------------------------------------
2668 ## git utility subroutines, invoking git commands
2670 # returns path to the core git executable and the --git-dir parameter as list
2671 sub git_cmd {
2672 $number_of_git_cmds++;
2673 return $GIT, '--git-dir='.$git_dir;
2676 # quote the given arguments for passing them to the shell
2677 # quote_command("command", "arg 1", "arg with ' and ! characters")
2678 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2679 # Try to avoid using this function wherever possible.
2680 sub quote_command {
2681 return join(' ',
2682 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2685 # get HEAD ref of given project as hash
2686 sub git_get_head_hash {
2687 return git_get_full_hash(shift, 'HEAD');
2690 sub git_get_full_hash {
2691 return git_get_hash(@_);
2694 sub git_get_short_hash {
2695 return git_get_hash(@_, '--short=7');
2698 sub git_get_hash {
2699 my ($project, $hash, @options) = @_;
2700 my $o_git_dir = $git_dir;
2701 my $retval = undef;
2702 $git_dir = "$projectroot/$project";
2703 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2704 '--verify', '-q', @options, $hash) {
2705 $retval = <$fd>;
2706 chomp $retval if defined $retval;
2707 close $fd;
2709 if (defined $o_git_dir) {
2710 $git_dir = $o_git_dir;
2712 return $retval;
2715 # get type of given object
2716 sub git_get_type {
2717 my $hash = shift;
2719 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2720 my $type = <$fd>;
2721 close $fd or return;
2722 chomp $type;
2723 return $type;
2726 # repository configuration
2727 our $config_file = '';
2728 our %config;
2730 # store multiple values for single key as anonymous array reference
2731 # single values stored directly in the hash, not as [ <value> ]
2732 sub hash_set_multi {
2733 my ($hash, $key, $value) = @_;
2735 if (!exists $hash->{$key}) {
2736 $hash->{$key} = $value;
2737 } elsif (!ref $hash->{$key}) {
2738 $hash->{$key} = [ $hash->{$key}, $value ];
2739 } else {
2740 push @{$hash->{$key}}, $value;
2744 # return hash of git project configuration
2745 # optionally limited to some section, e.g. 'gitweb'
2746 sub git_parse_project_config {
2747 my $section_regexp = shift;
2748 my %config;
2750 local $/ = "\0";
2752 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2753 or return;
2755 while (my $keyval = <$fh>) {
2756 chomp $keyval;
2757 my ($key, $value) = split(/\n/, $keyval, 2);
2759 hash_set_multi(\%config, $key, $value)
2760 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2762 close $fh;
2764 return %config;
2767 # convert config value to boolean: 'true' or 'false'
2768 # no value, number > 0, 'true' and 'yes' values are true
2769 # rest of values are treated as false (never as error)
2770 sub config_to_bool {
2771 my $val = shift;
2773 return 1 if !defined $val; # section.key
2775 # strip leading and trailing whitespace
2776 $val =~ s/^\s+//;
2777 $val =~ s/\s+$//;
2779 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2780 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2783 # convert config value to simple decimal number
2784 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2785 # to be multiplied by 1024, 1048576, or 1073741824
2786 sub config_to_int {
2787 my $val = shift;
2789 # strip leading and trailing whitespace
2790 $val =~ s/^\s+//;
2791 $val =~ s/\s+$//;
2793 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2794 $unit = lc($unit);
2795 # unknown unit is treated as 1
2796 return $num * ($unit eq 'g' ? 1073741824 :
2797 $unit eq 'm' ? 1048576 :
2798 $unit eq 'k' ? 1024 : 1);
2800 return $val;
2803 # convert config value to array reference, if needed
2804 sub config_to_multi {
2805 my $val = shift;
2807 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2810 sub git_get_project_config {
2811 my ($key, $type) = @_;
2813 return unless defined $git_dir;
2815 # key sanity check
2816 return unless ($key);
2817 # only subsection, if exists, is case sensitive,
2818 # and not lowercased by 'git config -z -l'
2819 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2820 $lo =~ s/_//g;
2821 $key = join(".", lc($hi), $mi, lc($lo));
2822 return if ($lo =~ /\W/ || $hi =~ /\W/);
2823 } else {
2824 $key = lc($key);
2825 $key =~ s/_//g;
2826 return if ($key =~ /\W/);
2828 $key =~ s/^gitweb\.//;
2830 # type sanity check
2831 if (defined $type) {
2832 $type =~ s/^--//;
2833 $type = undef
2834 unless ($type eq 'bool' || $type eq 'int');
2837 # get config
2838 if (!defined $config_file ||
2839 $config_file ne "$git_dir/config") {
2840 %config = git_parse_project_config('gitweb');
2841 $config_file = "$git_dir/config";
2844 # check if config variable (key) exists
2845 return unless exists $config{"gitweb.$key"};
2847 # ensure given type
2848 if (!defined $type) {
2849 return $config{"gitweb.$key"};
2850 } elsif ($type eq 'bool') {
2851 # backward compatibility: 'git config --bool' returns true/false
2852 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2853 } elsif ($type eq 'int') {
2854 return config_to_int($config{"gitweb.$key"});
2856 return $config{"gitweb.$key"};
2859 # get hash of given path at given ref
2860 sub git_get_hash_by_path {
2861 my $base = shift;
2862 my $path = shift || return undef;
2863 my $type = shift;
2865 $path =~ s,/+$,,;
2867 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2868 or die_error(500, "Open git-ls-tree failed");
2869 my $line = <$fd>;
2870 close $fd or return undef;
2872 if (!defined $line) {
2873 # there is no tree or hash given by $path at $base
2874 return undef;
2877 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2878 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2879 if (defined $type && $type ne $2) {
2880 # type doesn't match
2881 return undef;
2883 return $3;
2886 # get path of entry with given hash at given tree-ish (ref)
2887 # used to get 'from' filename for combined diff (merge commit) for renames
2888 sub git_get_path_by_hash {
2889 my $base = shift || return;
2890 my $hash = shift || return;
2892 local $/ = "\0";
2894 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2895 or return undef;
2896 while (my $line = <$fd>) {
2897 chomp $line;
2899 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2900 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2901 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2902 close $fd;
2903 return $1;
2906 close $fd;
2907 return undef;
2910 ## ......................................................................
2911 ## git utility functions, directly accessing git repository
2913 # get the value of config variable either from file named as the variable
2914 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2915 # configuration variable in the repository config file.
2916 sub git_get_file_or_project_config {
2917 my ($path, $name) = @_;
2919 $git_dir = "$projectroot/$path";
2920 open my $fd, '<', "$git_dir/$name"
2921 or return git_get_project_config($name);
2922 my $conf = <$fd>;
2923 close $fd;
2924 if (defined $conf) {
2925 chomp $conf;
2927 return $conf;
2930 sub git_get_project_description {
2931 my $path = shift;
2932 return git_get_file_or_project_config($path, 'description');
2935 sub git_get_project_category {
2936 my $path = shift;
2937 return git_get_file_or_project_config($path, 'category');
2941 # supported formats:
2942 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2943 # - if its contents is a number, use it as tag weight,
2944 # - otherwise add a tag with weight 1
2945 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2946 # the same value multiple times increases tag weight
2947 # * `gitweb.ctag' multi-valued repo config variable
2948 sub git_get_project_ctags {
2949 my $project = shift;
2950 my $ctags = {};
2952 $git_dir = "$projectroot/$project";
2953 if (opendir my $dh, "$git_dir/ctags") {
2954 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2955 foreach my $tagfile (@files) {
2956 open my $ct, '<', $tagfile
2957 or next;
2958 my $val = <$ct>;
2959 chomp $val if $val;
2960 close $ct;
2962 (my $ctag = $tagfile) =~ s#.*/##;
2963 if ($val =~ /^\d+$/) {
2964 $ctags->{$ctag} = $val;
2965 } else {
2966 $ctags->{$ctag} = 1;
2969 closedir $dh;
2971 } elsif (open my $fh, '<', "$git_dir/ctags") {
2972 while (my $line = <$fh>) {
2973 chomp $line;
2974 $ctags->{$line}++ if $line;
2976 close $fh;
2978 } else {
2979 my $taglist = config_to_multi(git_get_project_config('ctag'));
2980 foreach my $tag (@$taglist) {
2981 $ctags->{$tag}++;
2985 return $ctags;
2988 # return hash, where keys are content tags ('ctags'),
2989 # and values are sum of weights of given tag in every project
2990 sub git_gather_all_ctags {
2991 my $projects = shift;
2992 my $ctags = {};
2994 foreach my $p (@$projects) {
2995 foreach my $ct (keys %{$p->{'ctags'}}) {
2996 $ctags->{$ct} += $p->{'ctags'}->{$ct};
3000 return $ctags;
3003 sub git_populate_project_tagcloud {
3004 my $ctags = shift;
3006 # First, merge different-cased tags; tags vote on casing
3007 my %ctags_lc;
3008 foreach (keys %$ctags) {
3009 $ctags_lc{lc $_}->{count} += $ctags->{$_};
3010 if (not $ctags_lc{lc $_}->{topcount}
3011 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
3012 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
3013 $ctags_lc{lc $_}->{topname} = $_;
3017 my $cloud;
3018 my $matched = $input_params{'ctag'};
3019 if (eval { require HTML::TagCloud; 1; }) {
3020 $cloud = HTML::TagCloud->new;
3021 foreach my $ctag (sort keys %ctags_lc) {
3022 # Pad the title with spaces so that the cloud looks
3023 # less crammed.
3024 my $title = esc_html($ctags_lc{$ctag}->{topname});
3025 $title =~ s/ /&nbsp;/g;
3026 $title =~ s/^/&nbsp;/g;
3027 $title =~ s/$/&nbsp;/g;
3028 if (defined $matched && $matched eq $ctag) {
3029 $title = qq(<span class="match">$title</span>);
3031 $cloud->add($title, href(project=>undef, ctag=>$ctag),
3032 $ctags_lc{$ctag}->{count});
3034 } else {
3035 $cloud = {};
3036 foreach my $ctag (keys %ctags_lc) {
3037 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3038 if (defined $matched && $matched eq $ctag) {
3039 $title = qq(<span class="match">$title</span>);
3041 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3042 $cloud->{$ctag}{ctag} =
3043 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3046 return $cloud;
3049 sub git_show_project_tagcloud {
3050 my ($cloud, $count) = @_;
3051 if (ref $cloud eq 'HTML::TagCloud') {
3052 return $cloud->html_and_css($count);
3053 } else {
3054 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3055 return
3056 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3057 join (', ', map {
3058 $cloud->{$_}->{'ctag'}
3059 } splice(@tags, 0, $count)) .
3060 '</div>';
3064 sub git_get_project_url_list {
3065 my $path = shift;
3067 $git_dir = "$projectroot/$path";
3068 open my $fd, '<', "$git_dir/cloneurl"
3069 or return wantarray ?
3070 @{ config_to_multi(git_get_project_config('url')) } :
3071 config_to_multi(git_get_project_config('url'));
3072 my @git_project_url_list = map { chomp; $_ } <$fd>;
3073 close $fd;
3075 return wantarray ? @git_project_url_list : \@git_project_url_list;
3078 sub git_get_projects_list {
3079 my $filter = shift || '';
3080 my $paranoid = shift;
3081 my @list;
3083 if (-d $projects_list) {
3084 # search in directory
3085 my $dir = $projects_list;
3086 # remove the trailing "/"
3087 $dir =~ s!/+$!!;
3088 my $pfxlen = length("$dir");
3089 my $pfxdepth = ($dir =~ tr!/!!);
3090 # when filtering, search only given subdirectory
3091 if ($filter && !$paranoid) {
3092 $dir .= "/$filter";
3093 $dir =~ s!/+$!!;
3096 File::Find::find({
3097 follow_fast => 1, # follow symbolic links
3098 follow_skip => 2, # ignore duplicates
3099 dangling_symlinks => 0, # ignore dangling symlinks, silently
3100 wanted => sub {
3101 # global variables
3102 our $project_maxdepth;
3103 our $projectroot;
3104 # skip project-list toplevel, if we get it.
3105 return if (m!^[/.]$!);
3106 # only directories can be git repositories
3107 return unless (-d $_);
3108 # don't traverse too deep (Find is super slow on os x)
3109 # $project_maxdepth excludes depth of $projectroot
3110 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3111 $File::Find::prune = 1;
3112 return;
3115 my $path = substr($File::Find::name, $pfxlen + 1);
3116 # paranoidly only filter here
3117 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3118 next;
3120 # we check related file in $projectroot
3121 if (check_export_ok("$projectroot/$path")) {
3122 push @list, { path => $path };
3123 $File::Find::prune = 1;
3126 }, "$dir");
3128 } elsif (-f $projects_list) {
3129 # read from file(url-encoded):
3130 # 'git%2Fgit.git Linus+Torvalds'
3131 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3132 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3133 open my $fd, '<', $projects_list or return;
3134 PROJECT:
3135 while (my $line = <$fd>) {
3136 chomp $line;
3137 my ($path, $owner) = split ' ', $line;
3138 $path = unescape($path);
3139 $owner = unescape($owner);
3140 if (!defined $path) {
3141 next;
3143 # if $filter is rpovided, check if $path begins with $filter
3144 if ($filter && $path !~ m!^\Q$filter\E/!) {
3145 next;
3147 if (check_export_ok("$projectroot/$path")) {
3148 my $pr = {
3149 path => $path
3151 if ($owner) {
3152 $pr->{'owner'} = to_utf8($owner);
3154 push @list, $pr;
3157 close $fd;
3159 return @list;
3162 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3163 # as side effects it sets 'forks' field to list of forks for forked projects
3164 sub filter_forks_from_projects_list {
3165 my $projects = shift;
3167 my %trie; # prefix tree of directories (path components)
3168 # generate trie out of those directories that might contain forks
3169 foreach my $pr (@$projects) {
3170 my $path = $pr->{'path'};
3171 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3172 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3173 next unless ($path); # skip '.git' repository: tests, git-instaweb
3174 next unless (-d "$projectroot/$path"); # containing directory exists
3175 $pr->{'forks'} = []; # there can be 0 or more forks of project
3177 # add to trie
3178 my @dirs = split('/', $path);
3179 # walk the trie, until either runs out of components or out of trie
3180 my $ref = \%trie;
3181 while (scalar @dirs &&
3182 exists($ref->{$dirs[0]})) {
3183 $ref = $ref->{shift @dirs};
3185 # create rest of trie structure from rest of components
3186 foreach my $dir (@dirs) {
3187 $ref = $ref->{$dir} = {};
3189 # create end marker, store $pr as a data
3190 $ref->{''} = $pr if (!exists $ref->{''});
3193 # filter out forks, by finding shortest prefix match for paths
3194 my @filtered;
3195 PROJECT:
3196 foreach my $pr (@$projects) {
3197 # trie lookup
3198 my $ref = \%trie;
3199 DIR:
3200 foreach my $dir (split('/', $pr->{'path'})) {
3201 if (exists $ref->{''}) {
3202 # found [shortest] prefix, is a fork - skip it
3203 push @{$ref->{''}{'forks'}}, $pr;
3204 next PROJECT;
3206 if (!exists $ref->{$dir}) {
3207 # not in trie, cannot have prefix, not a fork
3208 push @filtered, $pr;
3209 next PROJECT;
3211 # If the dir is there, we just walk one step down the trie.
3212 $ref = $ref->{$dir};
3214 # we ran out of trie
3215 # (shouldn't happen: it's either no match, or end marker)
3216 push @filtered, $pr;
3219 return @filtered;
3222 # note: fill_project_list_info must be run first,
3223 # for 'descr_long' and 'ctags' to be filled
3224 sub search_projects_list {
3225 my ($projlist, %opts) = @_;
3226 my $tagfilter = $opts{'tagfilter'};
3227 my $search_re = $opts{'search_regexp'};
3229 return @$projlist
3230 unless ($tagfilter || $search_re);
3232 # searching projects require filling to be run before it;
3233 fill_project_list_info($projlist,
3234 $tagfilter ? 'ctags' : (),
3235 $search_re ? ('path', 'descr') : ());
3236 my @projects;
3237 PROJECT:
3238 foreach my $pr (@$projlist) {
3240 if ($tagfilter) {
3241 next unless ref($pr->{'ctags'}) eq 'HASH';
3242 next unless
3243 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3246 if ($search_re) {
3247 next unless
3248 $pr->{'path'} =~ /$search_re/ ||
3249 $pr->{'descr_long'} =~ /$search_re/;
3252 push @projects, $pr;
3255 return @projects;
3258 our $gitweb_project_owner = undef;
3259 sub git_get_project_list_from_file {
3261 return if (defined $gitweb_project_owner);
3263 $gitweb_project_owner = {};
3264 # read from file (url-encoded):
3265 # 'git%2Fgit.git Linus+Torvalds'
3266 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3267 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3268 if (-f $projects_list) {
3269 open(my $fd, '<', $projects_list);
3270 while (my $line = <$fd>) {
3271 chomp $line;
3272 my ($pr, $ow) = split ' ', $line;
3273 $pr = unescape($pr);
3274 $ow = unescape($ow);
3275 $gitweb_project_owner->{$pr} = to_utf8($ow);
3277 close $fd;
3281 sub git_get_project_owner {
3282 my $project = shift;
3283 my $owner;
3285 return undef unless $project;
3286 $git_dir = "$projectroot/$project";
3288 if (!defined $gitweb_project_owner) {
3289 git_get_project_list_from_file();
3292 if (exists $gitweb_project_owner->{$project}) {
3293 $owner = $gitweb_project_owner->{$project};
3295 if (!defined $owner){
3296 $owner = git_get_project_config('owner');
3298 if (!defined $owner) {
3299 $owner = get_file_owner("$git_dir");
3302 return $owner;
3305 sub git_get_last_activity {
3306 my ($path) = @_;
3307 my $fd;
3309 $git_dir = "$projectroot/$path";
3310 open($fd, "-|", git_cmd(), 'for-each-ref',
3311 '--format=%(committer)',
3312 '--sort=-committerdate',
3313 '--count=1',
3314 map { "refs/$_" } get_branch_refs ()) or return;
3315 my $most_recent = <$fd>;
3316 close $fd or return;
3317 if (defined $most_recent &&
3318 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3319 my $timestamp = $1;
3320 my $age = time - $timestamp;
3321 return ($age, age_string($age));
3323 return (undef, undef);
3326 # Implementation note: when a single remote is wanted, we cannot use 'git
3327 # remote show -n' because that command always work (assuming it's a remote URL
3328 # if it's not defined), and we cannot use 'git remote show' because that would
3329 # try to make a network roundtrip. So the only way to find if that particular
3330 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3331 # and when we find what we want.
3332 sub git_get_remotes_list {
3333 my $wanted = shift;
3334 my %remotes = ();
3336 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3337 return unless $fd;
3338 while (my $remote = <$fd>) {
3339 chomp $remote;
3340 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3341 next if $wanted and not $remote eq $wanted;
3342 my ($url, $key) = ($1, $2);
3344 $remotes{$remote} ||= { 'heads' => () };
3345 $remotes{$remote}{$key} = $url;
3347 close $fd or return;
3348 return wantarray ? %remotes : \%remotes;
3351 # Takes a hash of remotes as first parameter and fills it by adding the
3352 # available remote heads for each of the indicated remotes.
3353 sub fill_remote_heads {
3354 my $remotes = shift;
3355 my @heads = map { "remotes/$_" } keys %$remotes;
3356 my @remoteheads = git_get_heads_list(undef, @heads);
3357 foreach my $remote (keys %$remotes) {
3358 $remotes->{$remote}{'heads'} = [ grep {
3359 $_->{'name'} =~ s!^$remote/!!
3360 } @remoteheads ];
3364 sub git_get_references {
3365 my $type = shift || "";
3366 my %refs;
3367 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3368 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3369 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3370 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3371 or return;
3373 while (my $line = <$fd>) {
3374 chomp $line;
3375 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3376 if (defined $refs{$1}) {
3377 push @{$refs{$1}}, $2;
3378 } else {
3379 $refs{$1} = [ $2 ];
3383 close $fd or return;
3384 return \%refs;
3387 sub git_get_rev_name_tags {
3388 my $hash = shift || return undef;
3390 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3391 or return;
3392 my $name_rev = <$fd>;
3393 close $fd;
3395 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3396 return $1;
3397 } else {
3398 # catches also '$hash undefined' output
3399 return undef;
3403 ## ----------------------------------------------------------------------
3404 ## parse to hash functions
3406 sub parse_date {
3407 my $epoch = shift;
3408 my $tz = shift || "-0000";
3410 my %date;
3411 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3412 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3413 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3414 $date{'hour'} = $hour;
3415 $date{'minute'} = $min;
3416 $date{'mday'} = $mday;
3417 $date{'day'} = $days[$wday];
3418 $date{'month'} = $months[$mon];
3419 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3420 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3421 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3422 $mday, $months[$mon], $hour ,$min;
3423 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3424 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3426 my ($tz_sign, $tz_hour, $tz_min) =
3427 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3428 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3429 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3430 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3431 $date{'hour_local'} = $hour;
3432 $date{'minute_local'} = $min;
3433 $date{'tz_local'} = $tz;
3434 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3435 1900+$year, $mon+1, $mday,
3436 $hour, $min, $sec, $tz);
3437 return %date;
3440 sub parse_tag {
3441 my $tag_id = shift;
3442 my %tag;
3443 my @comment;
3445 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3446 $tag{'id'} = $tag_id;
3447 while (my $line = <$fd>) {
3448 chomp $line;
3449 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3450 $tag{'object'} = $1;
3451 } elsif ($line =~ m/^type (.+)$/) {
3452 $tag{'type'} = $1;
3453 } elsif ($line =~ m/^tag (.+)$/) {
3454 $tag{'name'} = $1;
3455 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3456 $tag{'author'} = $1;
3457 $tag{'author_epoch'} = $2;
3458 $tag{'author_tz'} = $3;
3459 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3460 $tag{'author_name'} = $1;
3461 $tag{'author_email'} = $2;
3462 } else {
3463 $tag{'author_name'} = $tag{'author'};
3465 } elsif ($line =~ m/--BEGIN/) {
3466 push @comment, $line;
3467 last;
3468 } elsif ($line eq "") {
3469 last;
3472 push @comment, <$fd>;
3473 $tag{'comment'} = \@comment;
3474 close $fd or return;
3475 if (!defined $tag{'name'}) {
3476 return
3478 return %tag
3481 sub parse_commit_text {
3482 my ($commit_text, $withparents) = @_;
3483 my @commit_lines = split '\n', $commit_text;
3484 my %co;
3486 pop @commit_lines; # Remove '\0'
3488 if (! @commit_lines) {
3489 return;
3492 my $header = shift @commit_lines;
3493 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3494 return;
3496 ($co{'id'}, my @parents) = split ' ', $header;
3497 while (my $line = shift @commit_lines) {
3498 last if $line eq "\n";
3499 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3500 $co{'tree'} = $1;
3501 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3502 push @parents, $1;
3503 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3504 $co{'author'} = to_utf8($1);
3505 $co{'author_epoch'} = $2;
3506 $co{'author_tz'} = $3;
3507 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3508 $co{'author_name'} = $1;
3509 $co{'author_email'} = $2;
3510 } else {
3511 $co{'author_name'} = $co{'author'};
3513 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3514 $co{'committer'} = to_utf8($1);
3515 $co{'committer_epoch'} = $2;
3516 $co{'committer_tz'} = $3;
3517 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3518 $co{'committer_name'} = $1;
3519 $co{'committer_email'} = $2;
3520 } else {
3521 $co{'committer_name'} = $co{'committer'};
3525 if (!defined $co{'tree'}) {
3526 return;
3528 $co{'parents'} = \@parents;
3529 $co{'parent'} = $parents[0];
3531 foreach my $title (@commit_lines) {
3532 $title =~ s/^ //;
3533 if ($title ne "") {
3534 $co{'title'} = chop_str($title, 80, 5);
3535 # remove leading stuff of merges to make the interesting part visible
3536 if (length($title) > 50) {
3537 $title =~ s/^Automatic //;
3538 $title =~ s/^merge (of|with) /Merge ... /i;
3539 if (length($title) > 50) {
3540 $title =~ s/(http|rsync):\/\///;
3542 if (length($title) > 50) {
3543 $title =~ s/(master|www|rsync)\.//;
3545 if (length($title) > 50) {
3546 $title =~ s/kernel.org:?//;
3548 if (length($title) > 50) {
3549 $title =~ s/\/pub\/scm//;
3552 $co{'title_short'} = chop_str($title, 50, 5);
3553 last;
3556 if (! defined $co{'title'} || $co{'title'} eq "") {
3557 $co{'title'} = $co{'title_short'} = '(no commit message)';
3559 # remove added spaces
3560 foreach my $line (@commit_lines) {
3561 $line =~ s/^ //;
3563 $co{'comment'} = \@commit_lines;
3565 my $age = time - $co{'committer_epoch'};
3566 $co{'age'} = $age;
3567 $co{'age_string'} = age_string($age);
3568 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3569 if ($age > 60*60*24*7*2) {
3570 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3571 $co{'age_string_age'} = $co{'age_string'};
3572 } else {
3573 $co{'age_string_date'} = $co{'age_string'};
3574 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3576 return %co;
3579 sub parse_commit {
3580 my ($commit_id) = @_;
3581 my %co;
3583 local $/ = "\0";
3585 open my $fd, "-|", git_cmd(), "rev-list",
3586 "--parents",
3587 "--header",
3588 "--max-count=1",
3589 $commit_id,
3590 "--",
3591 or die_error(500, "Open git-rev-list failed");
3592 %co = parse_commit_text(<$fd>, 1);
3593 close $fd;
3595 return %co;
3598 sub parse_commits {
3599 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3600 my @cos;
3602 $maxcount ||= 1;
3603 $skip ||= 0;
3605 local $/ = "\0";
3607 open my $fd, "-|", git_cmd(), "rev-list",
3608 "--header",
3609 @args,
3610 ("--max-count=" . $maxcount),
3611 ("--skip=" . $skip),
3612 @extra_options,
3613 $commit_id,
3614 "--",
3615 ($filename ? ($filename) : ())
3616 or die_error(500, "Open git-rev-list failed");
3617 while (my $line = <$fd>) {
3618 my %co = parse_commit_text($line);
3619 push @cos, \%co;
3621 close $fd;
3623 return wantarray ? @cos : \@cos;
3626 # parse line of git-diff-tree "raw" output
3627 sub parse_difftree_raw_line {
3628 my $line = shift;
3629 my %res;
3631 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3632 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3633 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3634 $res{'from_mode'} = $1;
3635 $res{'to_mode'} = $2;
3636 $res{'from_id'} = $3;
3637 $res{'to_id'} = $4;
3638 $res{'status'} = $5;
3639 $res{'similarity'} = $6;
3640 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3641 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3642 } else {
3643 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3646 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3647 # combined diff (for merge commit)
3648 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3649 $res{'nparents'} = length($1);
3650 $res{'from_mode'} = [ split(' ', $2) ];
3651 $res{'to_mode'} = pop @{$res{'from_mode'}};
3652 $res{'from_id'} = [ split(' ', $3) ];
3653 $res{'to_id'} = pop @{$res{'from_id'}};
3654 $res{'status'} = [ split('', $4) ];
3655 $res{'to_file'} = unquote($5);
3657 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3658 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3659 $res{'commit'} = $1;
3662 return wantarray ? %res : \%res;
3665 # wrapper: return parsed line of git-diff-tree "raw" output
3666 # (the argument might be raw line, or parsed info)
3667 sub parsed_difftree_line {
3668 my $line_or_ref = shift;
3670 if (ref($line_or_ref) eq "HASH") {
3671 # pre-parsed (or generated by hand)
3672 return $line_or_ref;
3673 } else {
3674 return parse_difftree_raw_line($line_or_ref);
3678 # parse line of git-ls-tree output
3679 sub parse_ls_tree_line {
3680 my $line = shift;
3681 my %opts = @_;
3682 my %res;
3684 if ($opts{'-l'}) {
3685 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3686 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3688 $res{'mode'} = $1;
3689 $res{'type'} = $2;
3690 $res{'hash'} = $3;
3691 $res{'size'} = $4;
3692 if ($opts{'-z'}) {
3693 $res{'name'} = $5;
3694 } else {
3695 $res{'name'} = unquote($5);
3697 } else {
3698 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3699 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3701 $res{'mode'} = $1;
3702 $res{'type'} = $2;
3703 $res{'hash'} = $3;
3704 if ($opts{'-z'}) {
3705 $res{'name'} = $4;
3706 } else {
3707 $res{'name'} = unquote($4);
3711 return wantarray ? %res : \%res;
3714 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3715 sub parse_from_to_diffinfo {
3716 my ($diffinfo, $from, $to, @parents) = @_;
3718 if ($diffinfo->{'nparents'}) {
3719 # combined diff
3720 $from->{'file'} = [];
3721 $from->{'href'} = [];
3722 fill_from_file_info($diffinfo, @parents)
3723 unless exists $diffinfo->{'from_file'};
3724 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3725 $from->{'file'}[$i] =
3726 defined $diffinfo->{'from_file'}[$i] ?
3727 $diffinfo->{'from_file'}[$i] :
3728 $diffinfo->{'to_file'};
3729 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3730 $from->{'href'}[$i] = href(action=>"blob",
3731 hash_base=>$parents[$i],
3732 hash=>$diffinfo->{'from_id'}[$i],
3733 file_name=>$from->{'file'}[$i]);
3734 } else {
3735 $from->{'href'}[$i] = undef;
3738 } else {
3739 # ordinary (not combined) diff
3740 $from->{'file'} = $diffinfo->{'from_file'};
3741 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3742 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3743 hash=>$diffinfo->{'from_id'},
3744 file_name=>$from->{'file'});
3745 } else {
3746 delete $from->{'href'};
3750 $to->{'file'} = $diffinfo->{'to_file'};
3751 if (!is_deleted($diffinfo)) { # file exists in result
3752 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3753 hash=>$diffinfo->{'to_id'},
3754 file_name=>$to->{'file'});
3755 } else {
3756 delete $to->{'href'};
3760 ## ......................................................................
3761 ## parse to array of hashes functions
3763 sub git_get_heads_list {
3764 my ($limit, @classes) = @_;
3765 @classes = get_branch_refs() unless @classes;
3766 my @patterns = map { "refs/$_" } @classes;
3767 my @headslist;
3769 open my $fd, '-|', git_cmd(), 'for-each-ref',
3770 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3771 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3772 @patterns
3773 or return;
3774 while (my $line = <$fd>) {
3775 my %ref_item;
3777 chomp $line;
3778 my ($refinfo, $committerinfo) = split(/\0/, $line);
3779 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3780 my ($committer, $epoch, $tz) =
3781 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3782 $ref_item{'fullname'} = $name;
3783 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3784 $name =~ s!^refs/($strip_refs|remotes)/!!;
3785 $ref_item{'name'} = $name;
3786 # for refs neither in 'heads' nor 'remotes' we want to
3787 # show their ref dir
3788 my $ref_dir = (defined $1) ? $1 : '';
3789 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3790 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3793 $ref_item{'id'} = $hash;
3794 $ref_item{'title'} = $title || '(no commit message)';
3795 $ref_item{'epoch'} = $epoch;
3796 if ($epoch) {
3797 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3798 } else {
3799 $ref_item{'age'} = "unknown";
3802 push @headslist, \%ref_item;
3804 close $fd;
3806 return wantarray ? @headslist : \@headslist;
3809 sub git_get_tags_list {
3810 my $limit = shift;
3811 my @tagslist;
3813 open my $fd, '-|', git_cmd(), 'for-each-ref',
3814 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3815 '--format=%(objectname) %(objecttype) %(refname) '.
3816 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3817 'refs/tags'
3818 or return;
3819 while (my $line = <$fd>) {
3820 my %ref_item;
3822 chomp $line;
3823 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3824 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3825 my ($creator, $epoch, $tz) =
3826 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3827 $ref_item{'fullname'} = $name;
3828 $name =~ s!^refs/tags/!!;
3830 $ref_item{'type'} = $type;
3831 $ref_item{'id'} = $id;
3832 $ref_item{'name'} = $name;
3833 if ($type eq "tag") {
3834 $ref_item{'subject'} = $title;
3835 $ref_item{'reftype'} = $reftype;
3836 $ref_item{'refid'} = $refid;
3837 } else {
3838 $ref_item{'reftype'} = $type;
3839 $ref_item{'refid'} = $id;
3842 if ($type eq "tag" || $type eq "commit") {
3843 $ref_item{'epoch'} = $epoch;
3844 if ($epoch) {
3845 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3846 } else {
3847 $ref_item{'age'} = "unknown";
3851 push @tagslist, \%ref_item;
3853 close $fd;
3855 return wantarray ? @tagslist : \@tagslist;
3858 ## ----------------------------------------------------------------------
3859 ## filesystem-related functions
3861 sub get_file_owner {
3862 my $path = shift;
3864 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3865 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3866 if (!defined $gcos) {
3867 return undef;
3869 my $owner = $gcos;
3870 $owner =~ s/[,;].*$//;
3871 return to_utf8($owner);
3874 # assume that file exists
3875 sub insert_file {
3876 my $filename = shift;
3878 open my $fd, '<', $filename;
3879 print map { to_utf8($_) } <$fd>;
3880 close $fd;
3883 ## ......................................................................
3884 ## mimetype related functions
3886 sub mimetype_guess_file {
3887 my $filename = shift;
3888 my $mimemap = shift;
3889 -r $mimemap or return undef;
3891 my %mimemap;
3892 open(my $mh, '<', $mimemap) or return undef;
3893 while (<$mh>) {
3894 next if m/^#/; # skip comments
3895 my ($mimetype, @exts) = split(/\s+/);
3896 foreach my $ext (@exts) {
3897 $mimemap{$ext} = $mimetype;
3900 close($mh);
3902 $filename =~ /\.([^.]*)$/;
3903 return $mimemap{$1};
3906 sub mimetype_guess {
3907 my $filename = shift;
3908 my $mime;
3909 $filename =~ /\./ or return undef;
3911 if ($mimetypes_file) {
3912 my $file = $mimetypes_file;
3913 if ($file !~ m!^/!) { # if it is relative path
3914 # it is relative to project
3915 $file = "$projectroot/$project/$file";
3917 $mime = mimetype_guess_file($filename, $file);
3919 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3920 return $mime;
3923 sub blob_mimetype {
3924 my $fd = shift;
3925 my $filename = shift;
3927 if ($filename) {
3928 my $mime = mimetype_guess($filename);
3929 $mime and return $mime;
3932 # just in case
3933 return $default_blob_plain_mimetype unless $fd;
3935 if (-T $fd) {
3936 return 'text/plain';
3937 } elsif (! $filename) {
3938 return 'application/octet-stream';
3939 } elsif ($filename =~ m/\.png$/i) {
3940 return 'image/png';
3941 } elsif ($filename =~ m/\.gif$/i) {
3942 return 'image/gif';
3943 } elsif ($filename =~ m/\.jpe?g$/i) {
3944 return 'image/jpeg';
3945 } else {
3946 return 'application/octet-stream';
3950 sub blob_contenttype {
3951 my ($fd, $file_name, $type) = @_;
3953 $type ||= blob_mimetype($fd, $file_name);
3954 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3955 $type .= "; charset=$default_text_plain_charset";
3958 return $type;
3961 # guess file syntax for syntax highlighting; return undef if no highlighting
3962 # the name of syntax can (in the future) depend on syntax highlighter used
3963 sub guess_file_syntax {
3964 my ($highlight, $mimetype, $file_name) = @_;
3965 return undef unless ($highlight && defined $file_name);
3966 my $basename = basename($file_name, '.in');
3967 return $highlight_basename{$basename}
3968 if exists $highlight_basename{$basename};
3970 $basename =~ /\.([^.]*)$/;
3971 my $ext = $1 or return undef;
3972 return $highlight_ext{$ext}
3973 if exists $highlight_ext{$ext};
3975 return undef;
3978 # run highlighter and return FD of its output,
3979 # or return original FD if no highlighting
3980 sub run_highlighter {
3981 my ($fd, $highlight, $syntax) = @_;
3982 return $fd unless ($highlight && defined $syntax);
3984 close $fd;
3985 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3986 quote_command($highlight_bin).
3987 " --replace-tabs=8 --fragment --syntax $syntax |"
3988 or die_error(500, "Couldn't open file or run syntax highlighter");
3989 return $fd;
3992 ## ======================================================================
3993 ## functions printing HTML: header, footer, error page
3995 sub get_page_title {
3996 my $title = to_utf8($site_name);
3998 unless (defined $project) {
3999 if (defined $project_filter) {
4000 $title .= " - projects in '" . esc_path($project_filter) . "'";
4002 return $title;
4004 $title .= " - " . to_utf8($project);
4006 return $title unless (defined $action);
4007 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
4009 return $title unless (defined $file_name);
4010 $title .= " - " . esc_path($file_name);
4011 if ($action eq "tree" && $file_name !~ m|/$|) {
4012 $title .= "/";
4015 return $title;
4018 sub get_content_type_html {
4019 # require explicit support from the UA if we are to send the page as
4020 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4021 # we have to do this because MSIE sometimes globs '*/*', pretending to
4022 # support xhtml+xml but choking when it gets what it asked for.
4023 if (defined $cgi->http('HTTP_ACCEPT') &&
4024 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4025 $cgi->Accept('application/xhtml+xml') != 0) {
4026 return 'application/xhtml+xml';
4027 } else {
4028 return 'text/html';
4032 sub print_feed_meta {
4033 if (defined $project) {
4034 my %href_params = get_feed_info();
4035 if (!exists $href_params{'-title'}) {
4036 $href_params{'-title'} = 'log';
4039 foreach my $format (qw(RSS Atom)) {
4040 my $type = lc($format);
4041 my %link_attr = (
4042 '-rel' => 'alternate',
4043 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4044 '-type' => "application/$type+xml"
4047 $href_params{'extra_options'} = undef;
4048 $href_params{'action'} = $type;
4049 $link_attr{'-href'} = href(%href_params);
4050 print "<link ".
4051 "rel=\"$link_attr{'-rel'}\" ".
4052 "title=\"$link_attr{'-title'}\" ".
4053 "href=\"$link_attr{'-href'}\" ".
4054 "type=\"$link_attr{'-type'}\" ".
4055 "/>\n";
4057 $href_params{'extra_options'} = '--no-merges';
4058 $link_attr{'-href'} = href(%href_params);
4059 $link_attr{'-title'} .= ' (no merges)';
4060 print "<link ".
4061 "rel=\"$link_attr{'-rel'}\" ".
4062 "title=\"$link_attr{'-title'}\" ".
4063 "href=\"$link_attr{'-href'}\" ".
4064 "type=\"$link_attr{'-type'}\" ".
4065 "/>\n";
4068 } else {
4069 printf('<link rel="alternate" title="%s projects list" '.
4070 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4071 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4072 printf('<link rel="alternate" title="%s projects feeds" '.
4073 'href="%s" type="text/x-opml" />'."\n",
4074 esc_attr($site_name), href(project=>undef, action=>"opml"));
4078 sub print_header_links {
4079 my $status = shift;
4081 # print out each stylesheet that exist, providing backwards capability
4082 # for those people who defined $stylesheet in a config file
4083 if (defined $stylesheet) {
4084 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4085 } else {
4086 foreach my $stylesheet (@stylesheets) {
4087 next unless $stylesheet;
4088 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4091 print_feed_meta()
4092 if ($status eq '200 OK');
4093 if (defined $favicon) {
4094 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4098 sub print_nav_breadcrumbs_path {
4099 my $dirprefix = undef;
4100 while (my $part = shift) {
4101 $dirprefix .= "/" if defined $dirprefix;
4102 $dirprefix .= $part;
4103 print $cgi->a({-href => href(project => undef,
4104 project_filter => $dirprefix,
4105 action => "project_list")},
4106 esc_html($part)) . " / ";
4110 sub print_nav_breadcrumbs {
4111 my %opts = @_;
4113 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4114 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4116 if (defined $project) {
4117 my @dirname = split '/', $project;
4118 my $projectbasename = pop @dirname;
4119 print_nav_breadcrumbs_path(@dirname);
4120 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4121 if (defined $action) {
4122 my $action_print = $action ;
4123 if (defined $opts{-action_extra}) {
4124 $action_print = $cgi->a({-href => href(action=>$action)},
4125 $action);
4127 print " / $action_print";
4129 if (defined $opts{-action_extra}) {
4130 print " / $opts{-action_extra}";
4132 print "\n";
4133 } elsif (defined $project_filter) {
4134 print_nav_breadcrumbs_path(split '/', $project_filter);
4138 sub print_search_form {
4139 if (!defined $searchtext) {
4140 $searchtext = "";
4142 my $search_hash;
4143 if (defined $hash_base) {
4144 $search_hash = $hash_base;
4145 } elsif (defined $hash) {
4146 $search_hash = $hash;
4147 } else {
4148 $search_hash = "HEAD";
4150 my $action = $my_uri;
4151 my $use_pathinfo = gitweb_check_feature('pathinfo');
4152 if ($use_pathinfo) {
4153 $action .= "/".esc_url($project);
4155 print $cgi->start_form(-method => "get", -action => $action) .
4156 "<div class=\"search\">\n" .
4157 (!$use_pathinfo &&
4158 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4159 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4160 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4161 $cgi->popup_menu(-name => 'st', -default => 'commit',
4162 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4163 " " . $cgi->a({-href => href(action=>"search_help"),
4164 -title => "search help" }, "?") . " search:\n",
4165 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4166 "<span title=\"Extended regular expression\">" .
4167 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4168 -checked => $search_use_regexp) .
4169 "</span>" .
4170 "</div>" .
4171 $cgi->end_form() . "\n";
4174 sub git_header_html {
4175 my $status = shift || "200 OK";
4176 my $expires = shift;
4177 my %opts = @_;
4179 my $title = get_page_title();
4180 my $content_type = get_content_type_html();
4181 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4182 -status=> $status, -expires => $expires)
4183 unless ($opts{'-no_http_header'});
4184 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4185 print <<EOF;
4186 <?xml version="1.0" encoding="utf-8"?>
4187 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4188 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4189 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4190 <!-- git core binaries version $git_version -->
4191 <head>
4192 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4193 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4194 <meta name="robots" content="index, nofollow"/>
4195 <title>$title</title>
4197 # the stylesheet, favicon etc urls won't work correctly with path_info
4198 # unless we set the appropriate base URL
4199 if ($ENV{'PATH_INFO'}) {
4200 print "<base href=\"".esc_url($base_url)."\" />\n";
4202 print_header_links($status);
4204 if (defined $site_html_head_string) {
4205 print to_utf8($site_html_head_string);
4208 print "</head>\n" .
4209 "<body>\n";
4211 if (defined $site_header && -f $site_header) {
4212 insert_file($site_header);
4215 print "<div class=\"page_header\">\n";
4216 if (defined $logo) {
4217 print $cgi->a({-href => esc_url($logo_url),
4218 -title => $logo_label},
4219 $cgi->img({-src => esc_url($logo),
4220 -width => 72, -height => 27,
4221 -alt => "git",
4222 -class => "logo"}));
4224 print_nav_breadcrumbs(%opts);
4225 print "</div>\n";
4227 my $have_search = gitweb_check_feature('search');
4228 if (defined $project && $have_search) {
4229 print_search_form();
4233 sub git_footer_html {
4234 my $feed_class = 'rss_logo';
4236 print "<div class=\"page_footer\">\n";
4237 if (defined $project) {
4238 my $descr = git_get_project_description($project);
4239 if (defined $descr) {
4240 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4243 my %href_params = get_feed_info();
4244 if (!%href_params) {
4245 $feed_class .= ' generic';
4247 $href_params{'-title'} ||= 'log';
4249 foreach my $format (qw(RSS Atom)) {
4250 $href_params{'action'} = lc($format);
4251 print $cgi->a({-href => href(%href_params),
4252 -title => "$href_params{'-title'} $format feed",
4253 -class => $feed_class}, $format)."\n";
4256 } else {
4257 print $cgi->a({-href => href(project=>undef, action=>"opml",
4258 project_filter => $project_filter),
4259 -class => $feed_class}, "OPML") . " ";
4260 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4261 project_filter => $project_filter),
4262 -class => $feed_class}, "TXT") . "\n";
4264 print "</div>\n"; # class="page_footer"
4266 if (defined $t0 && gitweb_check_feature('timed')) {
4267 print "<div id=\"generating_info\">\n";
4268 print 'This page took '.
4269 '<span id="generating_time" class="time_span">'.
4270 tv_interval($t0, [ gettimeofday() ]).
4271 ' seconds </span>'.
4272 ' and '.
4273 '<span id="generating_cmd">'.
4274 $number_of_git_cmds.
4275 '</span> git commands '.
4276 " to generate.\n";
4277 print "</div>\n"; # class="page_footer"
4280 if (defined $site_footer && -f $site_footer) {
4281 insert_file($site_footer);
4284 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4285 if (defined $action &&
4286 $action eq 'blame_incremental') {
4287 print qq!<script type="text/javascript">\n!.
4288 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4289 qq! "!. href() .qq!");\n!.
4290 qq!</script>\n!;
4291 } else {
4292 my ($jstimezone, $tz_cookie, $datetime_class) =
4293 gitweb_get_feature('javascript-timezone');
4295 print qq!<script type="text/javascript">\n!.
4296 qq!window.onload = function () {\n!;
4297 if (gitweb_check_feature('javascript-actions')) {
4298 print qq! fixLinks();\n!;
4300 if ($jstimezone && $tz_cookie && $datetime_class) {
4301 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4302 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4304 print qq!};\n!.
4305 qq!</script>\n!;
4308 print "</body>\n" .
4309 "</html>";
4312 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4313 # Example: die_error(404, 'Hash not found')
4314 # By convention, use the following status codes (as defined in RFC 2616):
4315 # 400: Invalid or missing CGI parameters, or
4316 # requested object exists but has wrong type.
4317 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4318 # this server or project.
4319 # 404: Requested object/revision/project doesn't exist.
4320 # 500: The server isn't configured properly, or
4321 # an internal error occurred (e.g. failed assertions caused by bugs), or
4322 # an unknown error occurred (e.g. the git binary died unexpectedly).
4323 # 503: The server is currently unavailable (because it is overloaded,
4324 # or down for maintenance). Generally, this is a temporary state.
4325 sub die_error {
4326 my $status = shift || 500;
4327 my $error = esc_html(shift) || "Internal Server Error";
4328 my $extra = shift;
4329 my %opts = @_;
4331 my %http_responses = (
4332 400 => '400 Bad Request',
4333 403 => '403 Forbidden',
4334 404 => '404 Not Found',
4335 500 => '500 Internal Server Error',
4336 503 => '503 Service Unavailable',
4338 git_header_html($http_responses{$status}, undef, %opts);
4339 print <<EOF;
4340 <div class="page_body">
4341 <br /><br />
4342 $status - $error
4343 <br />
4345 if (defined $extra) {
4346 print "<hr />\n" .
4347 "$extra\n";
4349 print "</div>\n";
4351 git_footer_html();
4352 goto DONE_GITWEB
4353 unless ($opts{'-error_handler'});
4356 ## ----------------------------------------------------------------------
4357 ## functions printing or outputting HTML: navigation
4359 sub git_print_page_nav {
4360 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4361 $extra = '' if !defined $extra; # pager or formats
4363 my @navs = qw(summary shortlog log commit commitdiff tree);
4364 if ($suppress) {
4365 @navs = grep { $_ ne $suppress } @navs;
4368 my %arg = map { $_ => {action=>$_} } @navs;
4369 if (defined $head) {
4370 for (qw(commit commitdiff)) {
4371 $arg{$_}{'hash'} = $head;
4373 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4374 for (qw(shortlog log)) {
4375 $arg{$_}{'hash'} = $head;
4380 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4381 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4383 my @actions = gitweb_get_feature('actions');
4384 my %repl = (
4385 '%' => '%',
4386 'n' => $project, # project name
4387 'f' => $git_dir, # project path within filesystem
4388 'h' => $treehead || '', # current hash ('h' parameter)
4389 'b' => $treebase || '', # hash base ('hb' parameter)
4391 while (@actions) {
4392 my ($label, $link, $pos) = splice(@actions,0,3);
4393 # insert
4394 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4395 # munch munch
4396 $link =~ s/%([%nfhb])/$repl{$1}/g;
4397 $arg{$label}{'_href'} = $link;
4400 print "<div class=\"page_nav\">\n" .
4401 (join " | ",
4402 map { $_ eq $current ?
4403 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4404 } @navs);
4405 print "<br/>\n$extra<br/>\n" .
4406 "</div>\n";
4409 # returns a submenu for the nagivation of the refs views (tags, heads,
4410 # remotes) with the current view disabled and the remotes view only
4411 # available if the feature is enabled
4412 sub format_ref_views {
4413 my ($current) = @_;
4414 my @ref_views = qw{tags heads};
4415 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4416 return join " | ", map {
4417 $_ eq $current ? $_ :
4418 $cgi->a({-href => href(action=>$_)}, $_)
4419 } @ref_views
4422 sub format_paging_nav {
4423 my ($action, $page, $has_next_link) = @_;
4424 my $paging_nav;
4427 if ($page > 0) {
4428 $paging_nav .=
4429 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4430 " &sdot; " .
4431 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4432 -accesskey => "p", -title => "Alt-p"}, "prev");
4433 } else {
4434 $paging_nav .= "first &sdot; prev";
4437 if ($has_next_link) {
4438 $paging_nav .= " &sdot; " .
4439 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4440 -accesskey => "n", -title => "Alt-n"}, "next");
4441 } else {
4442 $paging_nav .= " &sdot; next";
4445 return $paging_nav;
4448 ## ......................................................................
4449 ## functions printing or outputting HTML: div
4451 sub git_print_header_div {
4452 my ($action, $title, $hash, $hash_base) = @_;
4453 my %args = ();
4455 $args{'action'} = $action;
4456 $args{'hash'} = $hash if $hash;
4457 $args{'hash_base'} = $hash_base if $hash_base;
4459 print "<div class=\"header\">\n" .
4460 $cgi->a({-href => href(%args), -class => "title"},
4461 $title ? $title : $action) .
4462 "\n</div>\n";
4465 sub format_repo_url {
4466 my ($name, $url) = @_;
4467 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4470 # Group output by placing it in a DIV element and adding a header.
4471 # Options for start_div() can be provided by passing a hash reference as the
4472 # first parameter to the function.
4473 # Options to git_print_header_div() can be provided by passing an array
4474 # reference. This must follow the options to start_div if they are present.
4475 # The content can be a scalar, which is output as-is, a scalar reference, which
4476 # is output after html escaping, an IO handle passed either as *handle or
4477 # *handle{IO}, or a function reference. In the latter case all following
4478 # parameters will be taken as argument to the content function call.
4479 sub git_print_section {
4480 my ($div_args, $header_args, $content);
4481 my $arg = shift;
4482 if (ref($arg) eq 'HASH') {
4483 $div_args = $arg;
4484 $arg = shift;
4486 if (ref($arg) eq 'ARRAY') {
4487 $header_args = $arg;
4488 $arg = shift;
4490 $content = $arg;
4492 print $cgi->start_div($div_args);
4493 git_print_header_div(@$header_args);
4495 if (ref($content) eq 'CODE') {
4496 $content->(@_);
4497 } elsif (ref($content) eq 'SCALAR') {
4498 print esc_html($$content);
4499 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4500 print <$content>;
4501 } elsif (!ref($content) && defined($content)) {
4502 print $content;
4505 print $cgi->end_div;
4508 sub format_timestamp_html {
4509 my $date = shift;
4510 my $strtime = $date->{'rfc2822'};
4512 my (undef, undef, $datetime_class) =
4513 gitweb_get_feature('javascript-timezone');
4514 if ($datetime_class) {
4515 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4518 my $localtime_format = '(%02d:%02d %s)';
4519 if ($date->{'hour_local'} < 6) {
4520 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4522 $strtime .= ' ' .
4523 sprintf($localtime_format,
4524 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4526 return $strtime;
4529 # Outputs the author name and date in long form
4530 sub git_print_authorship {
4531 my $co = shift;
4532 my %opts = @_;
4533 my $tag = $opts{-tag} || 'div';
4534 my $author = $co->{'author_name'};
4536 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4537 print "<$tag class=\"author_date\">" .
4538 format_search_author($author, "author", esc_html($author)) .
4539 " [".format_timestamp_html(\%ad)."]".
4540 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4541 "</$tag>\n";
4544 # Outputs table rows containing the full author or committer information,
4545 # in the format expected for 'commit' view (& similar).
4546 # Parameters are a commit hash reference, followed by the list of people
4547 # to output information for. If the list is empty it defaults to both
4548 # author and committer.
4549 sub git_print_authorship_rows {
4550 my $co = shift;
4551 # too bad we can't use @people = @_ || ('author', 'committer')
4552 my @people = @_;
4553 @people = ('author', 'committer') unless @people;
4554 foreach my $who (@people) {
4555 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4556 print "<tr><td>$who</td><td>" .
4557 format_search_author($co->{"${who}_name"}, $who,
4558 esc_html($co->{"${who}_name"})) . " " .
4559 format_search_author($co->{"${who}_email"}, $who,
4560 esc_html("<" . $co->{"${who}_email"} . ">")) .
4561 "</td><td rowspan=\"2\">" .
4562 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4563 "</td></tr>\n" .
4564 "<tr>" .
4565 "<td></td><td>" .
4566 format_timestamp_html(\%wd) .
4567 "</td>" .
4568 "</tr>\n";
4572 sub git_print_page_path {
4573 my $name = shift;
4574 my $type = shift;
4575 my $hb = shift;
4578 print "<div class=\"page_path\">";
4579 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4580 -title => 'tree root'}, to_utf8("[$project]"));
4581 print " / ";
4582 if (defined $name) {
4583 my @dirname = split '/', $name;
4584 my $basename = pop @dirname;
4585 my $fullname = '';
4587 foreach my $dir (@dirname) {
4588 $fullname .= ($fullname ? '/' : '') . $dir;
4589 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4590 hash_base=>$hb),
4591 -title => $fullname}, esc_path($dir));
4592 print " / ";
4594 if (defined $type && $type eq 'blob') {
4595 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4596 hash_base=>$hb),
4597 -title => $name}, esc_path($basename));
4598 } elsif (defined $type && $type eq 'tree') {
4599 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4600 hash_base=>$hb),
4601 -title => $name}, esc_path($basename));
4602 print " / ";
4603 } else {
4604 print esc_path($basename);
4607 print "<br/></div>\n";
4610 sub git_print_log {
4611 my $log = shift;
4612 my %opts = @_;
4614 if ($opts{'-remove_title'}) {
4615 # remove title, i.e. first line of log
4616 shift @$log;
4618 # remove leading empty lines
4619 while (defined $log->[0] && $log->[0] eq "") {
4620 shift @$log;
4623 # print log
4624 my $skip_blank_line = 0;
4625 foreach my $line (@$log) {
4626 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4627 if (! $opts{'-remove_signoff'}) {
4628 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4629 $skip_blank_line = 1;
4631 next;
4634 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4635 if (! $opts{'-remove_signoff'}) {
4636 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4637 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4638 "</span><br/>\n";
4639 $skip_blank_line = 1;
4641 next;
4644 # print only one empty line
4645 # do not print empty line after signoff
4646 if ($line eq "") {
4647 next if ($skip_blank_line);
4648 $skip_blank_line = 1;
4649 } else {
4650 $skip_blank_line = 0;
4653 print format_log_line_html($line) . "<br/>\n";
4656 if ($opts{'-final_empty_line'}) {
4657 # end with single empty line
4658 print "<br/>\n" unless $skip_blank_line;
4662 # return link target (what link points to)
4663 sub git_get_link_target {
4664 my $hash = shift;
4665 my $link_target;
4667 # read link
4668 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4669 or return;
4671 local $/ = undef;
4672 $link_target = <$fd>;
4674 close $fd
4675 or return;
4677 return $link_target;
4680 # given link target, and the directory (basedir) the link is in,
4681 # return target of link relative to top directory (top tree);
4682 # return undef if it is not possible (including absolute links).
4683 sub normalize_link_target {
4684 my ($link_target, $basedir) = @_;
4686 # absolute symlinks (beginning with '/') cannot be normalized
4687 return if (substr($link_target, 0, 1) eq '/');
4689 # normalize link target to path from top (root) tree (dir)
4690 my $path;
4691 if ($basedir) {
4692 $path = $basedir . '/' . $link_target;
4693 } else {
4694 # we are in top (root) tree (dir)
4695 $path = $link_target;
4698 # remove //, /./, and /../
4699 my @path_parts;
4700 foreach my $part (split('/', $path)) {
4701 # discard '.' and ''
4702 next if (!$part || $part eq '.');
4703 # handle '..'
4704 if ($part eq '..') {
4705 if (@path_parts) {
4706 pop @path_parts;
4707 } else {
4708 # link leads outside repository (outside top dir)
4709 return;
4711 } else {
4712 push @path_parts, $part;
4715 $path = join('/', @path_parts);
4717 return $path;
4720 # print tree entry (row of git_tree), but without encompassing <tr> element
4721 sub git_print_tree_entry {
4722 my ($t, $basedir, $hash_base, $have_blame) = @_;
4724 my %base_key = ();
4725 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4727 # The format of a table row is: mode list link. Where mode is
4728 # the mode of the entry, list is the name of the entry, an href,
4729 # and link is the action links of the entry.
4731 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4732 if (exists $t->{'size'}) {
4733 print "<td class=\"size\">$t->{'size'}</td>\n";
4735 if ($t->{'type'} eq "blob") {
4736 print "<td class=\"list\">" .
4737 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4738 file_name=>"$basedir$t->{'name'}", %base_key),
4739 -class => "list"}, esc_path($t->{'name'}));
4740 if (S_ISLNK(oct $t->{'mode'})) {
4741 my $link_target = git_get_link_target($t->{'hash'});
4742 if ($link_target) {
4743 my $norm_target = normalize_link_target($link_target, $basedir);
4744 if (defined $norm_target) {
4745 print " -> " .
4746 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4747 file_name=>$norm_target),
4748 -title => $norm_target}, esc_path($link_target));
4749 } else {
4750 print " -> " . esc_path($link_target);
4754 print "</td>\n";
4755 print "<td class=\"link\">";
4756 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4757 file_name=>"$basedir$t->{'name'}", %base_key)},
4758 "blob");
4759 if ($have_blame) {
4760 print " | " .
4761 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4762 file_name=>"$basedir$t->{'name'}", %base_key)},
4763 "blame");
4765 if (defined $hash_base) {
4766 print " | " .
4767 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4768 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4769 "history");
4771 print " | " .
4772 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4773 file_name=>"$basedir$t->{'name'}")},
4774 "raw");
4775 print "</td>\n";
4777 } elsif ($t->{'type'} eq "tree") {
4778 print "<td class=\"list\">";
4779 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4780 file_name=>"$basedir$t->{'name'}",
4781 %base_key)},
4782 esc_path($t->{'name'}));
4783 print "</td>\n";
4784 print "<td class=\"link\">";
4785 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4786 file_name=>"$basedir$t->{'name'}",
4787 %base_key)},
4788 "tree");
4789 if (defined $hash_base) {
4790 print " | " .
4791 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4792 file_name=>"$basedir$t->{'name'}")},
4793 "history");
4795 print "</td>\n";
4796 } else {
4797 # unknown object: we can only present history for it
4798 # (this includes 'commit' object, i.e. submodule support)
4799 print "<td class=\"list\">" .
4800 esc_path($t->{'name'}) .
4801 "</td>\n";
4802 print "<td class=\"link\">";
4803 if (defined $hash_base) {
4804 print $cgi->a({-href => href(action=>"history",
4805 hash_base=>$hash_base,
4806 file_name=>"$basedir$t->{'name'}")},
4807 "history");
4809 print "</td>\n";
4813 ## ......................................................................
4814 ## functions printing large fragments of HTML
4816 # get pre-image filenames for merge (combined) diff
4817 sub fill_from_file_info {
4818 my ($diff, @parents) = @_;
4820 $diff->{'from_file'} = [ ];
4821 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4822 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4823 if ($diff->{'status'}[$i] eq 'R' ||
4824 $diff->{'status'}[$i] eq 'C') {
4825 $diff->{'from_file'}[$i] =
4826 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4830 return $diff;
4833 # is current raw difftree line of file deletion
4834 sub is_deleted {
4835 my $diffinfo = shift;
4837 return $diffinfo->{'to_id'} eq ('0' x 40);
4840 # does patch correspond to [previous] difftree raw line
4841 # $diffinfo - hashref of parsed raw diff format
4842 # $patchinfo - hashref of parsed patch diff format
4843 # (the same keys as in $diffinfo)
4844 sub is_patch_split {
4845 my ($diffinfo, $patchinfo) = @_;
4847 return defined $diffinfo && defined $patchinfo
4848 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4852 sub git_difftree_body {
4853 my ($difftree, $hash, @parents) = @_;
4854 my ($parent) = $parents[0];
4855 my $have_blame = gitweb_check_feature('blame');
4856 print "<div class=\"list_head\">\n";
4857 if ($#{$difftree} > 10) {
4858 print(($#{$difftree} + 1) . " files changed:\n");
4860 print "</div>\n";
4862 print "<table class=\"" .
4863 (@parents > 1 ? "combined " : "") .
4864 "diff_tree\">\n";
4866 # header only for combined diff in 'commitdiff' view
4867 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4868 if ($has_header) {
4869 # table header
4870 print "<thead><tr>\n" .
4871 "<th></th><th></th>\n"; # filename, patchN link
4872 for (my $i = 0; $i < @parents; $i++) {
4873 my $par = $parents[$i];
4874 print "<th>" .
4875 $cgi->a({-href => href(action=>"commitdiff",
4876 hash=>$hash, hash_parent=>$par),
4877 -title => 'commitdiff to parent number ' .
4878 ($i+1) . ': ' . substr($par,0,7)},
4879 $i+1) .
4880 "&nbsp;</th>\n";
4882 print "</tr></thead>\n<tbody>\n";
4885 my $alternate = 1;
4886 my $patchno = 0;
4887 foreach my $line (@{$difftree}) {
4888 my $diff = parsed_difftree_line($line);
4890 if ($alternate) {
4891 print "<tr class=\"dark\">\n";
4892 } else {
4893 print "<tr class=\"light\">\n";
4895 $alternate ^= 1;
4897 if (exists $diff->{'nparents'}) { # combined diff
4899 fill_from_file_info($diff, @parents)
4900 unless exists $diff->{'from_file'};
4902 if (!is_deleted($diff)) {
4903 # file exists in the result (child) commit
4904 print "<td>" .
4905 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4906 file_name=>$diff->{'to_file'},
4907 hash_base=>$hash),
4908 -class => "list"}, esc_path($diff->{'to_file'})) .
4909 "</td>\n";
4910 } else {
4911 print "<td>" .
4912 esc_path($diff->{'to_file'}) .
4913 "</td>\n";
4916 if ($action eq 'commitdiff') {
4917 # link to patch
4918 $patchno++;
4919 print "<td class=\"link\">" .
4920 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4921 "patch") .
4922 " | " .
4923 "</td>\n";
4926 my $has_history = 0;
4927 my $not_deleted = 0;
4928 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4929 my $hash_parent = $parents[$i];
4930 my $from_hash = $diff->{'from_id'}[$i];
4931 my $from_path = $diff->{'from_file'}[$i];
4932 my $status = $diff->{'status'}[$i];
4934 $has_history ||= ($status ne 'A');
4935 $not_deleted ||= ($status ne 'D');
4937 if ($status eq 'A') {
4938 print "<td class=\"link\" align=\"right\"> | </td>\n";
4939 } elsif ($status eq 'D') {
4940 print "<td class=\"link\">" .
4941 $cgi->a({-href => href(action=>"blob",
4942 hash_base=>$hash,
4943 hash=>$from_hash,
4944 file_name=>$from_path)},
4945 "blob" . ($i+1)) .
4946 " | </td>\n";
4947 } else {
4948 if ($diff->{'to_id'} eq $from_hash) {
4949 print "<td class=\"link nochange\">";
4950 } else {
4951 print "<td class=\"link\">";
4953 print $cgi->a({-href => href(action=>"blobdiff",
4954 hash=>$diff->{'to_id'},
4955 hash_parent=>$from_hash,
4956 hash_base=>$hash,
4957 hash_parent_base=>$hash_parent,
4958 file_name=>$diff->{'to_file'},
4959 file_parent=>$from_path)},
4960 "diff" . ($i+1)) .
4961 " | </td>\n";
4965 print "<td class=\"link\">";
4966 if ($not_deleted) {
4967 print $cgi->a({-href => href(action=>"blob",
4968 hash=>$diff->{'to_id'},
4969 file_name=>$diff->{'to_file'},
4970 hash_base=>$hash)},
4971 "blob");
4972 print " | " if ($has_history);
4974 if ($has_history) {
4975 print $cgi->a({-href => href(action=>"history",
4976 file_name=>$diff->{'to_file'},
4977 hash_base=>$hash)},
4978 "history");
4980 print "</td>\n";
4982 print "</tr>\n";
4983 next; # instead of 'else' clause, to avoid extra indent
4985 # else ordinary diff
4987 my ($to_mode_oct, $to_mode_str, $to_file_type);
4988 my ($from_mode_oct, $from_mode_str, $from_file_type);
4989 if ($diff->{'to_mode'} ne ('0' x 6)) {
4990 $to_mode_oct = oct $diff->{'to_mode'};
4991 if (S_ISREG($to_mode_oct)) { # only for regular file
4992 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4994 $to_file_type = file_type($diff->{'to_mode'});
4996 if ($diff->{'from_mode'} ne ('0' x 6)) {
4997 $from_mode_oct = oct $diff->{'from_mode'};
4998 if (S_ISREG($from_mode_oct)) { # only for regular file
4999 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5001 $from_file_type = file_type($diff->{'from_mode'});
5004 if ($diff->{'status'} eq "A") { # created
5005 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5006 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5007 $mode_chng .= "]</span>";
5008 print "<td>";
5009 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5010 hash_base=>$hash, file_name=>$diff->{'file'}),
5011 -class => "list"}, esc_path($diff->{'file'}));
5012 print "</td>\n";
5013 print "<td>$mode_chng</td>\n";
5014 print "<td class=\"link\">";
5015 if ($action eq 'commitdiff') {
5016 # link to patch
5017 $patchno++;
5018 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5019 "patch") .
5020 " | ";
5022 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5023 hash_base=>$hash, file_name=>$diff->{'file'})},
5024 "blob");
5025 print "</td>\n";
5027 } elsif ($diff->{'status'} eq "D") { # deleted
5028 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5029 print "<td>";
5030 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5031 hash_base=>$parent, file_name=>$diff->{'file'}),
5032 -class => "list"}, esc_path($diff->{'file'}));
5033 print "</td>\n";
5034 print "<td>$mode_chng</td>\n";
5035 print "<td class=\"link\">";
5036 if ($action eq 'commitdiff') {
5037 # link to patch
5038 $patchno++;
5039 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5040 "patch") .
5041 " | ";
5043 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5044 hash_base=>$parent, file_name=>$diff->{'file'})},
5045 "blob") . " | ";
5046 if ($have_blame) {
5047 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5048 file_name=>$diff->{'file'})},
5049 "blame") . " | ";
5051 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5052 file_name=>$diff->{'file'})},
5053 "history");
5054 print "</td>\n";
5056 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5057 my $mode_chnge = "";
5058 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5059 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5060 if ($from_file_type ne $to_file_type) {
5061 $mode_chnge .= " from $from_file_type to $to_file_type";
5063 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5064 if ($from_mode_str && $to_mode_str) {
5065 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5066 } elsif ($to_mode_str) {
5067 $mode_chnge .= " mode: $to_mode_str";
5070 $mode_chnge .= "]</span>\n";
5072 print "<td>";
5073 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5074 hash_base=>$hash, file_name=>$diff->{'file'}),
5075 -class => "list"}, esc_path($diff->{'file'}));
5076 print "</td>\n";
5077 print "<td>$mode_chnge</td>\n";
5078 print "<td class=\"link\">";
5079 if ($action eq 'commitdiff') {
5080 # link to patch
5081 $patchno++;
5082 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5083 "patch") .
5084 " | ";
5085 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5086 # "commit" view and modified file (not onlu mode changed)
5087 print $cgi->a({-href => href(action=>"blobdiff",
5088 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5089 hash_base=>$hash, hash_parent_base=>$parent,
5090 file_name=>$diff->{'file'})},
5091 "diff") .
5092 " | ";
5094 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5095 hash_base=>$hash, file_name=>$diff->{'file'})},
5096 "blob") . " | ";
5097 if ($have_blame) {
5098 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5099 file_name=>$diff->{'file'})},
5100 "blame") . " | ";
5102 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5103 file_name=>$diff->{'file'})},
5104 "history");
5105 print "</td>\n";
5107 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5108 my %status_name = ('R' => 'moved', 'C' => 'copied');
5109 my $nstatus = $status_name{$diff->{'status'}};
5110 my $mode_chng = "";
5111 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5112 # mode also for directories, so we cannot use $to_mode_str
5113 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5115 print "<td>" .
5116 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5117 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5118 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5119 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5120 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5121 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5122 -class => "list"}, esc_path($diff->{'from_file'})) .
5123 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5124 "<td class=\"link\">";
5125 if ($action eq 'commitdiff') {
5126 # link to patch
5127 $patchno++;
5128 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5129 "patch") .
5130 " | ";
5131 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5132 # "commit" view and modified file (not only pure rename or copy)
5133 print $cgi->a({-href => href(action=>"blobdiff",
5134 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5135 hash_base=>$hash, hash_parent_base=>$parent,
5136 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5137 "diff") .
5138 " | ";
5140 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5141 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5142 "blob") . " | ";
5143 if ($have_blame) {
5144 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5145 file_name=>$diff->{'to_file'})},
5146 "blame") . " | ";
5148 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5149 file_name=>$diff->{'to_file'})},
5150 "history");
5151 print "</td>\n";
5153 } # we should not encounter Unmerged (U) or Unknown (X) status
5154 print "</tr>\n";
5156 print "</tbody>" if $has_header;
5157 print "</table>\n";
5160 # Print context lines and then rem/add lines in a side-by-side manner.
5161 sub print_sidebyside_diff_lines {
5162 my ($ctx, $rem, $add) = @_;
5164 # print context block before add/rem block
5165 if (@$ctx) {
5166 print join '',
5167 '<div class="chunk_block ctx">',
5168 '<div class="old">',
5169 @$ctx,
5170 '</div>',
5171 '<div class="new">',
5172 @$ctx,
5173 '</div>',
5174 '</div>';
5177 if (!@$add) {
5178 # pure removal
5179 print join '',
5180 '<div class="chunk_block rem">',
5181 '<div class="old">',
5182 @$rem,
5183 '</div>',
5184 '</div>';
5185 } elsif (!@$rem) {
5186 # pure addition
5187 print join '',
5188 '<div class="chunk_block add">',
5189 '<div class="new">',
5190 @$add,
5191 '</div>',
5192 '</div>';
5193 } else {
5194 print join '',
5195 '<div class="chunk_block chg">',
5196 '<div class="old">',
5197 @$rem,
5198 '</div>',
5199 '<div class="new">',
5200 @$add,
5201 '</div>',
5202 '</div>';
5206 # Print context lines and then rem/add lines in inline manner.
5207 sub print_inline_diff_lines {
5208 my ($ctx, $rem, $add) = @_;
5210 print @$ctx, @$rem, @$add;
5213 # Format removed and added line, mark changed part and HTML-format them.
5214 # Implementation is based on contrib/diff-highlight
5215 sub format_rem_add_lines_pair {
5216 my ($rem, $add, $num_parents) = @_;
5218 # We need to untabify lines before split()'ing them;
5219 # otherwise offsets would be invalid.
5220 chomp $rem;
5221 chomp $add;
5222 $rem = untabify($rem);
5223 $add = untabify($add);
5225 my @rem = split(//, $rem);
5226 my @add = split(//, $add);
5227 my ($esc_rem, $esc_add);
5228 # Ignore leading +/- characters for each parent.
5229 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5230 my ($prefix_has_nonspace, $suffix_has_nonspace);
5232 my $shorter = (@rem < @add) ? @rem : @add;
5233 while ($prefix_len < $shorter) {
5234 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5236 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5237 $prefix_len++;
5240 while ($prefix_len + $suffix_len < $shorter) {
5241 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5243 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5244 $suffix_len++;
5247 # Mark lines that are different from each other, but have some common
5248 # part that isn't whitespace. If lines are completely different, don't
5249 # mark them because that would make output unreadable, especially if
5250 # diff consists of multiple lines.
5251 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5252 $esc_rem = esc_html_hl_regions($rem, 'marked',
5253 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5254 $esc_add = esc_html_hl_regions($add, 'marked',
5255 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5256 } else {
5257 $esc_rem = esc_html($rem, -nbsp=>1);
5258 $esc_add = esc_html($add, -nbsp=>1);
5261 return format_diff_line(\$esc_rem, 'rem'),
5262 format_diff_line(\$esc_add, 'add');
5265 # HTML-format diff context, removed and added lines.
5266 sub format_ctx_rem_add_lines {
5267 my ($ctx, $rem, $add, $num_parents) = @_;
5268 my (@new_ctx, @new_rem, @new_add);
5269 my $can_highlight = 0;
5270 my $is_combined = ($num_parents > 1);
5272 # Highlight if every removed line has a corresponding added line.
5273 if (@$add > 0 && @$add == @$rem) {
5274 $can_highlight = 1;
5276 # Highlight lines in combined diff only if the chunk contains
5277 # diff between the same version, e.g.
5279 # - a
5280 # - b
5281 # + c
5282 # + d
5284 # Otherwise the highlightling would be confusing.
5285 if ($is_combined) {
5286 for (my $i = 0; $i < @$add; $i++) {
5287 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5288 my $prefix_add = substr($add->[$i], 0, $num_parents);
5290 $prefix_rem =~ s/-/+/g;
5292 if ($prefix_rem ne $prefix_add) {
5293 $can_highlight = 0;
5294 last;
5300 if ($can_highlight) {
5301 for (my $i = 0; $i < @$add; $i++) {
5302 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5303 $rem->[$i], $add->[$i], $num_parents);
5304 push @new_rem, $line_rem;
5305 push @new_add, $line_add;
5307 } else {
5308 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5309 @new_add = map { format_diff_line($_, 'add') } @$add;
5312 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5314 return (\@new_ctx, \@new_rem, \@new_add);
5317 # Print context lines and then rem/add lines.
5318 sub print_diff_lines {
5319 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5320 my $is_combined = $num_parents > 1;
5322 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5323 $num_parents);
5325 if ($diff_style eq 'sidebyside' && !$is_combined) {
5326 print_sidebyside_diff_lines($ctx, $rem, $add);
5327 } else {
5328 # default 'inline' style and unknown styles
5329 print_inline_diff_lines($ctx, $rem, $add);
5333 sub print_diff_chunk {
5334 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5335 my (@ctx, @rem, @add);
5337 # The class of the previous line.
5338 my $prev_class = '';
5340 return unless @chunk;
5342 # incomplete last line might be among removed or added lines,
5343 # or both, or among context lines: find which
5344 for (my $i = 1; $i < @chunk; $i++) {
5345 if ($chunk[$i][0] eq 'incomplete') {
5346 $chunk[$i][0] = $chunk[$i-1][0];
5350 # guardian
5351 push @chunk, ["", ""];
5353 foreach my $line_info (@chunk) {
5354 my ($class, $line) = @$line_info;
5356 # print chunk headers
5357 if ($class && $class eq 'chunk_header') {
5358 print format_diff_line($line, $class, $from, $to);
5359 next;
5362 ## print from accumulator when have some add/rem lines or end
5363 # of chunk (flush context lines), or when have add and rem
5364 # lines and new block is reached (otherwise add/rem lines could
5365 # be reordered)
5366 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5367 (@rem && @add && $class ne $prev_class)) {
5368 print_diff_lines(\@ctx, \@rem, \@add,
5369 $diff_style, $num_parents);
5370 @ctx = @rem = @add = ();
5373 ## adding lines to accumulator
5374 # guardian value
5375 last unless $line;
5376 # rem, add or change
5377 if ($class eq 'rem') {
5378 push @rem, $line;
5379 } elsif ($class eq 'add') {
5380 push @add, $line;
5382 # context line
5383 if ($class eq 'ctx') {
5384 push @ctx, $line;
5387 $prev_class = $class;
5391 sub git_patchset_body {
5392 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5393 my ($hash_parent) = $hash_parents[0];
5395 my $is_combined = (@hash_parents > 1);
5396 my $patch_idx = 0;
5397 my $patch_number = 0;
5398 my $patch_line;
5399 my $diffinfo;
5400 my $to_name;
5401 my (%from, %to);
5402 my @chunk; # for side-by-side diff
5404 print "<div class=\"patchset\">\n";
5406 # skip to first patch
5407 while ($patch_line = <$fd>) {
5408 chomp $patch_line;
5410 last if ($patch_line =~ m/^diff /);
5413 PATCH:
5414 while ($patch_line) {
5416 # parse "git diff" header line
5417 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5418 # $1 is from_name, which we do not use
5419 $to_name = unquote($2);
5420 $to_name =~ s!^b/!!;
5421 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5422 # $1 is 'cc' or 'combined', which we do not use
5423 $to_name = unquote($2);
5424 } else {
5425 $to_name = undef;
5428 # check if current patch belong to current raw line
5429 # and parse raw git-diff line if needed
5430 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5431 # this is continuation of a split patch
5432 print "<div class=\"patch cont\">\n";
5433 } else {
5434 # advance raw git-diff output if needed
5435 $patch_idx++ if defined $diffinfo;
5437 # read and prepare patch information
5438 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5440 # compact combined diff output can have some patches skipped
5441 # find which patch (using pathname of result) we are at now;
5442 if ($is_combined) {
5443 while ($to_name ne $diffinfo->{'to_file'}) {
5444 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5445 format_diff_cc_simplified($diffinfo, @hash_parents) .
5446 "</div>\n"; # class="patch"
5448 $patch_idx++;
5449 $patch_number++;
5451 last if $patch_idx > $#$difftree;
5452 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5456 # modifies %from, %to hashes
5457 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5459 # this is first patch for raw difftree line with $patch_idx index
5460 # we index @$difftree array from 0, but number patches from 1
5461 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5464 # git diff header
5465 #assert($patch_line =~ m/^diff /) if DEBUG;
5466 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5467 $patch_number++;
5468 # print "git diff" header
5469 print format_git_diff_header_line($patch_line, $diffinfo,
5470 \%from, \%to);
5472 # print extended diff header
5473 print "<div class=\"diff extended_header\">\n";
5474 EXTENDED_HEADER:
5475 while ($patch_line = <$fd>) {
5476 chomp $patch_line;
5478 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5480 print format_extended_diff_header_line($patch_line, $diffinfo,
5481 \%from, \%to);
5483 print "</div>\n"; # class="diff extended_header"
5485 # from-file/to-file diff header
5486 if (! $patch_line) {
5487 print "</div>\n"; # class="patch"
5488 last PATCH;
5490 next PATCH if ($patch_line =~ m/^diff /);
5491 #assert($patch_line =~ m/^---/) if DEBUG;
5493 my $last_patch_line = $patch_line;
5494 $patch_line = <$fd>;
5495 chomp $patch_line;
5496 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5498 print format_diff_from_to_header($last_patch_line, $patch_line,
5499 $diffinfo, \%from, \%to,
5500 @hash_parents);
5502 # the patch itself
5503 LINE:
5504 while ($patch_line = <$fd>) {
5505 chomp $patch_line;
5507 next PATCH if ($patch_line =~ m/^diff /);
5509 my $class = diff_line_class($patch_line, \%from, \%to);
5511 if ($class eq 'chunk_header') {
5512 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5513 @chunk = ();
5516 push @chunk, [ $class, $patch_line ];
5519 } continue {
5520 if (@chunk) {
5521 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5522 @chunk = ();
5524 print "</div>\n"; # class="patch"
5527 # for compact combined (--cc) format, with chunk and patch simplification
5528 # the patchset might be empty, but there might be unprocessed raw lines
5529 for (++$patch_idx if $patch_number > 0;
5530 $patch_idx < @$difftree;
5531 ++$patch_idx) {
5532 # read and prepare patch information
5533 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5535 # generate anchor for "patch" links in difftree / whatchanged part
5536 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5537 format_diff_cc_simplified($diffinfo, @hash_parents) .
5538 "</div>\n"; # class="patch"
5540 $patch_number++;
5543 if ($patch_number == 0) {
5544 if (@hash_parents > 1) {
5545 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5546 } else {
5547 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5551 print "</div>\n"; # class="patchset"
5554 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5556 sub git_project_search_form {
5557 my ($searchtext, $search_use_regexp) = @_;
5559 my $limit = '';
5560 if ($project_filter) {
5561 $limit = " in '$project_filter/'";
5564 print "<div class=\"projsearch\">\n";
5565 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5566 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5567 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5568 if (defined $project_filter);
5569 print $cgi->textfield(-name => 's', -value => $searchtext,
5570 -title => "Search project by name and description$limit",
5571 -size => 60) . "\n" .
5572 "<span title=\"Extended regular expression\">" .
5573 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5574 -checked => $search_use_regexp) .
5575 "</span>\n" .
5576 $cgi->submit(-name => 'btnS', -value => 'Search') .
5577 $cgi->end_form() . "\n" .
5578 $cgi->a({-href => href(project => undef, searchtext => undef,
5579 project_filter => $project_filter)},
5580 esc_html("List all projects$limit")) . "<br />\n";
5581 print "</div>\n";
5584 # entry for given @keys needs filling if at least one of keys in list
5585 # is not present in %$project_info
5586 sub project_info_needs_filling {
5587 my ($project_info, @keys) = @_;
5589 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5590 foreach my $key (@keys) {
5591 if (!exists $project_info->{$key}) {
5592 return 1;
5595 return;
5598 # fills project list info (age, description, owner, category, forks, etc.)
5599 # for each project in the list, removing invalid projects from
5600 # returned list, or fill only specified info.
5602 # Invalid projects are removed from the returned list if and only if you
5603 # ask 'age' or 'age_string' to be filled, because they are the only fields
5604 # that run unconditionally git command that requires repository, and
5605 # therefore do always check if project repository is invalid.
5607 # USAGE:
5608 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5609 # ensures that 'descr_long' and 'ctags' fields are filled
5610 # * @project_list = fill_project_list_info(\@project_list)
5611 # ensures that all fields are filled (and invalid projects removed)
5613 # NOTE: modifies $projlist, but does not remove entries from it
5614 sub fill_project_list_info {
5615 my ($projlist, @wanted_keys) = @_;
5616 my @projects;
5617 my $filter_set = sub { return @_; };
5618 if (@wanted_keys) {
5619 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5620 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5623 my $show_ctags = gitweb_check_feature('ctags');
5624 PROJECT:
5625 foreach my $pr (@$projlist) {
5626 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5627 my (@activity) = git_get_last_activity($pr->{'path'});
5628 unless (@activity) {
5629 next PROJECT;
5631 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5633 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5634 my $descr = git_get_project_description($pr->{'path'}) || "";
5635 $descr = to_utf8($descr);
5636 $pr->{'descr_long'} = $descr;
5637 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5639 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5640 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5642 if ($show_ctags &&
5643 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5644 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5646 if ($projects_list_group_categories &&
5647 project_info_needs_filling($pr, $filter_set->('category'))) {
5648 my $cat = git_get_project_category($pr->{'path'}) ||
5649 $project_list_default_category;
5650 $pr->{'category'} = to_utf8($cat);
5653 push @projects, $pr;
5656 return @projects;
5659 sub sort_projects_list {
5660 my ($projlist, $order) = @_;
5662 sub order_str {
5663 my $key = shift;
5664 return sub { $a->{$key} cmp $b->{$key} };
5667 sub order_num_then_undef {
5668 my $key = shift;
5669 return sub {
5670 defined $a->{$key} ?
5671 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5672 (defined $b->{$key} ? 1 : 0)
5676 my %orderings = (
5677 project => order_str('path'),
5678 descr => order_str('descr_long'),
5679 owner => order_str('owner'),
5680 age => order_num_then_undef('age'),
5683 my $ordering = $orderings{$order};
5684 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5687 # returns a hash of categories, containing the list of project
5688 # belonging to each category
5689 sub build_projlist_by_category {
5690 my ($projlist, $from, $to) = @_;
5691 my %categories;
5693 $from = 0 unless defined $from;
5694 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5696 for (my $i = $from; $i <= $to; $i++) {
5697 my $pr = $projlist->[$i];
5698 push @{$categories{ $pr->{'category'} }}, $pr;
5701 return wantarray ? %categories : \%categories;
5704 # print 'sort by' <th> element, generating 'sort by $name' replay link
5705 # if that order is not selected
5706 sub print_sort_th {
5707 print format_sort_th(@_);
5710 sub format_sort_th {
5711 my ($name, $order, $header) = @_;
5712 my $sort_th = "";
5713 $header ||= ucfirst($name);
5715 if ($order eq $name) {
5716 $sort_th .= "<th>$header</th>\n";
5717 } else {
5718 $sort_th .= "<th>" .
5719 $cgi->a({-href => href(-replay=>1, order=>$name),
5720 -class => "header"}, $header) .
5721 "</th>\n";
5724 return $sort_th;
5727 sub git_project_list_rows {
5728 my ($projlist, $from, $to, $check_forks) = @_;
5730 $from = 0 unless defined $from;
5731 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5733 my $alternate = 1;
5734 for (my $i = $from; $i <= $to; $i++) {
5735 my $pr = $projlist->[$i];
5737 if ($alternate) {
5738 print "<tr class=\"dark\">\n";
5739 } else {
5740 print "<tr class=\"light\">\n";
5742 $alternate ^= 1;
5744 if ($check_forks) {
5745 print "<td>";
5746 if ($pr->{'forks'}) {
5747 my $nforks = scalar @{$pr->{'forks'}};
5748 if ($nforks > 0) {
5749 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5750 -title => "$nforks forks"}, "+");
5751 } else {
5752 print $cgi->span({-title => "$nforks forks"}, "+");
5755 print "</td>\n";
5757 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5758 -class => "list"},
5759 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5760 "</td>\n" .
5761 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5762 -class => "list",
5763 -title => $pr->{'descr_long'}},
5764 $search_regexp
5765 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5766 $pr->{'descr'}, $search_regexp)
5767 : esc_html($pr->{'descr'})) .
5768 "</td>\n";
5769 unless ($omit_owner) {
5770 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5772 unless ($omit_age_column) {
5773 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5774 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5776 print"<td class=\"link\">" .
5777 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5778 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5779 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5780 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5781 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5782 "</td>\n" .
5783 "</tr>\n";
5787 sub git_project_list_body {
5788 # actually uses global variable $project
5789 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5790 my @projects = @$projlist;
5792 my $check_forks = gitweb_check_feature('forks');
5793 my $show_ctags = gitweb_check_feature('ctags');
5794 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5795 $check_forks = undef
5796 if ($tagfilter || $search_regexp);
5798 # filtering out forks before filling info allows to do less work
5799 @projects = filter_forks_from_projects_list(\@projects)
5800 if ($check_forks);
5801 # search_projects_list pre-fills required info
5802 @projects = search_projects_list(\@projects,
5803 'search_regexp' => $search_regexp,
5804 'tagfilter' => $tagfilter)
5805 if ($tagfilter || $search_regexp);
5806 # fill the rest
5807 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5808 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5809 push @all_fields, 'owner' unless($omit_owner);
5810 @projects = fill_project_list_info(\@projects, @all_fields);
5812 $order ||= $default_projects_order;
5813 $from = 0 unless defined $from;
5814 $to = $#projects if (!defined $to || $#projects < $to);
5816 # short circuit
5817 if ($from > $to) {
5818 print "<center>\n".
5819 "<b>No such projects found</b><br />\n".
5820 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5821 "</center>\n<br />\n";
5822 return;
5825 @projects = sort_projects_list(\@projects, $order);
5827 if ($show_ctags) {
5828 my $ctags = git_gather_all_ctags(\@projects);
5829 my $cloud = git_populate_project_tagcloud($ctags);
5830 print git_show_project_tagcloud($cloud, 64);
5833 print "<table class=\"project_list\">\n";
5834 unless ($no_header) {
5835 print "<tr>\n";
5836 if ($check_forks) {
5837 print "<th></th>\n";
5839 print_sort_th('project', $order, 'Project');
5840 print_sort_th('descr', $order, 'Description');
5841 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5842 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5843 print "<th></th>\n" . # for links
5844 "</tr>\n";
5847 if ($projects_list_group_categories) {
5848 # only display categories with projects in the $from-$to window
5849 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5850 my %categories = build_projlist_by_category(\@projects, $from, $to);
5851 foreach my $cat (sort keys %categories) {
5852 unless ($cat eq "") {
5853 print "<tr>\n";
5854 if ($check_forks) {
5855 print "<td></td>\n";
5857 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5858 print "</tr>\n";
5861 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5863 } else {
5864 git_project_list_rows(\@projects, $from, $to, $check_forks);
5867 if (defined $extra) {
5868 print "<tr>\n";
5869 if ($check_forks) {
5870 print "<td></td>\n";
5872 print "<td colspan=\"5\">$extra</td>\n" .
5873 "</tr>\n";
5875 print "</table>\n";
5878 sub git_log_body {
5879 # uses global variable $project
5880 my ($commitlist, $from, $to, $refs, $extra) = @_;
5882 $from = 0 unless defined $from;
5883 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5885 for (my $i = 0; $i <= $to; $i++) {
5886 my %co = %{$commitlist->[$i]};
5887 next if !%co;
5888 my $commit = $co{'id'};
5889 my $ref = format_ref_marker($refs, $commit);
5890 git_print_header_div('commit',
5891 "<span class=\"age\">$co{'age_string'}</span>" .
5892 esc_html($co{'title'}) . $ref,
5893 $commit);
5894 print "<div class=\"title_text\">\n" .
5895 "<div class=\"log_link\">\n" .
5896 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5897 " | " .
5898 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5899 " | " .
5900 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5901 "<br/>\n" .
5902 "</div>\n";
5903 git_print_authorship(\%co, -tag => 'span');
5904 print "<br/>\n</div>\n";
5906 print "<div class=\"log_body\">\n";
5907 git_print_log($co{'comment'}, -final_empty_line=> 1);
5908 print "</div>\n";
5910 if ($extra) {
5911 print "<div class=\"page_nav\">\n";
5912 print "$extra\n";
5913 print "</div>\n";
5917 sub git_shortlog_body {
5918 # uses global variable $project
5919 my ($commitlist, $from, $to, $refs, $extra) = @_;
5921 $from = 0 unless defined $from;
5922 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5924 print "<table class=\"shortlog\">\n";
5925 my $alternate = 1;
5926 for (my $i = $from; $i <= $to; $i++) {
5927 my %co = %{$commitlist->[$i]};
5928 my $commit = $co{'id'};
5929 my $ref = format_ref_marker($refs, $commit);
5930 if ($alternate) {
5931 print "<tr class=\"dark\">\n";
5932 } else {
5933 print "<tr class=\"light\">\n";
5935 $alternate ^= 1;
5936 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5937 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5938 format_author_html('td', \%co, 10) . "<td>";
5939 print format_subject_html($co{'title'}, $co{'title_short'},
5940 href(action=>"commit", hash=>$commit), $ref);
5941 print "</td>\n" .
5942 "<td class=\"link\">" .
5943 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5944 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5945 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5946 my $snapshot_links = format_snapshot_links($commit);
5947 if (defined $snapshot_links) {
5948 print " | " . $snapshot_links;
5950 print "</td>\n" .
5951 "</tr>\n";
5953 if (defined $extra) {
5954 print "<tr>\n" .
5955 "<td colspan=\"4\">$extra</td>\n" .
5956 "</tr>\n";
5958 print "</table>\n";
5961 sub git_history_body {
5962 # Warning: assumes constant type (blob or tree) during history
5963 my ($commitlist, $from, $to, $refs, $extra,
5964 $file_name, $file_hash, $ftype) = @_;
5966 $from = 0 unless defined $from;
5967 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5969 print "<table class=\"history\">\n";
5970 my $alternate = 1;
5971 for (my $i = $from; $i <= $to; $i++) {
5972 my %co = %{$commitlist->[$i]};
5973 if (!%co) {
5974 next;
5976 my $commit = $co{'id'};
5978 my $ref = format_ref_marker($refs, $commit);
5980 if ($alternate) {
5981 print "<tr class=\"dark\">\n";
5982 } else {
5983 print "<tr class=\"light\">\n";
5985 $alternate ^= 1;
5986 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5987 # shortlog: format_author_html('td', \%co, 10)
5988 format_author_html('td', \%co, 15, 3) . "<td>";
5989 # originally git_history used chop_str($co{'title'}, 50)
5990 print format_subject_html($co{'title'}, $co{'title_short'},
5991 href(action=>"commit", hash=>$commit), $ref);
5992 print "</td>\n" .
5993 "<td class=\"link\">" .
5994 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5995 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5997 if ($ftype eq 'blob') {
5998 my $blob_current = $file_hash;
5999 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6000 if (defined $blob_current && defined $blob_parent &&
6001 $blob_current ne $blob_parent) {
6002 print " | " .
6003 $cgi->a({-href => href(action=>"blobdiff",
6004 hash=>$blob_current, hash_parent=>$blob_parent,
6005 hash_base=>$hash_base, hash_parent_base=>$commit,
6006 file_name=>$file_name)},
6007 "diff to current");
6010 print "</td>\n" .
6011 "</tr>\n";
6013 if (defined $extra) {
6014 print "<tr>\n" .
6015 "<td colspan=\"4\">$extra</td>\n" .
6016 "</tr>\n";
6018 print "</table>\n";
6021 sub git_tags_body {
6022 # uses global variable $project
6023 my ($taglist, $from, $to, $extra) = @_;
6024 $from = 0 unless defined $from;
6025 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6027 print "<table class=\"tags\">\n";
6028 my $alternate = 1;
6029 for (my $i = $from; $i <= $to; $i++) {
6030 my $entry = $taglist->[$i];
6031 my %tag = %$entry;
6032 my $comment = $tag{'subject'};
6033 my $comment_short;
6034 if (defined $comment) {
6035 $comment_short = chop_str($comment, 30, 5);
6037 if ($alternate) {
6038 print "<tr class=\"dark\">\n";
6039 } else {
6040 print "<tr class=\"light\">\n";
6042 $alternate ^= 1;
6043 if (defined $tag{'age'}) {
6044 print "<td><i>$tag{'age'}</i></td>\n";
6045 } else {
6046 print "<td></td>\n";
6048 print "<td>" .
6049 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6050 -class => "list name"}, esc_html($tag{'name'})) .
6051 "</td>\n" .
6052 "<td>";
6053 if (defined $comment) {
6054 print format_subject_html($comment, $comment_short,
6055 href(action=>"tag", hash=>$tag{'id'}));
6057 print "</td>\n" .
6058 "<td class=\"selflink\">";
6059 if ($tag{'type'} eq "tag") {
6060 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6061 } else {
6062 print "&nbsp;";
6064 print "</td>\n" .
6065 "<td class=\"link\">" . " | " .
6066 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6067 if ($tag{'reftype'} eq "commit") {
6068 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6069 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6070 } elsif ($tag{'reftype'} eq "blob") {
6071 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6073 print "</td>\n" .
6074 "</tr>";
6076 if (defined $extra) {
6077 print "<tr>\n" .
6078 "<td colspan=\"5\">$extra</td>\n" .
6079 "</tr>\n";
6081 print "</table>\n";
6084 sub git_heads_body {
6085 # uses global variable $project
6086 my ($headlist, $head_at, $from, $to, $extra) = @_;
6087 $from = 0 unless defined $from;
6088 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6090 print "<table class=\"heads\">\n";
6091 my $alternate = 1;
6092 for (my $i = $from; $i <= $to; $i++) {
6093 my $entry = $headlist->[$i];
6094 my %ref = %$entry;
6095 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6096 if ($alternate) {
6097 print "<tr class=\"dark\">\n";
6098 } else {
6099 print "<tr class=\"light\">\n";
6101 $alternate ^= 1;
6102 print "<td><i>$ref{'age'}</i></td>\n" .
6103 ($curr ? "<td class=\"current_head\">" : "<td>") .
6104 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6105 -class => "list name"},esc_html($ref{'name'})) .
6106 "</td>\n" .
6107 "<td class=\"link\">" .
6108 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6109 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6110 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6111 "</td>\n" .
6112 "</tr>";
6114 if (defined $extra) {
6115 print "<tr>\n" .
6116 "<td colspan=\"3\">$extra</td>\n" .
6117 "</tr>\n";
6119 print "</table>\n";
6122 # Display a single remote block
6123 sub git_remote_block {
6124 my ($remote, $rdata, $limit, $head) = @_;
6126 my $heads = $rdata->{'heads'};
6127 my $fetch = $rdata->{'fetch'};
6128 my $push = $rdata->{'push'};
6130 my $urls_table = "<table class=\"projects_list\">\n" ;
6132 if (defined $fetch) {
6133 if ($fetch eq $push) {
6134 $urls_table .= format_repo_url("URL", $fetch);
6135 } else {
6136 $urls_table .= format_repo_url("Fetch URL", $fetch);
6137 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6139 } elsif (defined $push) {
6140 $urls_table .= format_repo_url("Push URL", $push);
6141 } else {
6142 $urls_table .= format_repo_url("", "No remote URL");
6145 $urls_table .= "</table>\n";
6147 my $dots;
6148 if (defined $limit && $limit < @$heads) {
6149 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6152 print $urls_table;
6153 git_heads_body($heads, $head, 0, $limit, $dots);
6156 # Display a list of remote names with the respective fetch and push URLs
6157 sub git_remotes_list {
6158 my ($remotedata, $limit) = @_;
6159 print "<table class=\"heads\">\n";
6160 my $alternate = 1;
6161 my @remotes = sort keys %$remotedata;
6163 my $limited = $limit && $limit < @remotes;
6165 $#remotes = $limit - 1 if $limited;
6167 while (my $remote = shift @remotes) {
6168 my $rdata = $remotedata->{$remote};
6169 my $fetch = $rdata->{'fetch'};
6170 my $push = $rdata->{'push'};
6171 if ($alternate) {
6172 print "<tr class=\"dark\">\n";
6173 } else {
6174 print "<tr class=\"light\">\n";
6176 $alternate ^= 1;
6177 print "<td>" .
6178 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6179 -class=> "list name"},esc_html($remote)) .
6180 "</td>";
6181 print "<td class=\"link\">" .
6182 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6183 " | " .
6184 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6185 "</td>";
6187 print "</tr>\n";
6190 if ($limited) {
6191 print "<tr>\n" .
6192 "<td colspan=\"3\">" .
6193 $cgi->a({-href => href(action=>"remotes")}, "...") .
6194 "</td>\n" . "</tr>\n";
6197 print "</table>";
6200 # Display remote heads grouped by remote, unless there are too many
6201 # remotes, in which case we only display the remote names
6202 sub git_remotes_body {
6203 my ($remotedata, $limit, $head) = @_;
6204 if ($limit and $limit < keys %$remotedata) {
6205 git_remotes_list($remotedata, $limit);
6206 } else {
6207 fill_remote_heads($remotedata);
6208 while (my ($remote, $rdata) = each %$remotedata) {
6209 git_print_section({-class=>"remote", -id=>$remote},
6210 ["remotes", $remote, $remote], sub {
6211 git_remote_block($remote, $rdata, $limit, $head);
6217 sub git_search_message {
6218 my %co = @_;
6220 my $greptype;
6221 if ($searchtype eq 'commit') {
6222 $greptype = "--grep=";
6223 } elsif ($searchtype eq 'author') {
6224 $greptype = "--author=";
6225 } elsif ($searchtype eq 'committer') {
6226 $greptype = "--committer=";
6228 $greptype .= $searchtext;
6229 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6230 $greptype, '--regexp-ignore-case',
6231 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6233 my $paging_nav = '';
6234 if ($page > 0) {
6235 $paging_nav .=
6236 $cgi->a({-href => href(-replay=>1, page=>undef)},
6237 "first") .
6238 " &sdot; " .
6239 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6240 -accesskey => "p", -title => "Alt-p"}, "prev");
6241 } else {
6242 $paging_nav .= "first &sdot; prev";
6244 my $next_link = '';
6245 if ($#commitlist >= 100) {
6246 $next_link =
6247 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6248 -accesskey => "n", -title => "Alt-n"}, "next");
6249 $paging_nav .= " &sdot; $next_link";
6250 } else {
6251 $paging_nav .= " &sdot; next";
6254 git_header_html();
6256 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6257 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6258 if ($page == 0 && !@commitlist) {
6259 print "<p>No match.</p>\n";
6260 } else {
6261 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6264 git_footer_html();
6267 sub git_search_changes {
6268 my %co = @_;
6270 local $/ = "\n";
6271 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6272 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6273 ($search_use_regexp ? '--pickaxe-regex' : ())
6274 or die_error(500, "Open git-log failed");
6276 git_header_html();
6278 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6279 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6281 print "<table class=\"pickaxe search\">\n";
6282 my $alternate = 1;
6283 undef %co;
6284 my @files;
6285 while (my $line = <$fd>) {
6286 chomp $line;
6287 next unless $line;
6289 my %set = parse_difftree_raw_line($line);
6290 if (defined $set{'commit'}) {
6291 # finish previous commit
6292 if (%co) {
6293 print "</td>\n" .
6294 "<td class=\"link\">" .
6295 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6296 "commit") .
6297 " | " .
6298 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6299 hash_base=>$co{'id'})},
6300 "tree") .
6301 "</td>\n" .
6302 "</tr>\n";
6305 if ($alternate) {
6306 print "<tr class=\"dark\">\n";
6307 } else {
6308 print "<tr class=\"light\">\n";
6310 $alternate ^= 1;
6311 %co = parse_commit($set{'commit'});
6312 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6313 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6314 "<td><i>$author</i></td>\n" .
6315 "<td>" .
6316 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6317 -class => "list subject"},
6318 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6319 } elsif (defined $set{'to_id'}) {
6320 next if ($set{'to_id'} =~ m/^0{40}$/);
6322 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6323 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6324 -class => "list"},
6325 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6326 "<br/>\n";
6329 close $fd;
6331 # finish last commit (warning: repetition!)
6332 if (%co) {
6333 print "</td>\n" .
6334 "<td class=\"link\">" .
6335 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6336 "commit") .
6337 " | " .
6338 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6339 hash_base=>$co{'id'})},
6340 "tree") .
6341 "</td>\n" .
6342 "</tr>\n";
6345 print "</table>\n";
6347 git_footer_html();
6350 sub git_search_files {
6351 my %co = @_;
6353 local $/ = "\n";
6354 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6355 $search_use_regexp ? ('-E', '-i') : '-F',
6356 $searchtext, $co{'tree'}
6357 or die_error(500, "Open git-grep failed");
6359 git_header_html();
6361 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6362 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6364 print "<table class=\"grep_search\">\n";
6365 my $alternate = 1;
6366 my $matches = 0;
6367 my $lastfile = '';
6368 my $file_href;
6369 while (my $line = <$fd>) {
6370 chomp $line;
6371 my ($file, $lno, $ltext, $binary);
6372 last if ($matches++ > 1000);
6373 if ($line =~ /^Binary file (.+) matches$/) {
6374 $file = $1;
6375 $binary = 1;
6376 } else {
6377 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6378 $file =~ s/^$co{'tree'}://;
6380 if ($file ne $lastfile) {
6381 $lastfile and print "</td></tr>\n";
6382 if ($alternate++) {
6383 print "<tr class=\"dark\">\n";
6384 } else {
6385 print "<tr class=\"light\">\n";
6387 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6388 file_name=>$file);
6389 print "<td class=\"list\">".
6390 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6391 print "</td><td>\n";
6392 $lastfile = $file;
6394 if ($binary) {
6395 print "<div class=\"binary\">Binary file</div>\n";
6396 } else {
6397 $ltext = untabify($ltext);
6398 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6399 $ltext = esc_html($1, -nbsp=>1);
6400 $ltext .= '<span class="match">';
6401 $ltext .= esc_html($2, -nbsp=>1);
6402 $ltext .= '</span>';
6403 $ltext .= esc_html($3, -nbsp=>1);
6404 } else {
6405 $ltext = esc_html($ltext, -nbsp=>1);
6407 print "<div class=\"pre\">" .
6408 $cgi->a({-href => $file_href.'#l'.$lno,
6409 -class => "linenr"}, sprintf('%4i', $lno)) .
6410 ' ' . $ltext . "</div>\n";
6413 if ($lastfile) {
6414 print "</td></tr>\n";
6415 if ($matches > 1000) {
6416 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6418 } else {
6419 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6421 close $fd;
6423 print "</table>\n";
6425 git_footer_html();
6428 sub git_search_grep_body {
6429 my ($commitlist, $from, $to, $extra) = @_;
6430 $from = 0 unless defined $from;
6431 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6433 print "<table class=\"commit_search\">\n";
6434 my $alternate = 1;
6435 for (my $i = $from; $i <= $to; $i++) {
6436 my %co = %{$commitlist->[$i]};
6437 if (!%co) {
6438 next;
6440 my $commit = $co{'id'};
6441 if ($alternate) {
6442 print "<tr class=\"dark\">\n";
6443 } else {
6444 print "<tr class=\"light\">\n";
6446 $alternate ^= 1;
6447 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6448 format_author_html('td', \%co, 15, 5) .
6449 "<td>" .
6450 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6451 -class => "list subject"},
6452 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6453 my $comment = $co{'comment'};
6454 foreach my $line (@$comment) {
6455 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6456 my ($lead, $match, $trail) = ($1, $2, $3);
6457 $match = chop_str($match, 70, 5, 'center');
6458 my $contextlen = int((80 - length($match))/2);
6459 $contextlen = 30 if ($contextlen > 30);
6460 $lead = chop_str($lead, $contextlen, 10, 'left');
6461 $trail = chop_str($trail, $contextlen, 10, 'right');
6463 $lead = esc_html($lead);
6464 $match = esc_html($match);
6465 $trail = esc_html($trail);
6467 print "$lead<span class=\"match\">$match</span>$trail<br />";
6470 print "</td>\n" .
6471 "<td class=\"link\">" .
6472 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6473 " | " .
6474 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6475 " | " .
6476 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6477 print "</td>\n" .
6478 "</tr>\n";
6480 if (defined $extra) {
6481 print "<tr>\n" .
6482 "<td colspan=\"3\">$extra</td>\n" .
6483 "</tr>\n";
6485 print "</table>\n";
6488 ## ======================================================================
6489 ## ======================================================================
6490 ## actions
6492 sub git_project_list {
6493 my $order = $input_params{'order'};
6494 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6495 die_error(400, "Unknown order parameter");
6498 my @list = git_get_projects_list($project_filter, $strict_export);
6499 if (!@list) {
6500 die_error(404, "No projects found");
6503 git_header_html();
6504 if (defined $home_text && -f $home_text) {
6505 print "<div class=\"index_include\">\n";
6506 insert_file($home_text);
6507 print "</div>\n";
6510 git_project_search_form($searchtext, $search_use_regexp);
6511 git_project_list_body(\@list, $order);
6512 git_footer_html();
6515 sub git_forks {
6516 my $order = $input_params{'order'};
6517 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6518 die_error(400, "Unknown order parameter");
6521 my $filter = $project;
6522 $filter =~ s/\.git$//;
6523 my @list = git_get_projects_list($filter);
6524 if (!@list) {
6525 die_error(404, "No forks found");
6528 git_header_html();
6529 git_print_page_nav('','');
6530 git_print_header_div('summary', "$project forks");
6531 git_project_list_body(\@list, $order);
6532 git_footer_html();
6535 sub git_project_index {
6536 my @projects = git_get_projects_list($project_filter, $strict_export);
6537 if (!@projects) {
6538 die_error(404, "No projects found");
6541 print $cgi->header(
6542 -type => 'text/plain',
6543 -charset => 'utf-8',
6544 -content_disposition => 'inline; filename="index.aux"');
6546 foreach my $pr (@projects) {
6547 if (!exists $pr->{'owner'}) {
6548 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6551 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6552 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6553 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6554 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6555 $path =~ s/ /\+/g;
6556 $owner =~ s/ /\+/g;
6558 print "$path $owner\n";
6562 sub git_summary {
6563 my $descr = git_get_project_description($project) || "none";
6564 my %co = parse_commit("HEAD");
6565 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6566 my $head = $co{'id'};
6567 my $remote_heads = gitweb_check_feature('remote_heads');
6569 my $owner = git_get_project_owner($project);
6571 my $refs = git_get_references();
6572 # These get_*_list functions return one more to allow us to see if
6573 # there are more ...
6574 my @taglist = git_get_tags_list(16);
6575 my @headlist = git_get_heads_list(16);
6576 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6577 my @forklist;
6578 my $check_forks = gitweb_check_feature('forks');
6580 if ($check_forks) {
6581 # find forks of a project
6582 my $filter = $project;
6583 $filter =~ s/\.git$//;
6584 @forklist = git_get_projects_list($filter);
6585 # filter out forks of forks
6586 @forklist = filter_forks_from_projects_list(\@forklist)
6587 if (@forklist);
6590 git_header_html();
6591 git_print_page_nav('summary','', $head);
6593 print "<div class=\"title\">&nbsp;</div>\n";
6594 print "<table class=\"projects_list\">\n" .
6595 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6596 if ($owner and not $omit_owner) {
6597 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6599 if (defined $cd{'rfc2822'}) {
6600 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6601 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6604 # use per project git URL list in $projectroot/$project/cloneurl
6605 # or make project git URL from git base URL and project name
6606 my $url_tag = "URL";
6607 my @url_list = git_get_project_url_list($project);
6608 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6609 foreach my $git_url (@url_list) {
6610 next unless $git_url;
6611 print format_repo_url($url_tag, $git_url);
6612 $url_tag = "";
6615 # Tag cloud
6616 my $show_ctags = gitweb_check_feature('ctags');
6617 if ($show_ctags) {
6618 my $ctags = git_get_project_ctags($project);
6619 if (%$ctags) {
6620 # without ability to add tags, don't show if there are none
6621 my $cloud = git_populate_project_tagcloud($ctags);
6622 print "<tr id=\"metadata_ctags\">" .
6623 "<td>content tags</td>" .
6624 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6625 "</tr>\n";
6629 print "</table>\n";
6631 # If XSS prevention is on, we don't include README.html.
6632 # TODO: Allow a readme in some safe format.
6633 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6634 print "<div class=\"title\">readme</div>\n" .
6635 "<div class=\"readme\">\n";
6636 insert_file("$projectroot/$project/README.html");
6637 print "\n</div>\n"; # class="readme"
6640 # we need to request one more than 16 (0..15) to check if
6641 # those 16 are all
6642 my @commitlist = $head ? parse_commits($head, 17) : ();
6643 if (@commitlist) {
6644 git_print_header_div('shortlog');
6645 git_shortlog_body(\@commitlist, 0, 15, $refs,
6646 $#commitlist <= 15 ? undef :
6647 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6650 if (@taglist) {
6651 git_print_header_div('tags');
6652 git_tags_body(\@taglist, 0, 15,
6653 $#taglist <= 15 ? undef :
6654 $cgi->a({-href => href(action=>"tags")}, "..."));
6657 if (@headlist) {
6658 git_print_header_div('heads');
6659 git_heads_body(\@headlist, $head, 0, 15,
6660 $#headlist <= 15 ? undef :
6661 $cgi->a({-href => href(action=>"heads")}, "..."));
6664 if (%remotedata) {
6665 git_print_header_div('remotes');
6666 git_remotes_body(\%remotedata, 15, $head);
6669 if (@forklist) {
6670 git_print_header_div('forks');
6671 git_project_list_body(\@forklist, 'age', 0, 15,
6672 $#forklist <= 15 ? undef :
6673 $cgi->a({-href => href(action=>"forks")}, "..."),
6674 'no_header');
6677 git_footer_html();
6680 sub git_tag {
6681 my %tag = parse_tag($hash);
6683 if (! %tag) {
6684 die_error(404, "Unknown tag object");
6687 my $head = git_get_head_hash($project);
6688 git_header_html();
6689 git_print_page_nav('','', $head,undef,$head);
6690 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6691 print "<div class=\"title_text\">\n" .
6692 "<table class=\"object_header\">\n" .
6693 "<tr>\n" .
6694 "<td>object</td>\n" .
6695 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6696 $tag{'object'}) . "</td>\n" .
6697 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6698 $tag{'type'}) . "</td>\n" .
6699 "</tr>\n";
6700 if (defined($tag{'author'})) {
6701 git_print_authorship_rows(\%tag, 'author');
6703 print "</table>\n\n" .
6704 "</div>\n";
6705 print "<div class=\"page_body\">";
6706 my $comment = $tag{'comment'};
6707 foreach my $line (@$comment) {
6708 chomp $line;
6709 print esc_html($line, -nbsp=>1) . "<br/>\n";
6711 print "</div>\n";
6712 git_footer_html();
6715 sub git_blame_common {
6716 my $format = shift || 'porcelain';
6717 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6718 $format = 'incremental';
6719 $action = 'blame_incremental'; # for page title etc
6722 # permissions
6723 gitweb_check_feature('blame')
6724 or die_error(403, "Blame view not allowed");
6726 # error checking
6727 die_error(400, "No file name given") unless $file_name;
6728 $hash_base ||= git_get_head_hash($project);
6729 die_error(404, "Couldn't find base commit") unless $hash_base;
6730 my %co = parse_commit($hash_base)
6731 or die_error(404, "Commit not found");
6732 my $ftype = "blob";
6733 if (!defined $hash) {
6734 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6735 or die_error(404, "Error looking up file");
6736 } else {
6737 $ftype = git_get_type($hash);
6738 if ($ftype !~ "blob") {
6739 die_error(400, "Object is not a blob");
6743 my $fd;
6744 if ($format eq 'incremental') {
6745 # get file contents (as base)
6746 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6747 or die_error(500, "Open git-cat-file failed");
6748 } elsif ($format eq 'data') {
6749 # run git-blame --incremental
6750 open $fd, "-|", git_cmd(), "blame", "--incremental",
6751 $hash_base, "--", $file_name
6752 or die_error(500, "Open git-blame --incremental failed");
6753 } else {
6754 # run git-blame --porcelain
6755 open $fd, "-|", git_cmd(), "blame", '-p',
6756 $hash_base, '--', $file_name
6757 or die_error(500, "Open git-blame --porcelain failed");
6759 binmode $fd, ':utf8';
6761 # incremental blame data returns early
6762 if ($format eq 'data') {
6763 print $cgi->header(
6764 -type=>"text/plain", -charset => "utf-8",
6765 -status=> "200 OK");
6766 local $| = 1; # output autoflush
6767 while (my $line = <$fd>) {
6768 print to_utf8($line);
6770 close $fd
6771 or print "ERROR $!\n";
6773 print 'END';
6774 if (defined $t0 && gitweb_check_feature('timed')) {
6775 print ' '.
6776 tv_interval($t0, [ gettimeofday() ]).
6777 ' '.$number_of_git_cmds;
6779 print "\n";
6781 return;
6784 # page header
6785 git_header_html();
6786 my $formats_nav =
6787 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6788 "blob") .
6789 " | ";
6790 if ($format eq 'incremental') {
6791 $formats_nav .=
6792 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6793 "blame") . " (non-incremental)";
6794 } else {
6795 $formats_nav .=
6796 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6797 "blame") . " (incremental)";
6799 $formats_nav .=
6800 " | " .
6801 $cgi->a({-href => href(action=>"history", -replay=>1)},
6802 "history") .
6803 " | " .
6804 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6805 "HEAD");
6806 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6807 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6808 git_print_page_path($file_name, $ftype, $hash_base);
6810 # page body
6811 if ($format eq 'incremental') {
6812 print "<noscript>\n<div class=\"error\"><center><b>\n".
6813 "This page requires JavaScript to run.\n Use ".
6814 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6815 'this page').
6816 " instead.\n".
6817 "</b></center></div>\n</noscript>\n";
6819 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6822 print qq!<div class="page_body">\n!;
6823 print qq!<div id="progress_info">... / ...</div>\n!
6824 if ($format eq 'incremental');
6825 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6826 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6827 qq!<thead>\n!.
6828 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6829 qq!</thead>\n!.
6830 qq!<tbody>\n!;
6832 my @rev_color = qw(light dark);
6833 my $num_colors = scalar(@rev_color);
6834 my $current_color = 0;
6836 if ($format eq 'incremental') {
6837 my $color_class = $rev_color[$current_color];
6839 #contents of a file
6840 my $linenr = 0;
6841 LINE:
6842 while (my $line = <$fd>) {
6843 chomp $line;
6844 $linenr++;
6846 print qq!<tr id="l$linenr" class="$color_class">!.
6847 qq!<td class="sha1"><a href=""> </a></td>!.
6848 qq!<td class="linenr">!.
6849 qq!<a class="linenr" href="">$linenr</a></td>!;
6850 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6851 print qq!</tr>\n!;
6854 } else { # porcelain, i.e. ordinary blame
6855 my %metainfo = (); # saves information about commits
6857 # blame data
6858 LINE:
6859 while (my $line = <$fd>) {
6860 chomp $line;
6861 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6862 # no <lines in group> for subsequent lines in group of lines
6863 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6864 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6865 if (!exists $metainfo{$full_rev}) {
6866 $metainfo{$full_rev} = { 'nprevious' => 0 };
6868 my $meta = $metainfo{$full_rev};
6869 my $data;
6870 while ($data = <$fd>) {
6871 chomp $data;
6872 last if ($data =~ s/^\t//); # contents of line
6873 if ($data =~ /^(\S+)(?: (.*))?$/) {
6874 $meta->{$1} = $2 unless exists $meta->{$1};
6876 if ($data =~ /^previous /) {
6877 $meta->{'nprevious'}++;
6880 my $short_rev = substr($full_rev, 0, 8);
6881 my $author = $meta->{'author'};
6882 my %date =
6883 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6884 my $date = $date{'iso-tz'};
6885 if ($group_size) {
6886 $current_color = ($current_color + 1) % $num_colors;
6888 my $tr_class = $rev_color[$current_color];
6889 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6890 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6891 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6892 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6893 if ($group_size) {
6894 print "<td class=\"sha1\"";
6895 print " title=\"". esc_html($author) . ", $date\"";
6896 print " rowspan=\"$group_size\"" if ($group_size > 1);
6897 print ">";
6898 print $cgi->a({-href => href(action=>"commit",
6899 hash=>$full_rev,
6900 file_name=>$file_name)},
6901 esc_html($short_rev));
6902 if ($group_size >= 2) {
6903 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6904 if (@author_initials) {
6905 print "<br />" .
6906 esc_html(join('', @author_initials));
6907 # or join('.', ...)
6910 print "</td>\n";
6912 # 'previous' <sha1 of parent commit> <filename at commit>
6913 if (exists $meta->{'previous'} &&
6914 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6915 $meta->{'parent'} = $1;
6916 $meta->{'file_parent'} = unquote($2);
6918 my $linenr_commit =
6919 exists($meta->{'parent'}) ?
6920 $meta->{'parent'} : $full_rev;
6921 my $linenr_filename =
6922 exists($meta->{'file_parent'}) ?
6923 $meta->{'file_parent'} : unquote($meta->{'filename'});
6924 my $blamed = href(action => 'blame',
6925 file_name => $linenr_filename,
6926 hash_base => $linenr_commit);
6927 print "<td class=\"linenr\">";
6928 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6929 -class => "linenr" },
6930 esc_html($lineno));
6931 print "</td>";
6932 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6933 print "</tr>\n";
6934 } # end while
6938 # footer
6939 print "</tbody>\n".
6940 "</table>\n"; # class="blame"
6941 print "</div>\n"; # class="blame_body"
6942 close $fd
6943 or print "Reading blob failed\n";
6945 git_footer_html();
6948 sub git_blame {
6949 git_blame_common();
6952 sub git_blame_incremental {
6953 git_blame_common('incremental');
6956 sub git_blame_data {
6957 git_blame_common('data');
6960 sub git_tags {
6961 my $head = git_get_head_hash($project);
6962 git_header_html();
6963 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6964 git_print_header_div('summary', $project);
6966 my @tagslist = git_get_tags_list();
6967 if (@tagslist) {
6968 git_tags_body(\@tagslist);
6970 git_footer_html();
6973 sub git_heads {
6974 my $head = git_get_head_hash($project);
6975 git_header_html();
6976 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6977 git_print_header_div('summary', $project);
6979 my @headslist = git_get_heads_list();
6980 if (@headslist) {
6981 git_heads_body(\@headslist, $head);
6983 git_footer_html();
6986 # used both for single remote view and for list of all the remotes
6987 sub git_remotes {
6988 gitweb_check_feature('remote_heads')
6989 or die_error(403, "Remote heads view is disabled");
6991 my $head = git_get_head_hash($project);
6992 my $remote = $input_params{'hash'};
6994 my $remotedata = git_get_remotes_list($remote);
6995 die_error(500, "Unable to get remote information") unless defined $remotedata;
6997 unless (%$remotedata) {
6998 die_error(404, defined $remote ?
6999 "Remote $remote not found" :
7000 "No remotes found");
7003 git_header_html(undef, undef, -action_extra => $remote);
7004 git_print_page_nav('', '', $head, undef, $head,
7005 format_ref_views($remote ? '' : 'remotes'));
7007 fill_remote_heads($remotedata);
7008 if (defined $remote) {
7009 git_print_header_div('remotes', "$remote remote for $project");
7010 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7011 } else {
7012 git_print_header_div('summary', "$project remotes");
7013 git_remotes_body($remotedata, undef, $head);
7016 git_footer_html();
7019 sub git_blob_plain {
7020 my $type = shift;
7021 my $expires;
7023 if (!defined $hash) {
7024 if (defined $file_name) {
7025 my $base = $hash_base || git_get_head_hash($project);
7026 $hash = git_get_hash_by_path($base, $file_name, "blob")
7027 or die_error(404, "Cannot find file");
7028 } else {
7029 die_error(400, "No file name defined");
7031 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7032 # blobs defined by non-textual hash id's can be cached
7033 $expires = "+1d";
7036 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7037 or die_error(500, "Open git-cat-file blob '$hash' failed");
7039 # content-type (can include charset)
7040 $type = blob_contenttype($fd, $file_name, $type);
7042 # "save as" filename, even when no $file_name is given
7043 my $save_as = "$hash";
7044 if (defined $file_name) {
7045 $save_as = $file_name;
7046 } elsif ($type =~ m/^text\//) {
7047 $save_as .= '.txt';
7050 # With XSS prevention on, blobs of all types except a few known safe
7051 # ones are served with "Content-Disposition: attachment" to make sure
7052 # they don't run in our security domain. For certain image types,
7053 # blob view writes an <img> tag referring to blob_plain view, and we
7054 # want to be sure not to break that by serving the image as an
7055 # attachment (though Firefox 3 doesn't seem to care).
7056 my $sandbox = $prevent_xss &&
7057 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7059 # serve text/* as text/plain
7060 if ($prevent_xss &&
7061 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7062 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7063 my $rest = $1;
7064 $rest = defined $rest ? $rest : '';
7065 $type = "text/plain$rest";
7068 print $cgi->header(
7069 -type => $type,
7070 -expires => $expires,
7071 -content_disposition =>
7072 ($sandbox ? 'attachment' : 'inline')
7073 . '; filename="' . $save_as . '"');
7074 local $/ = undef;
7075 binmode STDOUT, ':raw';
7076 print <$fd>;
7077 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7078 close $fd;
7081 sub git_blob {
7082 my $expires;
7084 if (!defined $hash) {
7085 if (defined $file_name) {
7086 my $base = $hash_base || git_get_head_hash($project);
7087 $hash = git_get_hash_by_path($base, $file_name, "blob")
7088 or die_error(404, "Cannot find file");
7089 } else {
7090 die_error(400, "No file name defined");
7092 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7093 # blobs defined by non-textual hash id's can be cached
7094 $expires = "+1d";
7097 my $have_blame = gitweb_check_feature('blame');
7098 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7099 or die_error(500, "Couldn't cat $file_name, $hash");
7100 my $mimetype = blob_mimetype($fd, $file_name);
7101 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7102 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7103 close $fd;
7104 return git_blob_plain($mimetype);
7106 # we can have blame only for text/* mimetype
7107 $have_blame &&= ($mimetype =~ m!^text/!);
7109 my $highlight = gitweb_check_feature('highlight');
7110 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7111 $fd = run_highlighter($fd, $highlight, $syntax)
7112 if $syntax;
7114 git_header_html(undef, $expires);
7115 my $formats_nav = '';
7116 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7117 if (defined $file_name) {
7118 if ($have_blame) {
7119 $formats_nav .=
7120 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7121 "blame") .
7122 " | ";
7124 $formats_nav .=
7125 $cgi->a({-href => href(action=>"history", -replay=>1)},
7126 "history") .
7127 " | " .
7128 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7129 "raw") .
7130 " | " .
7131 $cgi->a({-href => href(action=>"blob",
7132 hash_base=>"HEAD", file_name=>$file_name)},
7133 "HEAD");
7134 } else {
7135 $formats_nav .=
7136 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7137 "raw");
7139 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7140 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7141 } else {
7142 print "<div class=\"page_nav\">\n" .
7143 "<br/><br/></div>\n" .
7144 "<div class=\"title\">".esc_html($hash)."</div>\n";
7146 git_print_page_path($file_name, "blob", $hash_base);
7147 print "<div class=\"page_body\">\n";
7148 if ($mimetype =~ m!^image/!) {
7149 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7150 if ($file_name) {
7151 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7153 print qq! src="! .
7154 href(action=>"blob_plain", hash=>$hash,
7155 hash_base=>$hash_base, file_name=>$file_name) .
7156 qq!" />\n!;
7157 } else {
7158 my $nr;
7159 while (my $line = <$fd>) {
7160 chomp $line;
7161 $nr++;
7162 $line = untabify($line);
7163 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7164 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7165 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7168 close $fd
7169 or print "Reading blob failed.\n";
7170 print "</div>";
7171 git_footer_html();
7174 sub git_tree {
7175 if (!defined $hash_base) {
7176 $hash_base = "HEAD";
7178 if (!defined $hash) {
7179 if (defined $file_name) {
7180 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7181 } else {
7182 $hash = $hash_base;
7185 die_error(404, "No such tree") unless defined($hash);
7187 my $show_sizes = gitweb_check_feature('show-sizes');
7188 my $have_blame = gitweb_check_feature('blame');
7190 my @entries = ();
7192 local $/ = "\0";
7193 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7194 ($show_sizes ? '-l' : ()), @extra_options, $hash
7195 or die_error(500, "Open git-ls-tree failed");
7196 @entries = map { chomp; $_ } <$fd>;
7197 close $fd
7198 or die_error(404, "Reading tree failed");
7201 my $refs = git_get_references();
7202 my $ref = format_ref_marker($refs, $hash_base);
7203 git_header_html();
7204 my $basedir = '';
7205 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7206 my @views_nav = ();
7207 if (defined $file_name) {
7208 push @views_nav,
7209 $cgi->a({-href => href(action=>"history", -replay=>1)},
7210 "history"),
7211 $cgi->a({-href => href(action=>"tree",
7212 hash_base=>"HEAD", file_name=>$file_name)},
7213 "HEAD"),
7215 my $snapshot_links = format_snapshot_links($hash);
7216 if (defined $snapshot_links) {
7217 # FIXME: Should be available when we have no hash base as well.
7218 push @views_nav, $snapshot_links;
7220 git_print_page_nav('tree','', $hash_base, undef, undef,
7221 join(' | ', @views_nav));
7222 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7223 } else {
7224 undef $hash_base;
7225 print "<div class=\"page_nav\">\n";
7226 print "<br/><br/></div>\n";
7227 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7229 if (defined $file_name) {
7230 $basedir = $file_name;
7231 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7232 $basedir .= '/';
7234 git_print_page_path($file_name, 'tree', $hash_base);
7236 print "<div class=\"page_body\">\n";
7237 print "<table class=\"tree\">\n";
7238 my $alternate = 1;
7239 # '..' (top directory) link if possible
7240 if (defined $hash_base &&
7241 defined $file_name && $file_name =~ m![^/]+$!) {
7242 if ($alternate) {
7243 print "<tr class=\"dark\">\n";
7244 } else {
7245 print "<tr class=\"light\">\n";
7247 $alternate ^= 1;
7249 my $up = $file_name;
7250 $up =~ s!/?[^/]+$!!;
7251 undef $up unless $up;
7252 # based on git_print_tree_entry
7253 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7254 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7255 print '<td class="list">';
7256 print $cgi->a({-href => href(action=>"tree",
7257 hash_base=>$hash_base,
7258 file_name=>$up)},
7259 "..");
7260 print "</td>\n";
7261 print "<td class=\"link\"></td>\n";
7263 print "</tr>\n";
7265 foreach my $line (@entries) {
7266 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7268 if ($alternate) {
7269 print "<tr class=\"dark\">\n";
7270 } else {
7271 print "<tr class=\"light\">\n";
7273 $alternate ^= 1;
7275 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7277 print "</tr>\n";
7279 print "</table>\n" .
7280 "</div>";
7281 git_footer_html();
7284 sub sanitize_for_filename {
7285 my $name = shift;
7287 $name =~ s!/!-!g;
7288 $name =~ s/[^[:alnum:]_.-]//g;
7290 return $name;
7293 sub snapshot_name {
7294 my ($project, $hash) = @_;
7296 # path/to/project.git -> project
7297 # path/to/project/.git -> project
7298 my $name = to_utf8($project);
7299 $name =~ s,([^/])/*\.git$,$1,;
7300 $name = sanitize_for_filename(basename($name));
7302 my $ver = $hash;
7303 if ($hash =~ /^[0-9a-fA-F]+$/) {
7304 # shorten SHA-1 hash
7305 my $full_hash = git_get_full_hash($project, $hash);
7306 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7307 $ver = git_get_short_hash($project, $hash);
7309 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7310 # tags don't need shortened SHA-1 hash
7311 $ver = $1;
7312 } else {
7313 # branches and other need shortened SHA-1 hash
7314 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7315 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7316 my $ref_dir = (defined $1) ? $1 : '';
7317 $ver = $2;
7319 $ref_dir = sanitize_for_filename($ref_dir);
7320 # for refs neither in heads nor remotes we want to
7321 # add a ref dir to archive name
7322 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7323 $ver = $ref_dir . '-' . $ver;
7326 $ver .= '-' . git_get_short_hash($project, $hash);
7328 # special case of sanitization for filename - we change
7329 # slashes to dots instead of dashes
7330 # in case of hierarchical branch names
7331 $ver =~ s!/!.!g;
7332 $ver =~ s/[^[:alnum:]_.-]//g;
7334 # name = project-version_string
7335 $name = "$name-$ver";
7337 return wantarray ? ($name, $name) : $name;
7340 sub exit_if_unmodified_since {
7341 my ($latest_epoch) = @_;
7342 our $cgi;
7344 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7345 if (defined $if_modified) {
7346 my $since;
7347 if (eval { require HTTP::Date; 1; }) {
7348 $since = HTTP::Date::str2time($if_modified);
7349 } elsif (eval { require Time::ParseDate; 1; }) {
7350 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7352 if (defined $since && $latest_epoch <= $since) {
7353 my %latest_date = parse_date($latest_epoch);
7354 print $cgi->header(
7355 -last_modified => $latest_date{'rfc2822'},
7356 -status => '304 Not Modified');
7357 goto DONE_GITWEB;
7362 sub git_snapshot {
7363 my $format = $input_params{'snapshot_format'};
7364 if (!@snapshot_fmts) {
7365 die_error(403, "Snapshots not allowed");
7367 # default to first supported snapshot format
7368 $format ||= $snapshot_fmts[0];
7369 if ($format !~ m/^[a-z0-9]+$/) {
7370 die_error(400, "Invalid snapshot format parameter");
7371 } elsif (!exists($known_snapshot_formats{$format})) {
7372 die_error(400, "Unknown snapshot format");
7373 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7374 die_error(403, "Snapshot format not allowed");
7375 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7376 die_error(403, "Unsupported snapshot format");
7379 my $type = git_get_type("$hash^{}");
7380 if (!$type) {
7381 die_error(404, 'Object does not exist');
7382 } elsif ($type eq 'blob') {
7383 die_error(400, 'Object is not a tree-ish');
7386 my ($name, $prefix) = snapshot_name($project, $hash);
7387 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7389 my %co = parse_commit($hash);
7390 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7392 my $cmd = quote_command(
7393 git_cmd(), 'archive',
7394 "--format=$known_snapshot_formats{$format}{'format'}",
7395 "--prefix=$prefix/", $hash);
7396 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7397 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7400 $filename =~ s/(["\\])/\\$1/g;
7401 my %latest_date;
7402 if (%co) {
7403 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7406 print $cgi->header(
7407 -type => $known_snapshot_formats{$format}{'type'},
7408 -content_disposition => 'inline; filename="' . $filename . '"',
7409 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7410 -status => '200 OK');
7412 open my $fd, "-|", $cmd
7413 or die_error(500, "Execute git-archive failed");
7414 binmode STDOUT, ':raw';
7415 print <$fd>;
7416 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7417 close $fd;
7420 sub git_log_generic {
7421 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7423 my $head = git_get_head_hash($project);
7424 if (!defined $base) {
7425 $base = $head;
7427 if (!defined $page) {
7428 $page = 0;
7430 my $refs = git_get_references();
7432 my $commit_hash = $base;
7433 if (defined $parent) {
7434 $commit_hash = "$parent..$base";
7436 my @commitlist =
7437 parse_commits($commit_hash, 101, (100 * $page),
7438 defined $file_name ? ($file_name, "--full-history") : ());
7440 my $ftype;
7441 if (!defined $file_hash && defined $file_name) {
7442 # some commits could have deleted file in question,
7443 # and not have it in tree, but one of them has to have it
7444 for (my $i = 0; $i < @commitlist; $i++) {
7445 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7446 last if defined $file_hash;
7449 if (defined $file_hash) {
7450 $ftype = git_get_type($file_hash);
7452 if (defined $file_name && !defined $ftype) {
7453 die_error(500, "Unknown type of object");
7455 my %co;
7456 if (defined $file_name) {
7457 %co = parse_commit($base)
7458 or die_error(404, "Unknown commit object");
7462 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7463 my $next_link = '';
7464 if ($#commitlist >= 100) {
7465 $next_link =
7466 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7467 -accesskey => "n", -title => "Alt-n"}, "next");
7469 my $patch_max = gitweb_get_feature('patches');
7470 if ($patch_max && !defined $file_name) {
7471 if ($patch_max < 0 || @commitlist <= $patch_max) {
7472 $paging_nav .= " &sdot; " .
7473 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7474 "patches");
7478 git_header_html();
7479 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7480 if (defined $file_name) {
7481 git_print_header_div('commit', esc_html($co{'title'}), $base);
7482 } else {
7483 git_print_header_div('summary', $project)
7485 git_print_page_path($file_name, $ftype, $hash_base)
7486 if (defined $file_name);
7488 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7489 $file_name, $file_hash, $ftype);
7491 git_footer_html();
7494 sub git_log {
7495 git_log_generic('log', \&git_log_body,
7496 $hash, $hash_parent);
7499 sub git_commit {
7500 $hash ||= $hash_base || "HEAD";
7501 my %co = parse_commit($hash)
7502 or die_error(404, "Unknown commit object");
7504 my $parent = $co{'parent'};
7505 my $parents = $co{'parents'}; # listref
7507 # we need to prepare $formats_nav before any parameter munging
7508 my $formats_nav;
7509 if (!defined $parent) {
7510 # --root commitdiff
7511 $formats_nav .= '(initial)';
7512 } elsif (@$parents == 1) {
7513 # single parent commit
7514 $formats_nav .=
7515 '(parent: ' .
7516 $cgi->a({-href => href(action=>"commit",
7517 hash=>$parent)},
7518 esc_html(substr($parent, 0, 7))) .
7519 ')';
7520 } else {
7521 # merge commit
7522 $formats_nav .=
7523 '(merge: ' .
7524 join(' ', map {
7525 $cgi->a({-href => href(action=>"commit",
7526 hash=>$_)},
7527 esc_html(substr($_, 0, 7)));
7528 } @$parents ) .
7529 ')';
7531 if (gitweb_check_feature('patches') && @$parents <= 1) {
7532 $formats_nav .= " | " .
7533 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7534 "patch");
7537 if (!defined $parent) {
7538 $parent = "--root";
7540 my @difftree;
7541 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7542 @diff_opts,
7543 (@$parents <= 1 ? $parent : '-c'),
7544 $hash, "--"
7545 or die_error(500, "Open git-diff-tree failed");
7546 @difftree = map { chomp; $_ } <$fd>;
7547 close $fd or die_error(404, "Reading git-diff-tree failed");
7549 # non-textual hash id's can be cached
7550 my $expires;
7551 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7552 $expires = "+1d";
7554 my $refs = git_get_references();
7555 my $ref = format_ref_marker($refs, $co{'id'});
7557 git_header_html(undef, $expires);
7558 git_print_page_nav('commit', '',
7559 $hash, $co{'tree'}, $hash,
7560 $formats_nav);
7562 if (defined $co{'parent'}) {
7563 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7564 } else {
7565 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7567 print "<div class=\"title_text\">\n" .
7568 "<table class=\"object_header\">\n";
7569 git_print_authorship_rows(\%co);
7570 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7571 print "<tr>" .
7572 "<td>tree</td>" .
7573 "<td class=\"sha1\">" .
7574 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7575 class => "list"}, $co{'tree'}) .
7576 "</td>" .
7577 "<td class=\"link\">" .
7578 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7579 "tree");
7580 my $snapshot_links = format_snapshot_links($hash);
7581 if (defined $snapshot_links) {
7582 print " | " . $snapshot_links;
7584 print "</td>" .
7585 "</tr>\n";
7587 foreach my $par (@$parents) {
7588 print "<tr>" .
7589 "<td>parent</td>" .
7590 "<td class=\"sha1\">" .
7591 $cgi->a({-href => href(action=>"commit", hash=>$par),
7592 class => "list"}, $par) .
7593 "</td>" .
7594 "<td class=\"link\">" .
7595 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7596 " | " .
7597 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7598 "</td>" .
7599 "</tr>\n";
7601 print "</table>".
7602 "</div>\n";
7604 print "<div class=\"page_body\">\n";
7605 git_print_log($co{'comment'});
7606 print "</div>\n";
7608 git_difftree_body(\@difftree, $hash, @$parents);
7610 git_footer_html();
7613 sub git_object {
7614 # object is defined by:
7615 # - hash or hash_base alone
7616 # - hash_base and file_name
7617 my $type;
7619 # - hash or hash_base alone
7620 if ($hash || ($hash_base && !defined $file_name)) {
7621 my $object_id = $hash || $hash_base;
7623 open my $fd, "-|", quote_command(
7624 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7625 or die_error(404, "Object does not exist");
7626 $type = <$fd>;
7627 chomp $type;
7628 close $fd
7629 or die_error(404, "Object does not exist");
7631 # - hash_base and file_name
7632 } elsif ($hash_base && defined $file_name) {
7633 $file_name =~ s,/+$,,;
7635 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7636 or die_error(404, "Base object does not exist");
7638 # here errors should not happen
7639 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7640 or die_error(500, "Open git-ls-tree failed");
7641 my $line = <$fd>;
7642 close $fd;
7644 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7645 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7646 die_error(404, "File or directory for given base does not exist");
7648 $type = $2;
7649 $hash = $3;
7650 } else {
7651 die_error(400, "Not enough information to find object");
7654 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7655 hash=>$hash, hash_base=>$hash_base,
7656 file_name=>$file_name),
7657 -status => '302 Found');
7660 sub git_blobdiff {
7661 my $format = shift || 'html';
7662 my $diff_style = $input_params{'diff_style'} || 'inline';
7664 my $fd;
7665 my @difftree;
7666 my %diffinfo;
7667 my $expires;
7669 # preparing $fd and %diffinfo for git_patchset_body
7670 # new style URI
7671 if (defined $hash_base && defined $hash_parent_base) {
7672 if (defined $file_name) {
7673 # read raw output
7674 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7675 $hash_parent_base, $hash_base,
7676 "--", (defined $file_parent ? $file_parent : ()), $file_name
7677 or die_error(500, "Open git-diff-tree failed");
7678 @difftree = map { chomp; $_ } <$fd>;
7679 close $fd
7680 or die_error(404, "Reading git-diff-tree failed");
7681 @difftree
7682 or die_error(404, "Blob diff not found");
7684 } elsif (defined $hash &&
7685 $hash =~ /[0-9a-fA-F]{40}/) {
7686 # try to find filename from $hash
7688 # read filtered raw output
7689 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7690 $hash_parent_base, $hash_base, "--"
7691 or die_error(500, "Open git-diff-tree failed");
7692 @difftree =
7693 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7694 # $hash == to_id
7695 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7696 map { chomp; $_ } <$fd>;
7697 close $fd
7698 or die_error(404, "Reading git-diff-tree failed");
7699 @difftree
7700 or die_error(404, "Blob diff not found");
7702 } else {
7703 die_error(400, "Missing one of the blob diff parameters");
7706 if (@difftree > 1) {
7707 die_error(400, "Ambiguous blob diff specification");
7710 %diffinfo = parse_difftree_raw_line($difftree[0]);
7711 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7712 $file_name ||= $diffinfo{'to_file'};
7714 $hash_parent ||= $diffinfo{'from_id'};
7715 $hash ||= $diffinfo{'to_id'};
7717 # non-textual hash id's can be cached
7718 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7719 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7720 $expires = '+1d';
7723 # open patch output
7724 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7725 '-p', ($format eq 'html' ? "--full-index" : ()),
7726 $hash_parent_base, $hash_base,
7727 "--", (defined $file_parent ? $file_parent : ()), $file_name
7728 or die_error(500, "Open git-diff-tree failed");
7731 # old/legacy style URI -- not generated anymore since 1.4.3.
7732 if (!%diffinfo) {
7733 die_error('404 Not Found', "Missing one of the blob diff parameters")
7736 # header
7737 if ($format eq 'html') {
7738 my $formats_nav =
7739 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7740 "raw");
7741 $formats_nav .= diff_style_nav($diff_style);
7742 git_header_html(undef, $expires);
7743 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7744 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7745 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7746 } else {
7747 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7748 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7750 if (defined $file_name) {
7751 git_print_page_path($file_name, "blob", $hash_base);
7752 } else {
7753 print "<div class=\"page_path\"></div>\n";
7756 } elsif ($format eq 'plain') {
7757 print $cgi->header(
7758 -type => 'text/plain',
7759 -charset => 'utf-8',
7760 -expires => $expires,
7761 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7763 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7765 } else {
7766 die_error(400, "Unknown blobdiff format");
7769 # patch
7770 if ($format eq 'html') {
7771 print "<div class=\"page_body\">\n";
7773 git_patchset_body($fd, $diff_style,
7774 [ \%diffinfo ], $hash_base, $hash_parent_base);
7775 close $fd;
7777 print "</div>\n"; # class="page_body"
7778 git_footer_html();
7780 } else {
7781 while (my $line = <$fd>) {
7782 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7783 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7785 print $line;
7787 last if $line =~ m!^\+\+\+!;
7789 local $/ = undef;
7790 print <$fd>;
7791 close $fd;
7795 sub git_blobdiff_plain {
7796 git_blobdiff('plain');
7799 # assumes that it is added as later part of already existing navigation,
7800 # so it returns "| foo | bar" rather than just "foo | bar"
7801 sub diff_style_nav {
7802 my ($diff_style, $is_combined) = @_;
7803 $diff_style ||= 'inline';
7805 return "" if ($is_combined);
7807 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7808 my %styles = @styles;
7809 @styles =
7810 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7812 return join '',
7813 map { " | ".$_ }
7814 map {
7815 $_ eq $diff_style ? $styles{$_} :
7816 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7817 } @styles;
7820 sub git_commitdiff {
7821 my %params = @_;
7822 my $format = $params{-format} || 'html';
7823 my $diff_style = $input_params{'diff_style'} || 'inline';
7825 my ($patch_max) = gitweb_get_feature('patches');
7826 if ($format eq 'patch') {
7827 die_error(403, "Patch view not allowed") unless $patch_max;
7830 $hash ||= $hash_base || "HEAD";
7831 my %co = parse_commit($hash)
7832 or die_error(404, "Unknown commit object");
7834 # choose format for commitdiff for merge
7835 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7836 $hash_parent = '--cc';
7838 # we need to prepare $formats_nav before almost any parameter munging
7839 my $formats_nav;
7840 if ($format eq 'html') {
7841 $formats_nav =
7842 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7843 "raw");
7844 if ($patch_max && @{$co{'parents'}} <= 1) {
7845 $formats_nav .= " | " .
7846 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7847 "patch");
7849 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7851 if (defined $hash_parent &&
7852 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7853 # commitdiff with two commits given
7854 my $hash_parent_short = $hash_parent;
7855 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7856 $hash_parent_short = substr($hash_parent, 0, 7);
7858 $formats_nav .=
7859 ' (from';
7860 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7861 if ($co{'parents'}[$i] eq $hash_parent) {
7862 $formats_nav .= ' parent ' . ($i+1);
7863 last;
7866 $formats_nav .= ': ' .
7867 $cgi->a({-href => href(-replay=>1,
7868 hash=>$hash_parent, hash_base=>undef)},
7869 esc_html($hash_parent_short)) .
7870 ')';
7871 } elsif (!$co{'parent'}) {
7872 # --root commitdiff
7873 $formats_nav .= ' (initial)';
7874 } elsif (scalar @{$co{'parents'}} == 1) {
7875 # single parent commit
7876 $formats_nav .=
7877 ' (parent: ' .
7878 $cgi->a({-href => href(-replay=>1,
7879 hash=>$co{'parent'}, hash_base=>undef)},
7880 esc_html(substr($co{'parent'}, 0, 7))) .
7881 ')';
7882 } else {
7883 # merge commit
7884 if ($hash_parent eq '--cc') {
7885 $formats_nav .= ' | ' .
7886 $cgi->a({-href => href(-replay=>1,
7887 hash=>$hash, hash_parent=>'-c')},
7888 'combined');
7889 } else { # $hash_parent eq '-c'
7890 $formats_nav .= ' | ' .
7891 $cgi->a({-href => href(-replay=>1,
7892 hash=>$hash, hash_parent=>'--cc')},
7893 'compact');
7895 $formats_nav .=
7896 ' (merge: ' .
7897 join(' ', map {
7898 $cgi->a({-href => href(-replay=>1,
7899 hash=>$_, hash_base=>undef)},
7900 esc_html(substr($_, 0, 7)));
7901 } @{$co{'parents'}} ) .
7902 ')';
7906 my $hash_parent_param = $hash_parent;
7907 if (!defined $hash_parent_param) {
7908 # --cc for multiple parents, --root for parentless
7909 $hash_parent_param =
7910 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7913 # read commitdiff
7914 my $fd;
7915 my @difftree;
7916 if ($format eq 'html') {
7917 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7918 "--no-commit-id", "--patch-with-raw", "--full-index",
7919 $hash_parent_param, $hash, "--"
7920 or die_error(500, "Open git-diff-tree failed");
7922 while (my $line = <$fd>) {
7923 chomp $line;
7924 # empty line ends raw part of diff-tree output
7925 last unless $line;
7926 push @difftree, scalar parse_difftree_raw_line($line);
7929 } elsif ($format eq 'plain') {
7930 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7931 '-p', $hash_parent_param, $hash, "--"
7932 or die_error(500, "Open git-diff-tree failed");
7933 } elsif ($format eq 'patch') {
7934 # For commit ranges, we limit the output to the number of
7935 # patches specified in the 'patches' feature.
7936 # For single commits, we limit the output to a single patch,
7937 # diverging from the git-format-patch default.
7938 my @commit_spec = ();
7939 if ($hash_parent) {
7940 if ($patch_max > 0) {
7941 push @commit_spec, "-$patch_max";
7943 push @commit_spec, '-n', "$hash_parent..$hash";
7944 } else {
7945 if ($params{-single}) {
7946 push @commit_spec, '-1';
7947 } else {
7948 if ($patch_max > 0) {
7949 push @commit_spec, "-$patch_max";
7951 push @commit_spec, "-n";
7953 push @commit_spec, '--root', $hash;
7955 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7956 '--encoding=utf8', '--stdout', @commit_spec
7957 or die_error(500, "Open git-format-patch failed");
7958 } else {
7959 die_error(400, "Unknown commitdiff format");
7962 # non-textual hash id's can be cached
7963 my $expires;
7964 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7965 $expires = "+1d";
7968 # write commit message
7969 if ($format eq 'html') {
7970 my $refs = git_get_references();
7971 my $ref = format_ref_marker($refs, $co{'id'});
7973 git_header_html(undef, $expires);
7974 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7975 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7976 print "<div class=\"title_text\">\n" .
7977 "<table class=\"object_header\">\n";
7978 git_print_authorship_rows(\%co);
7979 print "</table>".
7980 "</div>\n";
7981 print "<div class=\"page_body\">\n";
7982 if (@{$co{'comment'}} > 1) {
7983 print "<div class=\"log\">\n";
7984 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7985 print "</div>\n"; # class="log"
7988 } elsif ($format eq 'plain') {
7989 my $refs = git_get_references("tags");
7990 my $tagname = git_get_rev_name_tags($hash);
7991 my $filename = basename($project) . "-$hash.patch";
7993 print $cgi->header(
7994 -type => 'text/plain',
7995 -charset => 'utf-8',
7996 -expires => $expires,
7997 -content_disposition => 'inline; filename="' . "$filename" . '"');
7998 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7999 print "From: " . to_utf8($co{'author'}) . "\n";
8000 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8001 print "Subject: " . to_utf8($co{'title'}) . "\n";
8003 print "X-Git-Tag: $tagname\n" if $tagname;
8004 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8006 foreach my $line (@{$co{'comment'}}) {
8007 print to_utf8($line) . "\n";
8009 print "---\n\n";
8010 } elsif ($format eq 'patch') {
8011 my $filename = basename($project) . "-$hash.patch";
8013 print $cgi->header(
8014 -type => 'text/plain',
8015 -charset => 'utf-8',
8016 -expires => $expires,
8017 -content_disposition => 'inline; filename="' . "$filename" . '"');
8020 # write patch
8021 if ($format eq 'html') {
8022 my $use_parents = !defined $hash_parent ||
8023 $hash_parent eq '-c' || $hash_parent eq '--cc';
8024 git_difftree_body(\@difftree, $hash,
8025 $use_parents ? @{$co{'parents'}} : $hash_parent);
8026 print "<br/>\n";
8028 git_patchset_body($fd, $diff_style,
8029 \@difftree, $hash,
8030 $use_parents ? @{$co{'parents'}} : $hash_parent);
8031 close $fd;
8032 print "</div>\n"; # class="page_body"
8033 git_footer_html();
8035 } elsif ($format eq 'plain') {
8036 local $/ = undef;
8037 print <$fd>;
8038 close $fd
8039 or print "Reading git-diff-tree failed\n";
8040 } elsif ($format eq 'patch') {
8041 local $/ = undef;
8042 print <$fd>;
8043 close $fd
8044 or print "Reading git-format-patch failed\n";
8048 sub git_commitdiff_plain {
8049 git_commitdiff(-format => 'plain');
8052 # format-patch-style patches
8053 sub git_patch {
8054 git_commitdiff(-format => 'patch', -single => 1);
8057 sub git_patches {
8058 git_commitdiff(-format => 'patch');
8061 sub git_history {
8062 git_log_generic('history', \&git_history_body,
8063 $hash_base, $hash_parent_base,
8064 $file_name, $hash);
8067 sub git_search {
8068 $searchtype ||= 'commit';
8070 # check if appropriate features are enabled
8071 gitweb_check_feature('search')
8072 or die_error(403, "Search is disabled");
8073 if ($searchtype eq 'pickaxe') {
8074 # pickaxe may take all resources of your box and run for several minutes
8075 # with every query - so decide by yourself how public you make this feature
8076 gitweb_check_feature('pickaxe')
8077 or die_error(403, "Pickaxe search is disabled");
8079 if ($searchtype eq 'grep') {
8080 # grep search might be potentially CPU-intensive, too
8081 gitweb_check_feature('grep')
8082 or die_error(403, "Grep search is disabled");
8085 if (!defined $searchtext) {
8086 die_error(400, "Text field is empty");
8088 if (!defined $hash) {
8089 $hash = git_get_head_hash($project);
8091 my %co = parse_commit($hash);
8092 if (!%co) {
8093 die_error(404, "Unknown commit object");
8095 if (!defined $page) {
8096 $page = 0;
8099 if ($searchtype eq 'commit' ||
8100 $searchtype eq 'author' ||
8101 $searchtype eq 'committer') {
8102 git_search_message(%co);
8103 } elsif ($searchtype eq 'pickaxe') {
8104 git_search_changes(%co);
8105 } elsif ($searchtype eq 'grep') {
8106 git_search_files(%co);
8107 } else {
8108 die_error(400, "Unknown search type");
8112 sub git_search_help {
8113 git_header_html();
8114 git_print_page_nav('','', $hash,$hash,$hash);
8115 print <<EOT;
8116 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8117 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8118 the pattern entered is recognized as the POSIX extended
8119 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8120 insensitive).</p>
8121 <dl>
8122 <dt><b>commit</b></dt>
8123 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8125 my $have_grep = gitweb_check_feature('grep');
8126 if ($have_grep) {
8127 print <<EOT;
8128 <dt><b>grep</b></dt>
8129 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8130 a different one) are searched for the given pattern. On large trees, this search can take
8131 a while and put some strain on the server, so please use it with some consideration. Note that
8132 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8133 case-sensitive.</dd>
8136 print <<EOT;
8137 <dt><b>author</b></dt>
8138 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8139 <dt><b>committer</b></dt>
8140 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8142 my $have_pickaxe = gitweb_check_feature('pickaxe');
8143 if ($have_pickaxe) {
8144 print <<EOT;
8145 <dt><b>pickaxe</b></dt>
8146 <dd>All commits that caused the string to appear or disappear from any file (changes that
8147 added, removed or "modified" the string) will be listed. This search can take a while and
8148 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8149 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8152 print "</dl>\n";
8153 git_footer_html();
8156 sub git_shortlog {
8157 git_log_generic('shortlog', \&git_shortlog_body,
8158 $hash, $hash_parent);
8161 ## ......................................................................
8162 ## feeds (RSS, Atom; OPML)
8164 sub git_feed {
8165 my $format = shift || 'atom';
8166 my $have_blame = gitweb_check_feature('blame');
8168 # Atom: http://www.atomenabled.org/developers/syndication/
8169 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8170 if ($format ne 'rss' && $format ne 'atom') {
8171 die_error(400, "Unknown web feed format");
8174 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8175 my $head = $hash || 'HEAD';
8176 my @commitlist = parse_commits($head, 150, 0, $file_name);
8178 my %latest_commit;
8179 my %latest_date;
8180 my $content_type = "application/$format+xml";
8181 if (defined $cgi->http('HTTP_ACCEPT') &&
8182 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8183 # browser (feed reader) prefers text/xml
8184 $content_type = 'text/xml';
8186 if (defined($commitlist[0])) {
8187 %latest_commit = %{$commitlist[0]};
8188 my $latest_epoch = $latest_commit{'committer_epoch'};
8189 exit_if_unmodified_since($latest_epoch);
8190 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8192 print $cgi->header(
8193 -type => $content_type,
8194 -charset => 'utf-8',
8195 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8196 -status => '200 OK');
8198 # Optimization: skip generating the body if client asks only
8199 # for Last-Modified date.
8200 return if ($cgi->request_method() eq 'HEAD');
8202 # header variables
8203 my $title = "$site_name - $project/$action";
8204 my $feed_type = 'log';
8205 if (defined $hash) {
8206 $title .= " - '$hash'";
8207 $feed_type = 'branch log';
8208 if (defined $file_name) {
8209 $title .= " :: $file_name";
8210 $feed_type = 'history';
8212 } elsif (defined $file_name) {
8213 $title .= " - $file_name";
8214 $feed_type = 'history';
8216 $title .= " $feed_type";
8217 $title = esc_html($title);
8218 my $descr = git_get_project_description($project);
8219 if (defined $descr) {
8220 $descr = esc_html($descr);
8221 } else {
8222 $descr = "$project " .
8223 ($format eq 'rss' ? 'RSS' : 'Atom') .
8224 " feed";
8226 my $owner = git_get_project_owner($project);
8227 $owner = esc_html($owner);
8229 #header
8230 my $alt_url;
8231 if (defined $file_name) {
8232 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8233 } elsif (defined $hash) {
8234 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8235 } else {
8236 $alt_url = href(-full=>1, action=>"summary");
8238 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8239 if ($format eq 'rss') {
8240 print <<XML;
8241 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8242 <channel>
8244 print "<title>$title</title>\n" .
8245 "<link>$alt_url</link>\n" .
8246 "<description>$descr</description>\n" .
8247 "<language>en</language>\n" .
8248 # project owner is responsible for 'editorial' content
8249 "<managingEditor>$owner</managingEditor>\n";
8250 if (defined $logo || defined $favicon) {
8251 # prefer the logo to the favicon, since RSS
8252 # doesn't allow both
8253 my $img = esc_url($logo || $favicon);
8254 print "<image>\n" .
8255 "<url>$img</url>\n" .
8256 "<title>$title</title>\n" .
8257 "<link>$alt_url</link>\n" .
8258 "</image>\n";
8260 if (%latest_date) {
8261 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8262 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8264 print "<generator>gitweb v.$version/$git_version</generator>\n";
8265 } elsif ($format eq 'atom') {
8266 print <<XML;
8267 <feed xmlns="http://www.w3.org/2005/Atom">
8269 print "<title>$title</title>\n" .
8270 "<subtitle>$descr</subtitle>\n" .
8271 '<link rel="alternate" type="text/html" href="' .
8272 $alt_url . '" />' . "\n" .
8273 '<link rel="self" type="' . $content_type . '" href="' .
8274 $cgi->self_url() . '" />' . "\n" .
8275 "<id>" . href(-full=>1) . "</id>\n" .
8276 # use project owner for feed author
8277 "<author><name>$owner</name></author>\n";
8278 if (defined $favicon) {
8279 print "<icon>" . esc_url($favicon) . "</icon>\n";
8281 if (defined $logo) {
8282 # not twice as wide as tall: 72 x 27 pixels
8283 print "<logo>" . esc_url($logo) . "</logo>\n";
8285 if (! %latest_date) {
8286 # dummy date to keep the feed valid until commits trickle in:
8287 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8288 } else {
8289 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8291 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8294 # contents
8295 for (my $i = 0; $i <= $#commitlist; $i++) {
8296 my %co = %{$commitlist[$i]};
8297 my $commit = $co{'id'};
8298 # we read 150, we always show 30 and the ones more recent than 48 hours
8299 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8300 last;
8302 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8304 # get list of changed files
8305 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8306 $co{'parent'} || "--root",
8307 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8308 or next;
8309 my @difftree = map { chomp; $_ } <$fd>;
8310 close $fd
8311 or next;
8313 # print element (entry, item)
8314 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8315 if ($format eq 'rss') {
8316 print "<item>\n" .
8317 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8318 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8319 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8320 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8321 "<link>$co_url</link>\n" .
8322 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8323 "<content:encoded>" .
8324 "<![CDATA[\n";
8325 } elsif ($format eq 'atom') {
8326 print "<entry>\n" .
8327 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8328 "<updated>$cd{'iso-8601'}</updated>\n" .
8329 "<author>\n" .
8330 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8331 if ($co{'author_email'}) {
8332 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8334 print "</author>\n" .
8335 # use committer for contributor
8336 "<contributor>\n" .
8337 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8338 if ($co{'committer_email'}) {
8339 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8341 print "</contributor>\n" .
8342 "<published>$cd{'iso-8601'}</published>\n" .
8343 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8344 "<id>$co_url</id>\n" .
8345 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8346 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8348 my $comment = $co{'comment'};
8349 print "<pre>\n";
8350 foreach my $line (@$comment) {
8351 $line = esc_html($line);
8352 print "$line\n";
8354 print "</pre><ul>\n";
8355 foreach my $difftree_line (@difftree) {
8356 my %difftree = parse_difftree_raw_line($difftree_line);
8357 next if !$difftree{'from_id'};
8359 my $file = $difftree{'file'} || $difftree{'to_file'};
8361 print "<li>" .
8362 "[" .
8363 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8364 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8365 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8366 file_name=>$file, file_parent=>$difftree{'from_file'}),
8367 -title => "diff"}, 'D');
8368 if ($have_blame) {
8369 print $cgi->a({-href => href(-full=>1, action=>"blame",
8370 file_name=>$file, hash_base=>$commit),
8371 -title => "blame"}, 'B');
8373 # if this is not a feed of a file history
8374 if (!defined $file_name || $file_name ne $file) {
8375 print $cgi->a({-href => href(-full=>1, action=>"history",
8376 file_name=>$file, hash=>$commit),
8377 -title => "history"}, 'H');
8379 $file = esc_path($file);
8380 print "] ".
8381 "$file</li>\n";
8383 if ($format eq 'rss') {
8384 print "</ul>]]>\n" .
8385 "</content:encoded>\n" .
8386 "</item>\n";
8387 } elsif ($format eq 'atom') {
8388 print "</ul>\n</div>\n" .
8389 "</content>\n" .
8390 "</entry>\n";
8394 # end of feed
8395 if ($format eq 'rss') {
8396 print "</channel>\n</rss>\n";
8397 } elsif ($format eq 'atom') {
8398 print "</feed>\n";
8402 sub git_rss {
8403 git_feed('rss');
8406 sub git_atom {
8407 git_feed('atom');
8410 sub git_opml {
8411 my @list = git_get_projects_list($project_filter, $strict_export);
8412 if (!@list) {
8413 die_error(404, "No projects found");
8416 print $cgi->header(
8417 -type => 'text/xml',
8418 -charset => 'utf-8',
8419 -content_disposition => 'inline; filename="opml.xml"');
8421 my $title = esc_html($site_name);
8422 my $filter = " within subdirectory ";
8423 if (defined $project_filter) {
8424 $filter .= esc_html($project_filter);
8425 } else {
8426 $filter = "";
8428 print <<XML;
8429 <?xml version="1.0" encoding="utf-8"?>
8430 <opml version="1.0">
8431 <head>
8432 <title>$title OPML Export$filter</title>
8433 </head>
8434 <body>
8435 <outline text="git RSS feeds">
8438 foreach my $pr (@list) {
8439 my %proj = %$pr;
8440 my $head = git_get_head_hash($proj{'path'});
8441 if (!defined $head) {
8442 next;
8444 $git_dir = "$projectroot/$proj{'path'}";
8445 my %co = parse_commit($head);
8446 if (!%co) {
8447 next;
8450 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8451 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8452 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8453 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8455 print <<XML;
8456 </outline>
8457 </body>
8458 </opml>