Merge commit 'refs/top-bases/t/misc/encoding-opt' into t/misc/encoding-opt
[git/gitweb.git] / gitweb / gitweb.perl
blob922938b9833286fdaf4d2d79921f9829a1e02e86
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 sub configure_as_fcgi {
1300 return if $fcgi_mode;
1302 require CGI::Fast;
1303 our $CGI = 'CGI::Fast';
1305 $fcgi_mode = 1;
1306 $first_request = 0;
1307 my $request_number = 0;
1308 # let each child service 100 requests
1309 our $is_last_request = sub { ++$request_number > 100 };
1311 sub evaluate_argv {
1312 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1313 configure_as_fcgi()
1314 if $script_name =~ /\.fcgi$/
1315 or $auto_fcgi && defined fileno STDIN && fileno STDIN == 0 && getsockname(STDIN);
1317 return unless (@ARGV);
1319 require Getopt::Long;
1320 Getopt::Long::GetOptions(
1321 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1322 'nproc|n=i' => sub {
1323 my ($arg, $val) = @_;
1324 return unless eval { require FCGI::ProcManager; 1; };
1325 my $proc_manager = FCGI::ProcManager->new({
1326 n_processes => $val,
1328 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1329 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1330 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1335 sub run {
1336 evaluate_gitweb_config();
1337 evaluate_encoding();
1338 evaluate_git_version();
1339 my ($mu, $hl, $subroutine) = ($my_uri, $home_link, '');
1340 $subroutine .= '$my_uri = $mu;' if defined $my_uri && $my_uri ne '';
1341 $subroutine .= '$home_link = $hl;' if defined $home_link && $home_link ne '';
1342 $evaluate_uri_force = eval "sub {$subroutine}" if $subroutine;
1343 $first_request = 1;
1344 evaluate_argv();
1346 $pre_listen_hook->()
1347 if $pre_listen_hook;
1349 REQUEST:
1350 while ($cgi = $CGI->new()) {
1351 $pre_dispatch_hook->()
1352 if $pre_dispatch_hook;
1354 run_request();
1356 $post_dispatch_hook->()
1357 if $post_dispatch_hook;
1358 $first_request = 0;
1360 last REQUEST if ($is_last_request->());
1363 DONE_GITWEB:
1367 run();
1369 if (defined caller) {
1370 # wrapped in a subroutine processing requests,
1371 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1372 return;
1373 } else {
1374 # pure CGI script, serving single request
1375 exit;
1378 ## ======================================================================
1379 ## action links
1381 # possible values of extra options
1382 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1383 # -replay => 1 - start from a current view (replay with modifications)
1384 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1385 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1386 sub href {
1387 my %params = @_;
1388 # default is to use -absolute url() i.e. $my_uri
1389 my $href = $params{-full} ? $my_url : $my_uri;
1391 # implicit -replay, must be first of implicit params
1392 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1394 $params{'project'} = $project unless exists $params{'project'};
1396 if ($params{-replay}) {
1397 while (my ($name, $symbol) = each %cgi_param_mapping) {
1398 if (!exists $params{$name}) {
1399 $params{$name} = $input_params{$name};
1404 my $use_pathinfo = gitweb_check_feature('pathinfo');
1405 if (defined $params{'project'} &&
1406 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1407 # try to put as many parameters as possible in PATH_INFO:
1408 # - project name
1409 # - action
1410 # - hash_parent or hash_parent_base:/file_parent
1411 # - hash or hash_base:/filename
1412 # - the snapshot_format as an appropriate suffix
1414 # When the script is the root DirectoryIndex for the domain,
1415 # $href here would be something like http://gitweb.example.com/
1416 # Thus, we strip any trailing / from $href, to spare us double
1417 # slashes in the final URL
1418 $href =~ s,/$,,;
1420 # Then add the project name, if present
1421 $href .= "/".esc_path_info($params{'project'});
1422 delete $params{'project'};
1424 # since we destructively absorb parameters, we keep this
1425 # boolean that remembers if we're handling a snapshot
1426 my $is_snapshot = $params{'action'} eq 'snapshot';
1428 # Summary just uses the project path URL, any other action is
1429 # added to the URL
1430 if (defined $params{'action'}) {
1431 $href .= "/".esc_path_info($params{'action'})
1432 unless $params{'action'} eq 'summary';
1433 delete $params{'action'};
1436 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1437 # stripping nonexistent or useless pieces
1438 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1439 || $params{'hash_parent'} || $params{'hash'});
1440 if (defined $params{'hash_base'}) {
1441 if (defined $params{'hash_parent_base'}) {
1442 $href .= esc_path_info($params{'hash_parent_base'});
1443 # skip the file_parent if it's the same as the file_name
1444 if (defined $params{'file_parent'}) {
1445 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1446 delete $params{'file_parent'};
1447 } elsif ($params{'file_parent'} !~ /\.\./) {
1448 $href .= ":/".esc_path_info($params{'file_parent'});
1449 delete $params{'file_parent'};
1452 $href .= "..";
1453 delete $params{'hash_parent'};
1454 delete $params{'hash_parent_base'};
1455 } elsif (defined $params{'hash_parent'}) {
1456 $href .= esc_path_info($params{'hash_parent'}). "..";
1457 delete $params{'hash_parent'};
1460 $href .= esc_path_info($params{'hash_base'});
1461 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1462 $href .= ":/".esc_path_info($params{'file_name'});
1463 delete $params{'file_name'};
1465 delete $params{'hash'};
1466 delete $params{'hash_base'};
1467 } elsif (defined $params{'hash'}) {
1468 $href .= esc_path_info($params{'hash'});
1469 delete $params{'hash'};
1472 # If the action was a snapshot, we can absorb the
1473 # snapshot_format parameter too
1474 if ($is_snapshot) {
1475 my $fmt = $params{'snapshot_format'};
1476 # snapshot_format should always be defined when href()
1477 # is called, but just in case some code forgets, we
1478 # fall back to the default
1479 $fmt ||= $snapshot_fmts[0];
1480 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1481 delete $params{'snapshot_format'};
1485 # now encode the parameters explicitly
1486 my @result = ();
1487 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1488 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1489 if (defined $params{$name}) {
1490 if (ref($params{$name}) eq "ARRAY") {
1491 foreach my $par (@{$params{$name}}) {
1492 push @result, $symbol . "=" . esc_param($par);
1494 } else {
1495 push @result, $symbol . "=" . esc_param($params{$name});
1499 $href .= "?" . join(';', @result) if scalar @result;
1501 # final transformation: trailing spaces must be escaped (URI-encoded)
1502 $href =~ s/(\s+)$/CGI::escape($1)/e;
1504 if ($params{-anchor}) {
1505 $href .= "#".esc_param($params{-anchor});
1508 return $href;
1512 ## ======================================================================
1513 ## validation, quoting/unquoting and escaping
1515 sub is_valid_action {
1516 my $input = shift;
1517 return undef unless exists $actions{$input};
1518 return 1;
1521 sub is_valid_project {
1522 my $input = shift;
1524 return unless defined $input;
1525 if (!is_valid_pathname($input) ||
1526 !(-d "$projectroot/$input") ||
1527 !check_export_ok("$projectroot/$input") ||
1528 ($strict_export && !project_in_list($input))) {
1529 return undef;
1530 } else {
1531 return 1;
1535 sub is_valid_pathname {
1536 my $input = shift;
1538 return undef unless defined $input;
1539 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1540 # at the beginning, at the end, and between slashes.
1541 # also this catches doubled slashes
1542 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1543 return undef;
1545 # no null characters
1546 if ($input =~ m!\0!) {
1547 return undef;
1549 return 1;
1552 sub is_valid_ref_format {
1553 my $input = shift;
1555 return undef unless defined $input;
1556 # restrictions on ref name according to git-check-ref-format
1557 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1558 return undef;
1560 return 1;
1563 sub is_valid_refname {
1564 my $input = shift;
1566 return undef unless defined $input;
1567 # textual hashes are O.K.
1568 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1569 return 1;
1571 # it must be correct pathname
1572 is_valid_pathname($input) or return undef;
1573 # check git-check-ref-format restrictions
1574 is_valid_ref_format($input) or return undef;
1575 return 1;
1578 # decode sequences of octets in utf8 into Perl's internal form,
1579 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1580 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1581 sub to_utf8 {
1582 my $str = shift;
1583 return undef unless defined $str;
1585 if (utf8::is_utf8($str) || utf8::decode($str)) {
1586 return $str;
1587 } else {
1588 return $encode_object->decode($str, Encode::FB_DEFAULT);
1592 # quote unsafe chars, but keep the slash, even when it's not
1593 # correct, but quoted slashes look too horrible in bookmarks
1594 sub esc_param {
1595 my $str = shift;
1596 return undef unless defined $str;
1597 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1598 $str =~ s/ /\+/g;
1599 return $str;
1602 # the quoting rules for path_info fragment are slightly different
1603 sub esc_path_info {
1604 my $str = shift;
1605 return undef unless defined $str;
1607 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1608 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1610 return $str;
1613 # quote unsafe chars in whole URL, so some characters cannot be quoted
1614 sub esc_url {
1615 my $str = shift;
1616 return undef unless defined $str;
1617 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1618 $str =~ s/ /\+/g;
1619 return $str;
1622 # quote unsafe characters in HTML attributes
1623 sub esc_attr {
1625 # for XHTML conformance escaping '"' to '&quot;' is not enough
1626 return esc_html(@_);
1629 # replace invalid utf8 character with SUBSTITUTION sequence
1630 sub esc_html {
1631 my $str = shift;
1632 my %opts = @_;
1634 return undef unless defined $str;
1636 $str = to_utf8($str);
1637 $str = $cgi->escapeHTML($str);
1638 if ($opts{'-nbsp'}) {
1639 $str =~ s/ /&nbsp;/g;
1641 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1642 return $str;
1645 # quote control characters and escape filename to HTML
1646 sub esc_path {
1647 my $str = shift;
1648 my %opts = @_;
1650 return undef unless defined $str;
1652 $str = to_utf8($str);
1653 $str = $cgi->escapeHTML($str);
1654 if ($opts{'-nbsp'}) {
1655 $str =~ s/ /&nbsp;/g;
1657 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1658 return $str;
1661 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1662 sub sanitize {
1663 my $str = shift;
1665 return undef unless defined $str;
1667 $str = to_utf8($str);
1668 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1669 return $str;
1672 # Make control characters "printable", using character escape codes (CEC)
1673 sub quot_cec {
1674 my $cntrl = shift;
1675 my %opts = @_;
1676 my %es = ( # character escape codes, aka escape sequences
1677 "\t" => '\t', # tab (HT)
1678 "\n" => '\n', # line feed (LF)
1679 "\r" => '\r', # carrige return (CR)
1680 "\f" => '\f', # form feed (FF)
1681 "\b" => '\b', # backspace (BS)
1682 "\a" => '\a', # alarm (bell) (BEL)
1683 "\e" => '\e', # escape (ESC)
1684 "\013" => '\v', # vertical tab (VT)
1685 "\000" => '\0', # nul character (NUL)
1687 my $chr = ( (exists $es{$cntrl})
1688 ? $es{$cntrl}
1689 : sprintf('\%2x', ord($cntrl)) );
1690 if ($opts{-nohtml}) {
1691 return $chr;
1692 } else {
1693 return "<span class=\"cntrl\">$chr</span>";
1697 # Alternatively use unicode control pictures codepoints,
1698 # Unicode "printable representation" (PR)
1699 sub quot_upr {
1700 my $cntrl = shift;
1701 my %opts = @_;
1703 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1704 if ($opts{-nohtml}) {
1705 return $chr;
1706 } else {
1707 return "<span class=\"cntrl\">$chr</span>";
1711 # git may return quoted and escaped filenames
1712 sub unquote {
1713 my $str = shift;
1715 sub unq {
1716 my $seq = shift;
1717 my %es = ( # character escape codes, aka escape sequences
1718 't' => "\t", # tab (HT, TAB)
1719 'n' => "\n", # newline (NL)
1720 'r' => "\r", # return (CR)
1721 'f' => "\f", # form feed (FF)
1722 'b' => "\b", # backspace (BS)
1723 'a' => "\a", # alarm (bell) (BEL)
1724 'e' => "\e", # escape (ESC)
1725 'v' => "\013", # vertical tab (VT)
1728 if ($seq =~ m/^[0-7]{1,3}$/) {
1729 # octal char sequence
1730 return chr(oct($seq));
1731 } elsif (exists $es{$seq}) {
1732 # C escape sequence, aka character escape code
1733 return $es{$seq};
1735 # quoted ordinary character
1736 return $seq;
1739 if ($str =~ m/^"(.*)"$/) {
1740 # needs unquoting
1741 $str = $1;
1742 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1744 return $str;
1747 # escape tabs (convert tabs to spaces)
1748 sub untabify {
1749 my $line = shift;
1751 while ((my $pos = index($line, "\t")) != -1) {
1752 if (my $count = (8 - ($pos % 8))) {
1753 my $spaces = ' ' x $count;
1754 $line =~ s/\t/$spaces/;
1758 return $line;
1761 sub project_in_list {
1762 my $project = shift;
1763 my @list = git_get_projects_list();
1764 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1767 ## ----------------------------------------------------------------------
1768 ## HTML aware string manipulation
1770 # Try to chop given string on a word boundary between position
1771 # $len and $len+$add_len. If there is no word boundary there,
1772 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1773 # (marking chopped part) would be longer than given string.
1774 sub chop_str {
1775 my $str = shift;
1776 my $len = shift;
1777 my $add_len = shift || 10;
1778 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1780 # Make sure perl knows it is utf8 encoded so we don't
1781 # cut in the middle of a utf8 multibyte char.
1782 $str = to_utf8($str);
1784 # allow only $len chars, but don't cut a word if it would fit in $add_len
1785 # if it doesn't fit, cut it if it's still longer than the dots we would add
1786 # remove chopped character entities entirely
1788 # when chopping in the middle, distribute $len into left and right part
1789 # return early if chopping wouldn't make string shorter
1790 if ($where eq 'center') {
1791 return $str if ($len + 5 >= length($str)); # filler is length 5
1792 $len = int($len/2);
1793 } else {
1794 return $str if ($len + 4 >= length($str)); # filler is length 4
1797 # regexps: ending and beginning with word part up to $add_len
1798 my $endre = qr/.{$len}\w{0,$add_len}/;
1799 my $begre = qr/\w{0,$add_len}.{$len}/;
1801 if ($where eq 'left') {
1802 $str =~ m/^(.*?)($begre)$/;
1803 my ($lead, $body) = ($1, $2);
1804 if (length($lead) > 4) {
1805 $lead = " ...";
1807 return "$lead$body";
1809 } elsif ($where eq 'center') {
1810 $str =~ m/^($endre)(.*)$/;
1811 my ($left, $str) = ($1, $2);
1812 $str =~ m/^(.*?)($begre)$/;
1813 my ($mid, $right) = ($1, $2);
1814 if (length($mid) > 5) {
1815 $mid = " ... ";
1817 return "$left$mid$right";
1819 } else {
1820 $str =~ m/^($endre)(.*)$/;
1821 my $body = $1;
1822 my $tail = $2;
1823 if (length($tail) > 4) {
1824 $tail = "... ";
1826 return "$body$tail";
1830 # takes the same arguments as chop_str, but also wraps a <span> around the
1831 # result with a title attribute if it does get chopped. Additionally, the
1832 # string is HTML-escaped.
1833 sub chop_and_escape_str {
1834 my ($str) = @_;
1836 my $chopped = chop_str(@_);
1837 $str = to_utf8($str);
1838 if ($chopped eq $str) {
1839 return esc_html($chopped);
1840 } else {
1841 $str =~ s/[[:cntrl:]]/?/g;
1842 return $cgi->span({-title=>$str}, esc_html($chopped));
1846 # Highlight selected fragments of string, using given CSS class,
1847 # and escape HTML. It is assumed that fragments do not overlap.
1848 # Regions are passed as list of pairs (array references).
1850 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1851 # '<span class="mark">foo</span>bar'
1852 sub esc_html_hl_regions {
1853 my ($str, $css_class, @sel) = @_;
1854 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1855 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1856 return esc_html($str, %opts) unless @sel;
1858 my $out = '';
1859 my $pos = 0;
1861 for my $s (@sel) {
1862 my ($begin, $end) = @$s;
1864 # Don't create empty <span> elements.
1865 next if $end <= $begin;
1867 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1868 %opts);
1870 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1871 if ($begin - $pos > 0);
1872 $out .= $cgi->span({-class => $css_class}, $escaped);
1874 $pos = $end;
1876 $out .= esc_html(substr($str, $pos), %opts)
1877 if ($pos < length($str));
1879 return $out;
1882 # return positions of beginning and end of each match
1883 sub matchpos_list {
1884 my ($str, $regexp) = @_;
1885 return unless (defined $str && defined $regexp);
1887 my @matches;
1888 while ($str =~ /$regexp/g) {
1889 push @matches, [$-[0], $+[0]];
1891 return @matches;
1894 # highlight match (if any), and escape HTML
1895 sub esc_html_match_hl {
1896 my ($str, $regexp) = @_;
1897 return esc_html($str) unless defined $regexp;
1899 my @matches = matchpos_list($str, $regexp);
1900 return esc_html($str) unless @matches;
1902 return esc_html_hl_regions($str, 'match', @matches);
1906 # highlight match (if any) of shortened string, and escape HTML
1907 sub esc_html_match_hl_chopped {
1908 my ($str, $chopped, $regexp) = @_;
1909 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1911 my @matches = matchpos_list($str, $regexp);
1912 return esc_html($chopped) unless @matches;
1914 # filter matches so that we mark chopped string
1915 my $tail = "... "; # see chop_str
1916 unless ($chopped =~ s/\Q$tail\E$//) {
1917 $tail = '';
1919 my $chop_len = length($chopped);
1920 my $tail_len = length($tail);
1921 my @filtered;
1923 for my $m (@matches) {
1924 if ($m->[0] > $chop_len) {
1925 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1926 last;
1927 } elsif ($m->[1] > $chop_len) {
1928 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1929 last;
1931 push @filtered, $m;
1934 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1937 ## ----------------------------------------------------------------------
1938 ## functions returning short strings
1940 # CSS class for given age value (in seconds)
1941 sub age_class {
1942 my $age = shift;
1944 if (!defined $age) {
1945 return "noage";
1946 } elsif ($age < 60*60*2) {
1947 return "age0";
1948 } elsif ($age < 60*60*24*2) {
1949 return "age1";
1950 } else {
1951 return "age2";
1955 # convert age in seconds to "nn units ago" string
1956 sub age_string {
1957 my $age = shift;
1958 my $age_str;
1960 if ($age > 60*60*24*365*2) {
1961 $age_str = (int $age/60/60/24/365);
1962 $age_str .= " years ago";
1963 } elsif ($age > 60*60*24*(365/12)*2) {
1964 $age_str = int $age/60/60/24/(365/12);
1965 $age_str .= " months ago";
1966 } elsif ($age > 60*60*24*7*2) {
1967 $age_str = int $age/60/60/24/7;
1968 $age_str .= " weeks ago";
1969 } elsif ($age > 60*60*24*2) {
1970 $age_str = int $age/60/60/24;
1971 $age_str .= " days ago";
1972 } elsif ($age > 60*60*2) {
1973 $age_str = int $age/60/60;
1974 $age_str .= " hours ago";
1975 } elsif ($age > 60*2) {
1976 $age_str = int $age/60;
1977 $age_str .= " min ago";
1978 } elsif ($age > 2) {
1979 $age_str = int $age;
1980 $age_str .= " sec ago";
1981 } else {
1982 $age_str .= " right now";
1984 return $age_str;
1987 use constant {
1988 S_IFINVALID => 0030000,
1989 S_IFGITLINK => 0160000,
1992 # submodule/subproject, a commit object reference
1993 sub S_ISGITLINK {
1994 my $mode = shift;
1996 return (($mode & S_IFMT) == S_IFGITLINK)
1999 # convert file mode in octal to symbolic file mode string
2000 sub mode_str {
2001 my $mode = oct shift;
2003 if (S_ISGITLINK($mode)) {
2004 return 'm---------';
2005 } elsif (S_ISDIR($mode & S_IFMT)) {
2006 return 'drwxr-xr-x';
2007 } elsif (S_ISLNK($mode)) {
2008 return 'lrwxrwxrwx';
2009 } elsif (S_ISREG($mode)) {
2010 # git cares only about the executable bit
2011 if ($mode & S_IXUSR) {
2012 return '-rwxr-xr-x';
2013 } else {
2014 return '-rw-r--r--';
2016 } else {
2017 return '----------';
2021 # convert file mode in octal to file type string
2022 sub file_type {
2023 my $mode = shift;
2025 if ($mode !~ m/^[0-7]+$/) {
2026 return $mode;
2027 } else {
2028 $mode = oct $mode;
2031 if (S_ISGITLINK($mode)) {
2032 return "submodule";
2033 } elsif (S_ISDIR($mode & S_IFMT)) {
2034 return "directory";
2035 } elsif (S_ISLNK($mode)) {
2036 return "symlink";
2037 } elsif (S_ISREG($mode)) {
2038 return "file";
2039 } else {
2040 return "unknown";
2044 # convert file mode in octal to file type description string
2045 sub file_type_long {
2046 my $mode = shift;
2048 if ($mode !~ m/^[0-7]+$/) {
2049 return $mode;
2050 } else {
2051 $mode = oct $mode;
2054 if (S_ISGITLINK($mode)) {
2055 return "submodule";
2056 } elsif (S_ISDIR($mode & S_IFMT)) {
2057 return "directory";
2058 } elsif (S_ISLNK($mode)) {
2059 return "symlink";
2060 } elsif (S_ISREG($mode)) {
2061 if ($mode & S_IXUSR) {
2062 return "executable";
2063 } else {
2064 return "file";
2066 } else {
2067 return "unknown";
2072 ## ----------------------------------------------------------------------
2073 ## functions returning short HTML fragments, or transforming HTML fragments
2074 ## which don't belong to other sections
2076 # format line of commit message.
2077 sub format_log_line_html {
2078 my $line = shift;
2080 $line = esc_html($line, -nbsp=>1);
2081 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2082 $cgi->a({-href => href(action=>"object", hash=>$1),
2083 -class => "text"}, $1);
2084 }eg;
2086 return $line;
2089 # format marker of refs pointing to given object
2091 # the destination action is chosen based on object type and current context:
2092 # - for annotated tags, we choose the tag view unless it's the current view
2093 # already, in which case we go to shortlog view
2094 # - for other refs, we keep the current view if we're in history, shortlog or
2095 # log view, and select shortlog otherwise
2096 sub format_ref_marker {
2097 my ($refs, $id) = @_;
2098 my $markers = '';
2100 if (defined $refs->{$id}) {
2101 foreach my $ref (@{$refs->{$id}}) {
2102 # this code exploits the fact that non-lightweight tags are the
2103 # only indirect objects, and that they are the only objects for which
2104 # we want to use tag instead of shortlog as action
2105 my ($type, $name) = qw();
2106 my $indirect = ($ref =~ s/\^\{\}$//);
2107 # e.g. tags/v2.6.11 or heads/next
2108 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2109 $type = $1;
2110 $name = $2;
2111 } else {
2112 $type = "ref";
2113 $name = $ref;
2116 my $class = $type;
2117 $class .= " indirect" if $indirect;
2119 my $dest_action = "shortlog";
2121 if ($indirect) {
2122 $dest_action = "tag" unless $action eq "tag";
2123 } elsif ($action =~ /^(history|(short)?log)$/) {
2124 $dest_action = $action;
2127 my $dest = "";
2128 $dest .= "refs/" unless $ref =~ m!^refs/!;
2129 $dest .= $ref;
2131 my $link = $cgi->a({
2132 -href => href(
2133 action=>$dest_action,
2134 hash=>$dest
2135 )}, $name);
2137 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2138 $link . "</span>";
2142 if ($markers) {
2143 return ' <span class="refs">'. $markers . '</span>';
2144 } else {
2145 return "";
2149 # format, perhaps shortened and with markers, title line
2150 sub format_subject_html {
2151 my ($long, $short, $href, $extra) = @_;
2152 $extra = '' unless defined($extra);
2154 if (length($short) < length($long)) {
2155 $long =~ s/[[:cntrl:]]/?/g;
2156 return $cgi->a({-href => $href, -class => "list subject",
2157 -title => to_utf8($long)},
2158 esc_html($short)) . $extra;
2159 } else {
2160 return $cgi->a({-href => $href, -class => "list subject"},
2161 esc_html($long)) . $extra;
2165 # Rather than recomputing the url for an email multiple times, we cache it
2166 # after the first hit. This gives a visible benefit in views where the avatar
2167 # for the same email is used repeatedly (e.g. shortlog).
2168 # The cache is shared by all avatar engines (currently gravatar only), which
2169 # are free to use it as preferred. Since only one avatar engine is used for any
2170 # given page, there's no risk for cache conflicts.
2171 our %avatar_cache = ();
2173 # Compute the picon url for a given email, by using the picon search service over at
2174 # http://www.cs.indiana.edu/picons/search.html
2175 sub picon_url {
2176 my $email = lc shift;
2177 if (!$avatar_cache{$email}) {
2178 my ($user, $domain) = split('@', $email);
2179 $avatar_cache{$email} =
2180 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2181 "$domain/$user/" .
2182 "users+domains+unknown/up/single";
2184 return $avatar_cache{$email};
2187 # Compute the gravatar url for a given email, if it's not in the cache already.
2188 # Gravatar stores only the part of the URL before the size, since that's the
2189 # one computationally more expensive. This also allows reuse of the cache for
2190 # different sizes (for this particular engine).
2191 sub gravatar_url {
2192 my $email = lc shift;
2193 my $size = shift;
2194 $avatar_cache{$email} ||=
2195 "//www.gravatar.com/avatar/" .
2196 Digest::MD5::md5_hex($email) . "?s=";
2197 return $avatar_cache{$email} . $size;
2200 # Insert an avatar for the given $email at the given $size if the feature
2201 # is enabled.
2202 sub git_get_avatar {
2203 my ($email, %opts) = @_;
2204 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2205 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2206 $opts{-size} ||= 'default';
2207 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2208 my $url = "";
2209 if ($git_avatar eq 'gravatar') {
2210 $url = gravatar_url($email, $size);
2211 } elsif ($git_avatar eq 'picon') {
2212 $url = picon_url($email);
2214 # Other providers can be added by extending the if chain, defining $url
2215 # as needed. If no variant puts something in $url, we assume avatars
2216 # are completely disabled/unavailable.
2217 if ($url) {
2218 return $pre_white .
2219 "<img width=\"$size\" " .
2220 "class=\"avatar\" " .
2221 "src=\"".esc_url($url)."\" " .
2222 "alt=\"\" " .
2223 "/>" . $post_white;
2224 } else {
2225 return "";
2229 sub format_search_author {
2230 my ($author, $searchtype, $displaytext) = @_;
2231 my $have_search = gitweb_check_feature('search');
2233 if ($have_search) {
2234 my $performed = "";
2235 if ($searchtype eq 'author') {
2236 $performed = "authored";
2237 } elsif ($searchtype eq 'committer') {
2238 $performed = "committed";
2241 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2242 searchtext=>$author,
2243 searchtype=>$searchtype), class=>"list",
2244 title=>"Search for commits $performed by $author"},
2245 $displaytext);
2247 } else {
2248 return $displaytext;
2252 # format the author name of the given commit with the given tag
2253 # the author name is chopped and escaped according to the other
2254 # optional parameters (see chop_str).
2255 sub format_author_html {
2256 my $tag = shift;
2257 my $co = shift;
2258 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2259 return "<$tag class=\"author\">" .
2260 format_search_author($co->{'author_name'}, "author",
2261 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2262 $author) .
2263 "</$tag>";
2266 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2267 sub format_git_diff_header_line {
2268 my $line = shift;
2269 my $diffinfo = shift;
2270 my ($from, $to) = @_;
2272 if ($diffinfo->{'nparents'}) {
2273 # combined diff
2274 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2275 if ($to->{'href'}) {
2276 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2277 esc_path($to->{'file'}));
2278 } else { # file was deleted (no href)
2279 $line .= esc_path($to->{'file'});
2281 } else {
2282 # "ordinary" diff
2283 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2284 if ($from->{'href'}) {
2285 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2286 'a/' . esc_path($from->{'file'}));
2287 } else { # file was added (no href)
2288 $line .= 'a/' . esc_path($from->{'file'});
2290 $line .= ' ';
2291 if ($to->{'href'}) {
2292 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2293 'b/' . esc_path($to->{'file'}));
2294 } else { # file was deleted
2295 $line .= 'b/' . esc_path($to->{'file'});
2299 return "<div class=\"diff header\">$line</div>\n";
2302 # format extended diff header line, before patch itself
2303 sub format_extended_diff_header_line {
2304 my $line = shift;
2305 my $diffinfo = shift;
2306 my ($from, $to) = @_;
2308 # match <path>
2309 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2310 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2311 esc_path($from->{'file'}));
2313 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2314 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2315 esc_path($to->{'file'}));
2317 # match single <mode>
2318 if ($line =~ m/\s(\d{6})$/) {
2319 $line .= '<span class="info"> (' .
2320 file_type_long($1) .
2321 ')</span>';
2323 # match <hash>
2324 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2325 # can match only for combined diff
2326 $line = 'index ';
2327 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2328 if ($from->{'href'}[$i]) {
2329 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2330 -class=>"hash"},
2331 substr($diffinfo->{'from_id'}[$i],0,7));
2332 } else {
2333 $line .= '0' x 7;
2335 # separator
2336 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2338 $line .= '..';
2339 if ($to->{'href'}) {
2340 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2341 substr($diffinfo->{'to_id'},0,7));
2342 } else {
2343 $line .= '0' x 7;
2346 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2347 # can match only for ordinary diff
2348 my ($from_link, $to_link);
2349 if ($from->{'href'}) {
2350 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2351 substr($diffinfo->{'from_id'},0,7));
2352 } else {
2353 $from_link = '0' x 7;
2355 if ($to->{'href'}) {
2356 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2357 substr($diffinfo->{'to_id'},0,7));
2358 } else {
2359 $to_link = '0' x 7;
2361 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2362 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2365 return $line . "<br/>\n";
2368 # format from-file/to-file diff header
2369 sub format_diff_from_to_header {
2370 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2371 my $line;
2372 my $result = '';
2374 $line = $from_line;
2375 #assert($line =~ m/^---/) if DEBUG;
2376 # no extra formatting for "^--- /dev/null"
2377 if (! $diffinfo->{'nparents'}) {
2378 # ordinary (single parent) diff
2379 if ($line =~ m!^--- "?a/!) {
2380 if ($from->{'href'}) {
2381 $line = '--- a/' .
2382 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2383 esc_path($from->{'file'}));
2384 } else {
2385 $line = '--- a/' .
2386 esc_path($from->{'file'});
2389 $result .= qq!<div class="diff from_file">$line</div>\n!;
2391 } else {
2392 # combined diff (merge commit)
2393 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2394 if ($from->{'href'}[$i]) {
2395 $line = '--- ' .
2396 $cgi->a({-href=>href(action=>"blobdiff",
2397 hash_parent=>$diffinfo->{'from_id'}[$i],
2398 hash_parent_base=>$parents[$i],
2399 file_parent=>$from->{'file'}[$i],
2400 hash=>$diffinfo->{'to_id'},
2401 hash_base=>$hash,
2402 file_name=>$to->{'file'}),
2403 -class=>"path",
2404 -title=>"diff" . ($i+1)},
2405 $i+1) .
2406 '/' .
2407 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2408 esc_path($from->{'file'}[$i]));
2409 } else {
2410 $line = '--- /dev/null';
2412 $result .= qq!<div class="diff from_file">$line</div>\n!;
2416 $line = $to_line;
2417 #assert($line =~ m/^\+\+\+/) if DEBUG;
2418 # no extra formatting for "^+++ /dev/null"
2419 if ($line =~ m!^\+\+\+ "?b/!) {
2420 if ($to->{'href'}) {
2421 $line = '+++ b/' .
2422 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2423 esc_path($to->{'file'}));
2424 } else {
2425 $line = '+++ b/' .
2426 esc_path($to->{'file'});
2429 $result .= qq!<div class="diff to_file">$line</div>\n!;
2431 return $result;
2434 # create note for patch simplified by combined diff
2435 sub format_diff_cc_simplified {
2436 my ($diffinfo, @parents) = @_;
2437 my $result = '';
2439 $result .= "<div class=\"diff header\">" .
2440 "diff --cc ";
2441 if (!is_deleted($diffinfo)) {
2442 $result .= $cgi->a({-href => href(action=>"blob",
2443 hash_base=>$hash,
2444 hash=>$diffinfo->{'to_id'},
2445 file_name=>$diffinfo->{'to_file'}),
2446 -class => "path"},
2447 esc_path($diffinfo->{'to_file'}));
2448 } else {
2449 $result .= esc_path($diffinfo->{'to_file'});
2451 $result .= "</div>\n" . # class="diff header"
2452 "<div class=\"diff nodifferences\">" .
2453 "Simple merge" .
2454 "</div>\n"; # class="diff nodifferences"
2456 return $result;
2459 sub diff_line_class {
2460 my ($line, $from, $to) = @_;
2462 # ordinary diff
2463 my $num_sign = 1;
2464 # combined diff
2465 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2466 $num_sign = scalar @{$from->{'href'}};
2469 my @diff_line_classifier = (
2470 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2471 { regexp => qr/^\\/, class => "incomplete" },
2472 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2473 # classifier for context must come before classifier add/rem,
2474 # or we would have to use more complicated regexp, for example
2475 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2476 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2477 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2479 for my $clsfy (@diff_line_classifier) {
2480 return $clsfy->{'class'}
2481 if ($line =~ $clsfy->{'regexp'});
2484 # fallback
2485 return "";
2488 # assumes that $from and $to are defined and correctly filled,
2489 # and that $line holds a line of chunk header for unified diff
2490 sub format_unidiff_chunk_header {
2491 my ($line, $from, $to) = @_;
2493 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2494 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2496 $from_lines = 0 unless defined $from_lines;
2497 $to_lines = 0 unless defined $to_lines;
2499 if ($from->{'href'}) {
2500 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2501 -class=>"list"}, $from_text);
2503 if ($to->{'href'}) {
2504 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2505 -class=>"list"}, $to_text);
2507 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2508 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2509 return $line;
2512 # assumes that $from and $to are defined and correctly filled,
2513 # and that $line holds a line of chunk header for combined diff
2514 sub format_cc_diff_chunk_header {
2515 my ($line, $from, $to) = @_;
2517 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2518 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2520 @from_text = split(' ', $ranges);
2521 for (my $i = 0; $i < @from_text; ++$i) {
2522 ($from_start[$i], $from_nlines[$i]) =
2523 (split(',', substr($from_text[$i], 1)), 0);
2526 $to_text = pop @from_text;
2527 $to_start = pop @from_start;
2528 $to_nlines = pop @from_nlines;
2530 $line = "<span class=\"chunk_info\">$prefix ";
2531 for (my $i = 0; $i < @from_text; ++$i) {
2532 if ($from->{'href'}[$i]) {
2533 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2534 -class=>"list"}, $from_text[$i]);
2535 } else {
2536 $line .= $from_text[$i];
2538 $line .= " ";
2540 if ($to->{'href'}) {
2541 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2542 -class=>"list"}, $to_text);
2543 } else {
2544 $line .= $to_text;
2546 $line .= " $prefix</span>" .
2547 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2548 return $line;
2551 # process patch (diff) line (not to be used for diff headers),
2552 # returning HTML-formatted (but not wrapped) line.
2553 # If the line is passed as a reference, it is treated as HTML and not
2554 # esc_html()'ed.
2555 sub format_diff_line {
2556 my ($line, $diff_class, $from, $to) = @_;
2558 if (ref($line)) {
2559 $line = $$line;
2560 } else {
2561 chomp $line;
2562 $line = untabify($line);
2564 if ($from && $to && $line =~ m/^\@{2} /) {
2565 $line = format_unidiff_chunk_header($line, $from, $to);
2566 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2567 $line = format_cc_diff_chunk_header($line, $from, $to);
2568 } else {
2569 $line = esc_html($line, -nbsp=>1);
2573 my $diff_classes = "diff";
2574 $diff_classes .= " $diff_class" if ($diff_class);
2575 $line = "<div class=\"$diff_classes\">$line</div>\n";
2577 return $line;
2580 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2581 # linked. Pass the hash of the tree/commit to snapshot.
2582 sub format_snapshot_links {
2583 my ($hash) = @_;
2584 my $num_fmts = @snapshot_fmts;
2585 if ($num_fmts > 1) {
2586 # A parenthesized list of links bearing format names.
2587 # e.g. "snapshot (_tar.gz_ _zip_)"
2588 return "snapshot (" . join(' ', map
2589 $cgi->a({
2590 -href => href(
2591 action=>"snapshot",
2592 hash=>$hash,
2593 snapshot_format=>$_
2595 }, $known_snapshot_formats{$_}{'display'})
2596 , @snapshot_fmts) . ")";
2597 } elsif ($num_fmts == 1) {
2598 # A single "snapshot" link whose tooltip bears the format name.
2599 # i.e. "_snapshot_"
2600 my ($fmt) = @snapshot_fmts;
2601 return
2602 $cgi->a({
2603 -href => href(
2604 action=>"snapshot",
2605 hash=>$hash,
2606 snapshot_format=>$fmt
2608 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2609 }, "snapshot");
2610 } else { # $num_fmts == 0
2611 return undef;
2615 ## ......................................................................
2616 ## functions returning values to be passed, perhaps after some
2617 ## transformation, to other functions; e.g. returning arguments to href()
2619 # returns hash to be passed to href to generate gitweb URL
2620 # in -title key it returns description of link
2621 sub get_feed_info {
2622 my $format = shift || 'Atom';
2623 my %res = (action => lc($format));
2624 my $matched_ref = 0;
2626 # feed links are possible only for project views
2627 return unless (defined $project);
2628 # some views should link to OPML, or to generic project feed,
2629 # or don't have specific feed yet (so they should use generic)
2630 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2632 my $branch = undef;
2633 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2634 # (fullname) to differentiate from tag links; this also makes
2635 # possible to detect branch links
2636 for my $ref (get_branch_refs()) {
2637 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2638 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2639 $branch = $1;
2640 $matched_ref = $ref;
2641 last;
2644 # find log type for feed description (title)
2645 my $type = 'log';
2646 if (defined $file_name) {
2647 $type = "history of $file_name";
2648 $type .= "/" if ($action eq 'tree');
2649 $type .= " on '$branch'" if (defined $branch);
2650 } else {
2651 $type = "log of $branch" if (defined $branch);
2654 $res{-title} = $type;
2655 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2656 $res{'file_name'} = $file_name;
2658 return %res;
2661 ## ----------------------------------------------------------------------
2662 ## git utility subroutines, invoking git commands
2664 # returns path to the core git executable and the --git-dir parameter as list
2665 sub git_cmd {
2666 $number_of_git_cmds++;
2667 return $GIT, '--git-dir='.$git_dir;
2670 # quote the given arguments for passing them to the shell
2671 # quote_command("command", "arg 1", "arg with ' and ! characters")
2672 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2673 # Try to avoid using this function wherever possible.
2674 sub quote_command {
2675 return join(' ',
2676 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2679 # get HEAD ref of given project as hash
2680 sub git_get_head_hash {
2681 return git_get_full_hash(shift, 'HEAD');
2684 sub git_get_full_hash {
2685 return git_get_hash(@_);
2688 sub git_get_short_hash {
2689 return git_get_hash(@_, '--short=7');
2692 sub git_get_hash {
2693 my ($project, $hash, @options) = @_;
2694 my $o_git_dir = $git_dir;
2695 my $retval = undef;
2696 $git_dir = "$projectroot/$project";
2697 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2698 '--verify', '-q', @options, $hash) {
2699 $retval = <$fd>;
2700 chomp $retval if defined $retval;
2701 close $fd;
2703 if (defined $o_git_dir) {
2704 $git_dir = $o_git_dir;
2706 return $retval;
2709 # get type of given object
2710 sub git_get_type {
2711 my $hash = shift;
2713 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2714 my $type = <$fd>;
2715 close $fd or return;
2716 chomp $type;
2717 return $type;
2720 # repository configuration
2721 our $config_file = '';
2722 our %config;
2724 # store multiple values for single key as anonymous array reference
2725 # single values stored directly in the hash, not as [ <value> ]
2726 sub hash_set_multi {
2727 my ($hash, $key, $value) = @_;
2729 if (!exists $hash->{$key}) {
2730 $hash->{$key} = $value;
2731 } elsif (!ref $hash->{$key}) {
2732 $hash->{$key} = [ $hash->{$key}, $value ];
2733 } else {
2734 push @{$hash->{$key}}, $value;
2738 # return hash of git project configuration
2739 # optionally limited to some section, e.g. 'gitweb'
2740 sub git_parse_project_config {
2741 my $section_regexp = shift;
2742 my %config;
2744 local $/ = "\0";
2746 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2747 or return;
2749 while (my $keyval = <$fh>) {
2750 chomp $keyval;
2751 my ($key, $value) = split(/\n/, $keyval, 2);
2753 hash_set_multi(\%config, $key, $value)
2754 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2756 close $fh;
2758 return %config;
2761 # convert config value to boolean: 'true' or 'false'
2762 # no value, number > 0, 'true' and 'yes' values are true
2763 # rest of values are treated as false (never as error)
2764 sub config_to_bool {
2765 my $val = shift;
2767 return 1 if !defined $val; # section.key
2769 # strip leading and trailing whitespace
2770 $val =~ s/^\s+//;
2771 $val =~ s/\s+$//;
2773 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2774 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2777 # convert config value to simple decimal number
2778 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2779 # to be multiplied by 1024, 1048576, or 1073741824
2780 sub config_to_int {
2781 my $val = shift;
2783 # strip leading and trailing whitespace
2784 $val =~ s/^\s+//;
2785 $val =~ s/\s+$//;
2787 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2788 $unit = lc($unit);
2789 # unknown unit is treated as 1
2790 return $num * ($unit eq 'g' ? 1073741824 :
2791 $unit eq 'm' ? 1048576 :
2792 $unit eq 'k' ? 1024 : 1);
2794 return $val;
2797 # convert config value to array reference, if needed
2798 sub config_to_multi {
2799 my $val = shift;
2801 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2804 sub git_get_project_config {
2805 my ($key, $type) = @_;
2807 return unless defined $git_dir;
2809 # key sanity check
2810 return unless ($key);
2811 # only subsection, if exists, is case sensitive,
2812 # and not lowercased by 'git config -z -l'
2813 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2814 $lo =~ s/_//g;
2815 $key = join(".", lc($hi), $mi, lc($lo));
2816 return if ($lo =~ /\W/ || $hi =~ /\W/);
2817 } else {
2818 $key = lc($key);
2819 $key =~ s/_//g;
2820 return if ($key =~ /\W/);
2822 $key =~ s/^gitweb\.//;
2824 # type sanity check
2825 if (defined $type) {
2826 $type =~ s/^--//;
2827 $type = undef
2828 unless ($type eq 'bool' || $type eq 'int');
2831 # get config
2832 if (!defined $config_file ||
2833 $config_file ne "$git_dir/config") {
2834 %config = git_parse_project_config('gitweb');
2835 $config_file = "$git_dir/config";
2838 # check if config variable (key) exists
2839 return unless exists $config{"gitweb.$key"};
2841 # ensure given type
2842 if (!defined $type) {
2843 return $config{"gitweb.$key"};
2844 } elsif ($type eq 'bool') {
2845 # backward compatibility: 'git config --bool' returns true/false
2846 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2847 } elsif ($type eq 'int') {
2848 return config_to_int($config{"gitweb.$key"});
2850 return $config{"gitweb.$key"};
2853 # get hash of given path at given ref
2854 sub git_get_hash_by_path {
2855 my $base = shift;
2856 my $path = shift || return undef;
2857 my $type = shift;
2859 $path =~ s,/+$,,;
2861 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2862 or die_error(500, "Open git-ls-tree failed");
2863 my $line = <$fd>;
2864 close $fd or return undef;
2866 if (!defined $line) {
2867 # there is no tree or hash given by $path at $base
2868 return undef;
2871 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2872 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2873 if (defined $type && $type ne $2) {
2874 # type doesn't match
2875 return undef;
2877 return $3;
2880 # get path of entry with given hash at given tree-ish (ref)
2881 # used to get 'from' filename for combined diff (merge commit) for renames
2882 sub git_get_path_by_hash {
2883 my $base = shift || return;
2884 my $hash = shift || return;
2886 local $/ = "\0";
2888 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2889 or return undef;
2890 while (my $line = <$fd>) {
2891 chomp $line;
2893 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2894 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2895 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2896 close $fd;
2897 return $1;
2900 close $fd;
2901 return undef;
2904 ## ......................................................................
2905 ## git utility functions, directly accessing git repository
2907 # get the value of config variable either from file named as the variable
2908 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2909 # configuration variable in the repository config file.
2910 sub git_get_file_or_project_config {
2911 my ($path, $name) = @_;
2913 $git_dir = "$projectroot/$path";
2914 open my $fd, '<', "$git_dir/$name"
2915 or return git_get_project_config($name);
2916 my $conf = <$fd>;
2917 close $fd;
2918 if (defined $conf) {
2919 chomp $conf;
2921 return $conf;
2924 sub git_get_project_description {
2925 my $path = shift;
2926 return git_get_file_or_project_config($path, 'description');
2929 sub git_get_project_category {
2930 my $path = shift;
2931 return git_get_file_or_project_config($path, 'category');
2935 # supported formats:
2936 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2937 # - if its contents is a number, use it as tag weight,
2938 # - otherwise add a tag with weight 1
2939 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2940 # the same value multiple times increases tag weight
2941 # * `gitweb.ctag' multi-valued repo config variable
2942 sub git_get_project_ctags {
2943 my $project = shift;
2944 my $ctags = {};
2946 $git_dir = "$projectroot/$project";
2947 if (opendir my $dh, "$git_dir/ctags") {
2948 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2949 foreach my $tagfile (@files) {
2950 open my $ct, '<', $tagfile
2951 or next;
2952 my $val = <$ct>;
2953 chomp $val if $val;
2954 close $ct;
2956 (my $ctag = $tagfile) =~ s#.*/##;
2957 if ($val =~ /^\d+$/) {
2958 $ctags->{$ctag} = $val;
2959 } else {
2960 $ctags->{$ctag} = 1;
2963 closedir $dh;
2965 } elsif (open my $fh, '<', "$git_dir/ctags") {
2966 while (my $line = <$fh>) {
2967 chomp $line;
2968 $ctags->{$line}++ if $line;
2970 close $fh;
2972 } else {
2973 my $taglist = config_to_multi(git_get_project_config('ctag'));
2974 foreach my $tag (@$taglist) {
2975 $ctags->{$tag}++;
2979 return $ctags;
2982 # return hash, where keys are content tags ('ctags'),
2983 # and values are sum of weights of given tag in every project
2984 sub git_gather_all_ctags {
2985 my $projects = shift;
2986 my $ctags = {};
2988 foreach my $p (@$projects) {
2989 foreach my $ct (keys %{$p->{'ctags'}}) {
2990 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2994 return $ctags;
2997 sub git_populate_project_tagcloud {
2998 my $ctags = shift;
3000 # First, merge different-cased tags; tags vote on casing
3001 my %ctags_lc;
3002 foreach (keys %$ctags) {
3003 $ctags_lc{lc $_}->{count} += $ctags->{$_};
3004 if (not $ctags_lc{lc $_}->{topcount}
3005 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
3006 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
3007 $ctags_lc{lc $_}->{topname} = $_;
3011 my $cloud;
3012 my $matched = $input_params{'ctag'};
3013 if (eval { require HTML::TagCloud; 1; }) {
3014 $cloud = HTML::TagCloud->new;
3015 foreach my $ctag (sort keys %ctags_lc) {
3016 # Pad the title with spaces so that the cloud looks
3017 # less crammed.
3018 my $title = esc_html($ctags_lc{$ctag}->{topname});
3019 $title =~ s/ /&nbsp;/g;
3020 $title =~ s/^/&nbsp;/g;
3021 $title =~ s/$/&nbsp;/g;
3022 if (defined $matched && $matched eq $ctag) {
3023 $title = qq(<span class="match">$title</span>);
3025 $cloud->add($title, href(project=>undef, ctag=>$ctag),
3026 $ctags_lc{$ctag}->{count});
3028 } else {
3029 $cloud = {};
3030 foreach my $ctag (keys %ctags_lc) {
3031 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3032 if (defined $matched && $matched eq $ctag) {
3033 $title = qq(<span class="match">$title</span>);
3035 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3036 $cloud->{$ctag}{ctag} =
3037 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3040 return $cloud;
3043 sub git_show_project_tagcloud {
3044 my ($cloud, $count) = @_;
3045 if (ref $cloud eq 'HTML::TagCloud') {
3046 return $cloud->html_and_css($count);
3047 } else {
3048 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3049 return
3050 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3051 join (', ', map {
3052 $cloud->{$_}->{'ctag'}
3053 } splice(@tags, 0, $count)) .
3054 '</div>';
3058 sub git_get_project_url_list {
3059 my $path = shift;
3061 $git_dir = "$projectroot/$path";
3062 open my $fd, '<', "$git_dir/cloneurl"
3063 or return wantarray ?
3064 @{ config_to_multi(git_get_project_config('url')) } :
3065 config_to_multi(git_get_project_config('url'));
3066 my @git_project_url_list = map { chomp; $_ } <$fd>;
3067 close $fd;
3069 return wantarray ? @git_project_url_list : \@git_project_url_list;
3072 sub git_get_projects_list {
3073 my $filter = shift || '';
3074 my $paranoid = shift;
3075 my @list;
3077 if (-d $projects_list) {
3078 # search in directory
3079 my $dir = $projects_list;
3080 # remove the trailing "/"
3081 $dir =~ s!/+$!!;
3082 my $pfxlen = length("$dir");
3083 my $pfxdepth = ($dir =~ tr!/!!);
3084 # when filtering, search only given subdirectory
3085 if ($filter && !$paranoid) {
3086 $dir .= "/$filter";
3087 $dir =~ s!/+$!!;
3090 File::Find::find({
3091 follow_fast => 1, # follow symbolic links
3092 follow_skip => 2, # ignore duplicates
3093 dangling_symlinks => 0, # ignore dangling symlinks, silently
3094 wanted => sub {
3095 # global variables
3096 our $project_maxdepth;
3097 our $projectroot;
3098 # skip project-list toplevel, if we get it.
3099 return if (m!^[/.]$!);
3100 # only directories can be git repositories
3101 return unless (-d $_);
3102 # don't traverse too deep (Find is super slow on os x)
3103 # $project_maxdepth excludes depth of $projectroot
3104 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3105 $File::Find::prune = 1;
3106 return;
3109 my $path = substr($File::Find::name, $pfxlen + 1);
3110 # paranoidly only filter here
3111 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3112 next;
3114 # we check related file in $projectroot
3115 if (check_export_ok("$projectroot/$path")) {
3116 push @list, { path => $path };
3117 $File::Find::prune = 1;
3120 }, "$dir");
3122 } elsif (-f $projects_list) {
3123 # read from file(url-encoded):
3124 # 'git%2Fgit.git Linus+Torvalds'
3125 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3126 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3127 open my $fd, '<', $projects_list or return;
3128 PROJECT:
3129 while (my $line = <$fd>) {
3130 chomp $line;
3131 my ($path, $owner) = split ' ', $line;
3132 $path = unescape($path);
3133 $owner = unescape($owner);
3134 if (!defined $path) {
3135 next;
3137 # if $filter is rpovided, check if $path begins with $filter
3138 if ($filter && $path !~ m!^\Q$filter\E/!) {
3139 next;
3141 if (check_export_ok("$projectroot/$path")) {
3142 my $pr = {
3143 path => $path
3145 if ($owner) {
3146 $pr->{'owner'} = to_utf8($owner);
3148 push @list, $pr;
3151 close $fd;
3153 return @list;
3156 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3157 # as side effects it sets 'forks' field to list of forks for forked projects
3158 sub filter_forks_from_projects_list {
3159 my $projects = shift;
3161 my %trie; # prefix tree of directories (path components)
3162 # generate trie out of those directories that might contain forks
3163 foreach my $pr (@$projects) {
3164 my $path = $pr->{'path'};
3165 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3166 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3167 next unless ($path); # skip '.git' repository: tests, git-instaweb
3168 next unless (-d "$projectroot/$path"); # containing directory exists
3169 $pr->{'forks'} = []; # there can be 0 or more forks of project
3171 # add to trie
3172 my @dirs = split('/', $path);
3173 # walk the trie, until either runs out of components or out of trie
3174 my $ref = \%trie;
3175 while (scalar @dirs &&
3176 exists($ref->{$dirs[0]})) {
3177 $ref = $ref->{shift @dirs};
3179 # create rest of trie structure from rest of components
3180 foreach my $dir (@dirs) {
3181 $ref = $ref->{$dir} = {};
3183 # create end marker, store $pr as a data
3184 $ref->{''} = $pr if (!exists $ref->{''});
3187 # filter out forks, by finding shortest prefix match for paths
3188 my @filtered;
3189 PROJECT:
3190 foreach my $pr (@$projects) {
3191 # trie lookup
3192 my $ref = \%trie;
3193 DIR:
3194 foreach my $dir (split('/', $pr->{'path'})) {
3195 if (exists $ref->{''}) {
3196 # found [shortest] prefix, is a fork - skip it
3197 push @{$ref->{''}{'forks'}}, $pr;
3198 next PROJECT;
3200 if (!exists $ref->{$dir}) {
3201 # not in trie, cannot have prefix, not a fork
3202 push @filtered, $pr;
3203 next PROJECT;
3205 # If the dir is there, we just walk one step down the trie.
3206 $ref = $ref->{$dir};
3208 # we ran out of trie
3209 # (shouldn't happen: it's either no match, or end marker)
3210 push @filtered, $pr;
3213 return @filtered;
3216 # note: fill_project_list_info must be run first,
3217 # for 'descr_long' and 'ctags' to be filled
3218 sub search_projects_list {
3219 my ($projlist, %opts) = @_;
3220 my $tagfilter = $opts{'tagfilter'};
3221 my $search_re = $opts{'search_regexp'};
3223 return @$projlist
3224 unless ($tagfilter || $search_re);
3226 # searching projects require filling to be run before it;
3227 fill_project_list_info($projlist,
3228 $tagfilter ? 'ctags' : (),
3229 $search_re ? ('path', 'descr') : ());
3230 my @projects;
3231 PROJECT:
3232 foreach my $pr (@$projlist) {
3234 if ($tagfilter) {
3235 next unless ref($pr->{'ctags'}) eq 'HASH';
3236 next unless
3237 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3240 if ($search_re) {
3241 next unless
3242 $pr->{'path'} =~ /$search_re/ ||
3243 $pr->{'descr_long'} =~ /$search_re/;
3246 push @projects, $pr;
3249 return @projects;
3252 our $gitweb_project_owner = undef;
3253 sub git_get_project_list_from_file {
3255 return if (defined $gitweb_project_owner);
3257 $gitweb_project_owner = {};
3258 # read from file (url-encoded):
3259 # 'git%2Fgit.git Linus+Torvalds'
3260 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3261 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3262 if (-f $projects_list) {
3263 open(my $fd, '<', $projects_list);
3264 while (my $line = <$fd>) {
3265 chomp $line;
3266 my ($pr, $ow) = split ' ', $line;
3267 $pr = unescape($pr);
3268 $ow = unescape($ow);
3269 $gitweb_project_owner->{$pr} = to_utf8($ow);
3271 close $fd;
3275 sub git_get_project_owner {
3276 my $project = shift;
3277 my $owner;
3279 return undef unless $project;
3280 $git_dir = "$projectroot/$project";
3282 if (!defined $gitweb_project_owner) {
3283 git_get_project_list_from_file();
3286 if (exists $gitweb_project_owner->{$project}) {
3287 $owner = $gitweb_project_owner->{$project};
3289 if (!defined $owner){
3290 $owner = git_get_project_config('owner');
3292 if (!defined $owner) {
3293 $owner = get_file_owner("$git_dir");
3296 return $owner;
3299 sub git_get_last_activity {
3300 my ($path) = @_;
3301 my $fd;
3303 $git_dir = "$projectroot/$path";
3304 open($fd, "-|", git_cmd(), 'for-each-ref',
3305 '--format=%(committer)',
3306 '--sort=-committerdate',
3307 '--count=1',
3308 map { "refs/$_" } get_branch_refs ()) or return;
3309 my $most_recent = <$fd>;
3310 close $fd or return;
3311 if (defined $most_recent &&
3312 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3313 my $timestamp = $1;
3314 my $age = time - $timestamp;
3315 return ($age, age_string($age));
3317 return (undef, undef);
3320 # Implementation note: when a single remote is wanted, we cannot use 'git
3321 # remote show -n' because that command always work (assuming it's a remote URL
3322 # if it's not defined), and we cannot use 'git remote show' because that would
3323 # try to make a network roundtrip. So the only way to find if that particular
3324 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3325 # and when we find what we want.
3326 sub git_get_remotes_list {
3327 my $wanted = shift;
3328 my %remotes = ();
3330 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3331 return unless $fd;
3332 while (my $remote = <$fd>) {
3333 chomp $remote;
3334 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3335 next if $wanted and not $remote eq $wanted;
3336 my ($url, $key) = ($1, $2);
3338 $remotes{$remote} ||= { 'heads' => () };
3339 $remotes{$remote}{$key} = $url;
3341 close $fd or return;
3342 return wantarray ? %remotes : \%remotes;
3345 # Takes a hash of remotes as first parameter and fills it by adding the
3346 # available remote heads for each of the indicated remotes.
3347 sub fill_remote_heads {
3348 my $remotes = shift;
3349 my @heads = map { "remotes/$_" } keys %$remotes;
3350 my @remoteheads = git_get_heads_list(undef, @heads);
3351 foreach my $remote (keys %$remotes) {
3352 $remotes->{$remote}{'heads'} = [ grep {
3353 $_->{'name'} =~ s!^$remote/!!
3354 } @remoteheads ];
3358 sub git_get_references {
3359 my $type = shift || "";
3360 my %refs;
3361 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3362 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3363 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3364 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3365 or return;
3367 while (my $line = <$fd>) {
3368 chomp $line;
3369 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3370 if (defined $refs{$1}) {
3371 push @{$refs{$1}}, $2;
3372 } else {
3373 $refs{$1} = [ $2 ];
3377 close $fd or return;
3378 return \%refs;
3381 sub git_get_rev_name_tags {
3382 my $hash = shift || return undef;
3384 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3385 or return;
3386 my $name_rev = <$fd>;
3387 close $fd;
3389 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3390 return $1;
3391 } else {
3392 # catches also '$hash undefined' output
3393 return undef;
3397 ## ----------------------------------------------------------------------
3398 ## parse to hash functions
3400 sub parse_date {
3401 my $epoch = shift;
3402 my $tz = shift || "-0000";
3404 my %date;
3405 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3406 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3407 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3408 $date{'hour'} = $hour;
3409 $date{'minute'} = $min;
3410 $date{'mday'} = $mday;
3411 $date{'day'} = $days[$wday];
3412 $date{'month'} = $months[$mon];
3413 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3414 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3415 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3416 $mday, $months[$mon], $hour ,$min;
3417 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3418 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3420 my ($tz_sign, $tz_hour, $tz_min) =
3421 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3422 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3423 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3424 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3425 $date{'hour_local'} = $hour;
3426 $date{'minute_local'} = $min;
3427 $date{'tz_local'} = $tz;
3428 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3429 1900+$year, $mon+1, $mday,
3430 $hour, $min, $sec, $tz);
3431 return %date;
3434 sub parse_tag {
3435 my $tag_id = shift;
3436 my %tag;
3437 my @comment;
3439 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3440 $tag{'id'} = $tag_id;
3441 while (my $line = <$fd>) {
3442 chomp $line;
3443 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3444 $tag{'object'} = $1;
3445 } elsif ($line =~ m/^type (.+)$/) {
3446 $tag{'type'} = $1;
3447 } elsif ($line =~ m/^tag (.+)$/) {
3448 $tag{'name'} = $1;
3449 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3450 $tag{'author'} = $1;
3451 $tag{'author_epoch'} = $2;
3452 $tag{'author_tz'} = $3;
3453 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3454 $tag{'author_name'} = $1;
3455 $tag{'author_email'} = $2;
3456 } else {
3457 $tag{'author_name'} = $tag{'author'};
3459 } elsif ($line =~ m/--BEGIN/) {
3460 push @comment, $line;
3461 last;
3462 } elsif ($line eq "") {
3463 last;
3466 push @comment, <$fd>;
3467 $tag{'comment'} = \@comment;
3468 close $fd or return;
3469 if (!defined $tag{'name'}) {
3470 return
3472 return %tag
3475 sub parse_commit_text {
3476 my ($commit_text, $withparents) = @_;
3477 my @commit_lines = split '\n', $commit_text;
3478 my %co;
3480 pop @commit_lines; # Remove '\0'
3482 if (! @commit_lines) {
3483 return;
3486 my $header = shift @commit_lines;
3487 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3488 return;
3490 ($co{'id'}, my @parents) = split ' ', $header;
3491 while (my $line = shift @commit_lines) {
3492 last if $line eq "\n";
3493 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3494 $co{'tree'} = $1;
3495 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3496 push @parents, $1;
3497 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3498 $co{'author'} = to_utf8($1);
3499 $co{'author_epoch'} = $2;
3500 $co{'author_tz'} = $3;
3501 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3502 $co{'author_name'} = $1;
3503 $co{'author_email'} = $2;
3504 } else {
3505 $co{'author_name'} = $co{'author'};
3507 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3508 $co{'committer'} = to_utf8($1);
3509 $co{'committer_epoch'} = $2;
3510 $co{'committer_tz'} = $3;
3511 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3512 $co{'committer_name'} = $1;
3513 $co{'committer_email'} = $2;
3514 } else {
3515 $co{'committer_name'} = $co{'committer'};
3519 if (!defined $co{'tree'}) {
3520 return;
3522 $co{'parents'} = \@parents;
3523 $co{'parent'} = $parents[0];
3525 foreach my $title (@commit_lines) {
3526 $title =~ s/^ //;
3527 if ($title ne "") {
3528 $co{'title'} = chop_str($title, 80, 5);
3529 # remove leading stuff of merges to make the interesting part visible
3530 if (length($title) > 50) {
3531 $title =~ s/^Automatic //;
3532 $title =~ s/^merge (of|with) /Merge ... /i;
3533 if (length($title) > 50) {
3534 $title =~ s/(http|rsync):\/\///;
3536 if (length($title) > 50) {
3537 $title =~ s/(master|www|rsync)\.//;
3539 if (length($title) > 50) {
3540 $title =~ s/kernel.org:?//;
3542 if (length($title) > 50) {
3543 $title =~ s/\/pub\/scm//;
3546 $co{'title_short'} = chop_str($title, 50, 5);
3547 last;
3550 if (! defined $co{'title'} || $co{'title'} eq "") {
3551 $co{'title'} = $co{'title_short'} = '(no commit message)';
3553 # remove added spaces
3554 foreach my $line (@commit_lines) {
3555 $line =~ s/^ //;
3557 $co{'comment'} = \@commit_lines;
3559 my $age = time - $co{'committer_epoch'};
3560 $co{'age'} = $age;
3561 $co{'age_string'} = age_string($age);
3562 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3563 if ($age > 60*60*24*7*2) {
3564 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3565 $co{'age_string_age'} = $co{'age_string'};
3566 } else {
3567 $co{'age_string_date'} = $co{'age_string'};
3568 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3570 return %co;
3573 sub parse_commit {
3574 my ($commit_id) = @_;
3575 my %co;
3577 local $/ = "\0";
3579 open my $fd, "-|", git_cmd(), "rev-list",
3580 "--parents",
3581 "--header",
3582 "--max-count=1",
3583 $commit_id,
3584 "--",
3585 or die_error(500, "Open git-rev-list failed");
3586 %co = parse_commit_text(<$fd>, 1);
3587 close $fd;
3589 return %co;
3592 sub parse_commits {
3593 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3594 my @cos;
3596 $maxcount ||= 1;
3597 $skip ||= 0;
3599 local $/ = "\0";
3601 open my $fd, "-|", git_cmd(), "rev-list",
3602 "--header",
3603 @args,
3604 ("--max-count=" . $maxcount),
3605 ("--skip=" . $skip),
3606 @extra_options,
3607 $commit_id,
3608 "--",
3609 ($filename ? ($filename) : ())
3610 or die_error(500, "Open git-rev-list failed");
3611 while (my $line = <$fd>) {
3612 my %co = parse_commit_text($line);
3613 push @cos, \%co;
3615 close $fd;
3617 return wantarray ? @cos : \@cos;
3620 # parse line of git-diff-tree "raw" output
3621 sub parse_difftree_raw_line {
3622 my $line = shift;
3623 my %res;
3625 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3626 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3627 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3628 $res{'from_mode'} = $1;
3629 $res{'to_mode'} = $2;
3630 $res{'from_id'} = $3;
3631 $res{'to_id'} = $4;
3632 $res{'status'} = $5;
3633 $res{'similarity'} = $6;
3634 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3635 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3636 } else {
3637 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3640 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3641 # combined diff (for merge commit)
3642 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3643 $res{'nparents'} = length($1);
3644 $res{'from_mode'} = [ split(' ', $2) ];
3645 $res{'to_mode'} = pop @{$res{'from_mode'}};
3646 $res{'from_id'} = [ split(' ', $3) ];
3647 $res{'to_id'} = pop @{$res{'from_id'}};
3648 $res{'status'} = [ split('', $4) ];
3649 $res{'to_file'} = unquote($5);
3651 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3652 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3653 $res{'commit'} = $1;
3656 return wantarray ? %res : \%res;
3659 # wrapper: return parsed line of git-diff-tree "raw" output
3660 # (the argument might be raw line, or parsed info)
3661 sub parsed_difftree_line {
3662 my $line_or_ref = shift;
3664 if (ref($line_or_ref) eq "HASH") {
3665 # pre-parsed (or generated by hand)
3666 return $line_or_ref;
3667 } else {
3668 return parse_difftree_raw_line($line_or_ref);
3672 # parse line of git-ls-tree output
3673 sub parse_ls_tree_line {
3674 my $line = shift;
3675 my %opts = @_;
3676 my %res;
3678 if ($opts{'-l'}) {
3679 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3680 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3682 $res{'mode'} = $1;
3683 $res{'type'} = $2;
3684 $res{'hash'} = $3;
3685 $res{'size'} = $4;
3686 if ($opts{'-z'}) {
3687 $res{'name'} = $5;
3688 } else {
3689 $res{'name'} = unquote($5);
3691 } else {
3692 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3693 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3695 $res{'mode'} = $1;
3696 $res{'type'} = $2;
3697 $res{'hash'} = $3;
3698 if ($opts{'-z'}) {
3699 $res{'name'} = $4;
3700 } else {
3701 $res{'name'} = unquote($4);
3705 return wantarray ? %res : \%res;
3708 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3709 sub parse_from_to_diffinfo {
3710 my ($diffinfo, $from, $to, @parents) = @_;
3712 if ($diffinfo->{'nparents'}) {
3713 # combined diff
3714 $from->{'file'} = [];
3715 $from->{'href'} = [];
3716 fill_from_file_info($diffinfo, @parents)
3717 unless exists $diffinfo->{'from_file'};
3718 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3719 $from->{'file'}[$i] =
3720 defined $diffinfo->{'from_file'}[$i] ?
3721 $diffinfo->{'from_file'}[$i] :
3722 $diffinfo->{'to_file'};
3723 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3724 $from->{'href'}[$i] = href(action=>"blob",
3725 hash_base=>$parents[$i],
3726 hash=>$diffinfo->{'from_id'}[$i],
3727 file_name=>$from->{'file'}[$i]);
3728 } else {
3729 $from->{'href'}[$i] = undef;
3732 } else {
3733 # ordinary (not combined) diff
3734 $from->{'file'} = $diffinfo->{'from_file'};
3735 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3736 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3737 hash=>$diffinfo->{'from_id'},
3738 file_name=>$from->{'file'});
3739 } else {
3740 delete $from->{'href'};
3744 $to->{'file'} = $diffinfo->{'to_file'};
3745 if (!is_deleted($diffinfo)) { # file exists in result
3746 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3747 hash=>$diffinfo->{'to_id'},
3748 file_name=>$to->{'file'});
3749 } else {
3750 delete $to->{'href'};
3754 ## ......................................................................
3755 ## parse to array of hashes functions
3757 sub git_get_heads_list {
3758 my ($limit, @classes) = @_;
3759 @classes = get_branch_refs() unless @classes;
3760 my @patterns = map { "refs/$_" } @classes;
3761 my @headslist;
3763 open my $fd, '-|', git_cmd(), 'for-each-ref',
3764 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3765 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3766 @patterns
3767 or return;
3768 while (my $line = <$fd>) {
3769 my %ref_item;
3771 chomp $line;
3772 my ($refinfo, $committerinfo) = split(/\0/, $line);
3773 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3774 my ($committer, $epoch, $tz) =
3775 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3776 $ref_item{'fullname'} = $name;
3777 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3778 $name =~ s!^refs/($strip_refs|remotes)/!!;
3779 $ref_item{'name'} = $name;
3780 # for refs neither in 'heads' nor 'remotes' we want to
3781 # show their ref dir
3782 my $ref_dir = (defined $1) ? $1 : '';
3783 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3784 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3787 $ref_item{'id'} = $hash;
3788 $ref_item{'title'} = $title || '(no commit message)';
3789 $ref_item{'epoch'} = $epoch;
3790 if ($epoch) {
3791 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3792 } else {
3793 $ref_item{'age'} = "unknown";
3796 push @headslist, \%ref_item;
3798 close $fd;
3800 return wantarray ? @headslist : \@headslist;
3803 sub git_get_tags_list {
3804 my $limit = shift;
3805 my @tagslist;
3807 open my $fd, '-|', git_cmd(), 'for-each-ref',
3808 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3809 '--format=%(objectname) %(objecttype) %(refname) '.
3810 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3811 'refs/tags'
3812 or return;
3813 while (my $line = <$fd>) {
3814 my %ref_item;
3816 chomp $line;
3817 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3818 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3819 my ($creator, $epoch, $tz) =
3820 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3821 $ref_item{'fullname'} = $name;
3822 $name =~ s!^refs/tags/!!;
3824 $ref_item{'type'} = $type;
3825 $ref_item{'id'} = $id;
3826 $ref_item{'name'} = $name;
3827 if ($type eq "tag") {
3828 $ref_item{'subject'} = $title;
3829 $ref_item{'reftype'} = $reftype;
3830 $ref_item{'refid'} = $refid;
3831 } else {
3832 $ref_item{'reftype'} = $type;
3833 $ref_item{'refid'} = $id;
3836 if ($type eq "tag" || $type eq "commit") {
3837 $ref_item{'epoch'} = $epoch;
3838 if ($epoch) {
3839 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3840 } else {
3841 $ref_item{'age'} = "unknown";
3845 push @tagslist, \%ref_item;
3847 close $fd;
3849 return wantarray ? @tagslist : \@tagslist;
3852 ## ----------------------------------------------------------------------
3853 ## filesystem-related functions
3855 sub get_file_owner {
3856 my $path = shift;
3858 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3859 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3860 if (!defined $gcos) {
3861 return undef;
3863 my $owner = $gcos;
3864 $owner =~ s/[,;].*$//;
3865 return to_utf8($owner);
3868 # assume that file exists
3869 sub insert_file {
3870 my $filename = shift;
3872 open my $fd, '<', $filename;
3873 print map { to_utf8($_) } <$fd>;
3874 close $fd;
3877 ## ......................................................................
3878 ## mimetype related functions
3880 sub mimetype_guess_file {
3881 my $filename = shift;
3882 my $mimemap = shift;
3883 -r $mimemap or return undef;
3885 my %mimemap;
3886 open(my $mh, '<', $mimemap) or return undef;
3887 while (<$mh>) {
3888 next if m/^#/; # skip comments
3889 my ($mimetype, @exts) = split(/\s+/);
3890 foreach my $ext (@exts) {
3891 $mimemap{$ext} = $mimetype;
3894 close($mh);
3896 $filename =~ /\.([^.]*)$/;
3897 return $mimemap{$1};
3900 sub mimetype_guess {
3901 my $filename = shift;
3902 my $mime;
3903 $filename =~ /\./ or return undef;
3905 if ($mimetypes_file) {
3906 my $file = $mimetypes_file;
3907 if ($file !~ m!^/!) { # if it is relative path
3908 # it is relative to project
3909 $file = "$projectroot/$project/$file";
3911 $mime = mimetype_guess_file($filename, $file);
3913 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3914 return $mime;
3917 sub blob_mimetype {
3918 my $fd = shift;
3919 my $filename = shift;
3921 if ($filename) {
3922 my $mime = mimetype_guess($filename);
3923 $mime and return $mime;
3926 # just in case
3927 return $default_blob_plain_mimetype unless $fd;
3929 if (-T $fd) {
3930 return 'text/plain';
3931 } elsif (! $filename) {
3932 return 'application/octet-stream';
3933 } elsif ($filename =~ m/\.png$/i) {
3934 return 'image/png';
3935 } elsif ($filename =~ m/\.gif$/i) {
3936 return 'image/gif';
3937 } elsif ($filename =~ m/\.jpe?g$/i) {
3938 return 'image/jpeg';
3939 } else {
3940 return 'application/octet-stream';
3944 sub blob_contenttype {
3945 my ($fd, $file_name, $type) = @_;
3947 $type ||= blob_mimetype($fd, $file_name);
3948 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3949 $type .= "; charset=$default_text_plain_charset";
3952 return $type;
3955 # guess file syntax for syntax highlighting; return undef if no highlighting
3956 # the name of syntax can (in the future) depend on syntax highlighter used
3957 sub guess_file_syntax {
3958 my ($highlight, $mimetype, $file_name) = @_;
3959 return undef unless ($highlight && defined $file_name);
3960 my $basename = basename($file_name, '.in');
3961 return $highlight_basename{$basename}
3962 if exists $highlight_basename{$basename};
3964 $basename =~ /\.([^.]*)$/;
3965 my $ext = $1 or return undef;
3966 return $highlight_ext{$ext}
3967 if exists $highlight_ext{$ext};
3969 return undef;
3972 # run highlighter and return FD of its output,
3973 # or return original FD if no highlighting
3974 sub run_highlighter {
3975 my ($fd, $highlight, $syntax) = @_;
3976 return $fd unless ($highlight && defined $syntax);
3978 close $fd;
3979 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3980 quote_command($highlight_bin).
3981 " --replace-tabs=8 --fragment --syntax $syntax |"
3982 or die_error(500, "Couldn't open file or run syntax highlighter");
3983 return $fd;
3986 ## ======================================================================
3987 ## functions printing HTML: header, footer, error page
3989 sub get_page_title {
3990 my $title = to_utf8($site_name);
3992 unless (defined $project) {
3993 if (defined $project_filter) {
3994 $title .= " - projects in '" . esc_path($project_filter) . "'";
3996 return $title;
3998 $title .= " - " . to_utf8($project);
4000 return $title unless (defined $action);
4001 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
4003 return $title unless (defined $file_name);
4004 $title .= " - " . esc_path($file_name);
4005 if ($action eq "tree" && $file_name !~ m|/$|) {
4006 $title .= "/";
4009 return $title;
4012 sub get_content_type_html {
4013 # require explicit support from the UA if we are to send the page as
4014 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4015 # we have to do this because MSIE sometimes globs '*/*', pretending to
4016 # support xhtml+xml but choking when it gets what it asked for.
4017 if (defined $cgi->http('HTTP_ACCEPT') &&
4018 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4019 $cgi->Accept('application/xhtml+xml') != 0) {
4020 return 'application/xhtml+xml';
4021 } else {
4022 return 'text/html';
4026 sub print_feed_meta {
4027 if (defined $project) {
4028 my %href_params = get_feed_info();
4029 if (!exists $href_params{'-title'}) {
4030 $href_params{'-title'} = 'log';
4033 foreach my $format (qw(RSS Atom)) {
4034 my $type = lc($format);
4035 my %link_attr = (
4036 '-rel' => 'alternate',
4037 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4038 '-type' => "application/$type+xml"
4041 $href_params{'extra_options'} = undef;
4042 $href_params{'action'} = $type;
4043 $link_attr{'-href'} = href(%href_params);
4044 print "<link ".
4045 "rel=\"$link_attr{'-rel'}\" ".
4046 "title=\"$link_attr{'-title'}\" ".
4047 "href=\"$link_attr{'-href'}\" ".
4048 "type=\"$link_attr{'-type'}\" ".
4049 "/>\n";
4051 $href_params{'extra_options'} = '--no-merges';
4052 $link_attr{'-href'} = href(%href_params);
4053 $link_attr{'-title'} .= ' (no merges)';
4054 print "<link ".
4055 "rel=\"$link_attr{'-rel'}\" ".
4056 "title=\"$link_attr{'-title'}\" ".
4057 "href=\"$link_attr{'-href'}\" ".
4058 "type=\"$link_attr{'-type'}\" ".
4059 "/>\n";
4062 } else {
4063 printf('<link rel="alternate" title="%s projects list" '.
4064 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4065 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4066 printf('<link rel="alternate" title="%s projects feeds" '.
4067 'href="%s" type="text/x-opml" />'."\n",
4068 esc_attr($site_name), href(project=>undef, action=>"opml"));
4072 sub print_header_links {
4073 my $status = shift;
4075 # print out each stylesheet that exist, providing backwards capability
4076 # for those people who defined $stylesheet in a config file
4077 if (defined $stylesheet) {
4078 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4079 } else {
4080 foreach my $stylesheet (@stylesheets) {
4081 next unless $stylesheet;
4082 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4085 print_feed_meta()
4086 if ($status eq '200 OK');
4087 if (defined $favicon) {
4088 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4092 sub print_nav_breadcrumbs_path {
4093 my $dirprefix = undef;
4094 while (my $part = shift) {
4095 $dirprefix .= "/" if defined $dirprefix;
4096 $dirprefix .= $part;
4097 print $cgi->a({-href => href(project => undef,
4098 project_filter => $dirprefix,
4099 action => "project_list")},
4100 esc_html($part)) . " / ";
4104 sub print_nav_breadcrumbs {
4105 my %opts = @_;
4107 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4108 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4110 if (defined $project) {
4111 my @dirname = split '/', $project;
4112 my $projectbasename = pop @dirname;
4113 print_nav_breadcrumbs_path(@dirname);
4114 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4115 if (defined $action) {
4116 my $action_print = $action ;
4117 if (defined $opts{-action_extra}) {
4118 $action_print = $cgi->a({-href => href(action=>$action)},
4119 $action);
4121 print " / $action_print";
4123 if (defined $opts{-action_extra}) {
4124 print " / $opts{-action_extra}";
4126 print "\n";
4127 } elsif (defined $project_filter) {
4128 print_nav_breadcrumbs_path(split '/', $project_filter);
4132 sub print_search_form {
4133 if (!defined $searchtext) {
4134 $searchtext = "";
4136 my $search_hash;
4137 if (defined $hash_base) {
4138 $search_hash = $hash_base;
4139 } elsif (defined $hash) {
4140 $search_hash = $hash;
4141 } else {
4142 $search_hash = "HEAD";
4144 my $action = $my_uri;
4145 my $use_pathinfo = gitweb_check_feature('pathinfo');
4146 if ($use_pathinfo) {
4147 $action .= "/".esc_url($project);
4149 print $cgi->start_form(-method => "get", -action => $action) .
4150 "<div class=\"search\">\n" .
4151 (!$use_pathinfo &&
4152 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4153 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4154 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4155 $cgi->popup_menu(-name => 'st', -default => 'commit',
4156 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4157 " " . $cgi->a({-href => href(action=>"search_help"),
4158 -title => "search help" }, "?") . " search:\n",
4159 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4160 "<span title=\"Extended regular expression\">" .
4161 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4162 -checked => $search_use_regexp) .
4163 "</span>" .
4164 "</div>" .
4165 $cgi->end_form() . "\n";
4168 sub git_header_html {
4169 my $status = shift || "200 OK";
4170 my $expires = shift;
4171 my %opts = @_;
4173 my $title = get_page_title();
4174 my $content_type = get_content_type_html();
4175 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4176 -status=> $status, -expires => $expires)
4177 unless ($opts{'-no_http_header'});
4178 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4179 print <<EOF;
4180 <?xml version="1.0" encoding="utf-8"?>
4181 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4182 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4183 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4184 <!-- git core binaries version $git_version -->
4185 <head>
4186 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4187 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4188 <meta name="robots" content="index, nofollow"/>
4189 <title>$title</title>
4191 # the stylesheet, favicon etc urls won't work correctly with path_info
4192 # unless we set the appropriate base URL
4193 if ($ENV{'PATH_INFO'}) {
4194 print "<base href=\"".esc_url($base_url)."\" />\n";
4196 print_header_links($status);
4198 if (defined $site_html_head_string) {
4199 print to_utf8($site_html_head_string);
4202 print "</head>\n" .
4203 "<body>\n";
4205 if (defined $site_header && -f $site_header) {
4206 insert_file($site_header);
4209 print "<div class=\"page_header\">\n";
4210 if (defined $logo) {
4211 print $cgi->a({-href => esc_url($logo_url),
4212 -title => $logo_label},
4213 $cgi->img({-src => esc_url($logo),
4214 -width => 72, -height => 27,
4215 -alt => "git",
4216 -class => "logo"}));
4218 print_nav_breadcrumbs(%opts);
4219 print "</div>\n";
4221 my $have_search = gitweb_check_feature('search');
4222 if (defined $project && $have_search) {
4223 print_search_form();
4227 sub git_footer_html {
4228 my $feed_class = 'rss_logo';
4230 print "<div class=\"page_footer\">\n";
4231 if (defined $project) {
4232 my $descr = git_get_project_description($project);
4233 if (defined $descr) {
4234 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4237 my %href_params = get_feed_info();
4238 if (!%href_params) {
4239 $feed_class .= ' generic';
4241 $href_params{'-title'} ||= 'log';
4243 foreach my $format (qw(RSS Atom)) {
4244 $href_params{'action'} = lc($format);
4245 print $cgi->a({-href => href(%href_params),
4246 -title => "$href_params{'-title'} $format feed",
4247 -class => $feed_class}, $format)."\n";
4250 } else {
4251 print $cgi->a({-href => href(project=>undef, action=>"opml",
4252 project_filter => $project_filter),
4253 -class => $feed_class}, "OPML") . " ";
4254 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4255 project_filter => $project_filter),
4256 -class => $feed_class}, "TXT") . "\n";
4258 print "</div>\n"; # class="page_footer"
4260 if (defined $t0 && gitweb_check_feature('timed')) {
4261 print "<div id=\"generating_info\">\n";
4262 print 'This page took '.
4263 '<span id="generating_time" class="time_span">'.
4264 tv_interval($t0, [ gettimeofday() ]).
4265 ' seconds </span>'.
4266 ' and '.
4267 '<span id="generating_cmd">'.
4268 $number_of_git_cmds.
4269 '</span> git commands '.
4270 " to generate.\n";
4271 print "</div>\n"; # class="page_footer"
4274 if (defined $site_footer && -f $site_footer) {
4275 insert_file($site_footer);
4278 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4279 if (defined $action &&
4280 $action eq 'blame_incremental') {
4281 print qq!<script type="text/javascript">\n!.
4282 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4283 qq! "!. href() .qq!");\n!.
4284 qq!</script>\n!;
4285 } else {
4286 my ($jstimezone, $tz_cookie, $datetime_class) =
4287 gitweb_get_feature('javascript-timezone');
4289 print qq!<script type="text/javascript">\n!.
4290 qq!window.onload = function () {\n!;
4291 if (gitweb_check_feature('javascript-actions')) {
4292 print qq! fixLinks();\n!;
4294 if ($jstimezone && $tz_cookie && $datetime_class) {
4295 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4296 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4298 print qq!};\n!.
4299 qq!</script>\n!;
4302 print "</body>\n" .
4303 "</html>";
4306 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4307 # Example: die_error(404, 'Hash not found')
4308 # By convention, use the following status codes (as defined in RFC 2616):
4309 # 400: Invalid or missing CGI parameters, or
4310 # requested object exists but has wrong type.
4311 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4312 # this server or project.
4313 # 404: Requested object/revision/project doesn't exist.
4314 # 500: The server isn't configured properly, or
4315 # an internal error occurred (e.g. failed assertions caused by bugs), or
4316 # an unknown error occurred (e.g. the git binary died unexpectedly).
4317 # 503: The server is currently unavailable (because it is overloaded,
4318 # or down for maintenance). Generally, this is a temporary state.
4319 sub die_error {
4320 my $status = shift || 500;
4321 my $error = esc_html(shift) || "Internal Server Error";
4322 my $extra = shift;
4323 my %opts = @_;
4325 my %http_responses = (
4326 400 => '400 Bad Request',
4327 403 => '403 Forbidden',
4328 404 => '404 Not Found',
4329 500 => '500 Internal Server Error',
4330 503 => '503 Service Unavailable',
4332 git_header_html($http_responses{$status}, undef, %opts);
4333 print <<EOF;
4334 <div class="page_body">
4335 <br /><br />
4336 $status - $error
4337 <br />
4339 if (defined $extra) {
4340 print "<hr />\n" .
4341 "$extra\n";
4343 print "</div>\n";
4345 git_footer_html();
4346 goto DONE_GITWEB
4347 unless ($opts{'-error_handler'});
4350 ## ----------------------------------------------------------------------
4351 ## functions printing or outputting HTML: navigation
4353 sub git_print_page_nav {
4354 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4355 $extra = '' if !defined $extra; # pager or formats
4357 my @navs = qw(summary shortlog log commit commitdiff tree);
4358 if ($suppress) {
4359 @navs = grep { $_ ne $suppress } @navs;
4362 my %arg = map { $_ => {action=>$_} } @navs;
4363 if (defined $head) {
4364 for (qw(commit commitdiff)) {
4365 $arg{$_}{'hash'} = $head;
4367 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4368 for (qw(shortlog log)) {
4369 $arg{$_}{'hash'} = $head;
4374 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4375 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4377 my @actions = gitweb_get_feature('actions');
4378 my %repl = (
4379 '%' => '%',
4380 'n' => $project, # project name
4381 'f' => $git_dir, # project path within filesystem
4382 'h' => $treehead || '', # current hash ('h' parameter)
4383 'b' => $treebase || '', # hash base ('hb' parameter)
4385 while (@actions) {
4386 my ($label, $link, $pos) = splice(@actions,0,3);
4387 # insert
4388 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4389 # munch munch
4390 $link =~ s/%([%nfhb])/$repl{$1}/g;
4391 $arg{$label}{'_href'} = $link;
4394 print "<div class=\"page_nav\">\n" .
4395 (join " | ",
4396 map { $_ eq $current ?
4397 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4398 } @navs);
4399 print "<br/>\n$extra<br/>\n" .
4400 "</div>\n";
4403 # returns a submenu for the nagivation of the refs views (tags, heads,
4404 # remotes) with the current view disabled and the remotes view only
4405 # available if the feature is enabled
4406 sub format_ref_views {
4407 my ($current) = @_;
4408 my @ref_views = qw{tags heads};
4409 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4410 return join " | ", map {
4411 $_ eq $current ? $_ :
4412 $cgi->a({-href => href(action=>$_)}, $_)
4413 } @ref_views
4416 sub format_paging_nav {
4417 my ($action, $page, $has_next_link) = @_;
4418 my $paging_nav;
4421 if ($page > 0) {
4422 $paging_nav .=
4423 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4424 " &sdot; " .
4425 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4426 -accesskey => "p", -title => "Alt-p"}, "prev");
4427 } else {
4428 $paging_nav .= "first &sdot; prev";
4431 if ($has_next_link) {
4432 $paging_nav .= " &sdot; " .
4433 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4434 -accesskey => "n", -title => "Alt-n"}, "next");
4435 } else {
4436 $paging_nav .= " &sdot; next";
4439 return $paging_nav;
4442 ## ......................................................................
4443 ## functions printing or outputting HTML: div
4445 sub git_print_header_div {
4446 my ($action, $title, $hash, $hash_base) = @_;
4447 my %args = ();
4449 $args{'action'} = $action;
4450 $args{'hash'} = $hash if $hash;
4451 $args{'hash_base'} = $hash_base if $hash_base;
4453 print "<div class=\"header\">\n" .
4454 $cgi->a({-href => href(%args), -class => "title"},
4455 $title ? $title : $action) .
4456 "\n</div>\n";
4459 sub format_repo_url {
4460 my ($name, $url) = @_;
4461 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4464 # Group output by placing it in a DIV element and adding a header.
4465 # Options for start_div() can be provided by passing a hash reference as the
4466 # first parameter to the function.
4467 # Options to git_print_header_div() can be provided by passing an array
4468 # reference. This must follow the options to start_div if they are present.
4469 # The content can be a scalar, which is output as-is, a scalar reference, which
4470 # is output after html escaping, an IO handle passed either as *handle or
4471 # *handle{IO}, or a function reference. In the latter case all following
4472 # parameters will be taken as argument to the content function call.
4473 sub git_print_section {
4474 my ($div_args, $header_args, $content);
4475 my $arg = shift;
4476 if (ref($arg) eq 'HASH') {
4477 $div_args = $arg;
4478 $arg = shift;
4480 if (ref($arg) eq 'ARRAY') {
4481 $header_args = $arg;
4482 $arg = shift;
4484 $content = $arg;
4486 print $cgi->start_div($div_args);
4487 git_print_header_div(@$header_args);
4489 if (ref($content) eq 'CODE') {
4490 $content->(@_);
4491 } elsif (ref($content) eq 'SCALAR') {
4492 print esc_html($$content);
4493 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4494 print <$content>;
4495 } elsif (!ref($content) && defined($content)) {
4496 print $content;
4499 print $cgi->end_div;
4502 sub format_timestamp_html {
4503 my $date = shift;
4504 my $strtime = $date->{'rfc2822'};
4506 my (undef, undef, $datetime_class) =
4507 gitweb_get_feature('javascript-timezone');
4508 if ($datetime_class) {
4509 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4512 my $localtime_format = '(%02d:%02d %s)';
4513 if ($date->{'hour_local'} < 6) {
4514 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4516 $strtime .= ' ' .
4517 sprintf($localtime_format,
4518 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4520 return $strtime;
4523 # Outputs the author name and date in long form
4524 sub git_print_authorship {
4525 my $co = shift;
4526 my %opts = @_;
4527 my $tag = $opts{-tag} || 'div';
4528 my $author = $co->{'author_name'};
4530 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4531 print "<$tag class=\"author_date\">" .
4532 format_search_author($author, "author", esc_html($author)) .
4533 " [".format_timestamp_html(\%ad)."]".
4534 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4535 "</$tag>\n";
4538 # Outputs table rows containing the full author or committer information,
4539 # in the format expected for 'commit' view (& similar).
4540 # Parameters are a commit hash reference, followed by the list of people
4541 # to output information for. If the list is empty it defaults to both
4542 # author and committer.
4543 sub git_print_authorship_rows {
4544 my $co = shift;
4545 # too bad we can't use @people = @_ || ('author', 'committer')
4546 my @people = @_;
4547 @people = ('author', 'committer') unless @people;
4548 foreach my $who (@people) {
4549 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4550 print "<tr><td>$who</td><td>" .
4551 format_search_author($co->{"${who}_name"}, $who,
4552 esc_html($co->{"${who}_name"})) . " " .
4553 format_search_author($co->{"${who}_email"}, $who,
4554 esc_html("<" . $co->{"${who}_email"} . ">")) .
4555 "</td><td rowspan=\"2\">" .
4556 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4557 "</td></tr>\n" .
4558 "<tr>" .
4559 "<td></td><td>" .
4560 format_timestamp_html(\%wd) .
4561 "</td>" .
4562 "</tr>\n";
4566 sub git_print_page_path {
4567 my $name = shift;
4568 my $type = shift;
4569 my $hb = shift;
4572 print "<div class=\"page_path\">";
4573 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4574 -title => 'tree root'}, to_utf8("[$project]"));
4575 print " / ";
4576 if (defined $name) {
4577 my @dirname = split '/', $name;
4578 my $basename = pop @dirname;
4579 my $fullname = '';
4581 foreach my $dir (@dirname) {
4582 $fullname .= ($fullname ? '/' : '') . $dir;
4583 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4584 hash_base=>$hb),
4585 -title => $fullname}, esc_path($dir));
4586 print " / ";
4588 if (defined $type && $type eq 'blob') {
4589 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4590 hash_base=>$hb),
4591 -title => $name}, esc_path($basename));
4592 } elsif (defined $type && $type eq 'tree') {
4593 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4594 hash_base=>$hb),
4595 -title => $name}, esc_path($basename));
4596 print " / ";
4597 } else {
4598 print esc_path($basename);
4601 print "<br/></div>\n";
4604 sub git_print_log {
4605 my $log = shift;
4606 my %opts = @_;
4608 if ($opts{'-remove_title'}) {
4609 # remove title, i.e. first line of log
4610 shift @$log;
4612 # remove leading empty lines
4613 while (defined $log->[0] && $log->[0] eq "") {
4614 shift @$log;
4617 # print log
4618 my $skip_blank_line = 0;
4619 foreach my $line (@$log) {
4620 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4621 if (! $opts{'-remove_signoff'}) {
4622 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4623 $skip_blank_line = 1;
4625 next;
4628 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4629 if (! $opts{'-remove_signoff'}) {
4630 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4631 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4632 "</span><br/>\n";
4633 $skip_blank_line = 1;
4635 next;
4638 # print only one empty line
4639 # do not print empty line after signoff
4640 if ($line eq "") {
4641 next if ($skip_blank_line);
4642 $skip_blank_line = 1;
4643 } else {
4644 $skip_blank_line = 0;
4647 print format_log_line_html($line) . "<br/>\n";
4650 if ($opts{'-final_empty_line'}) {
4651 # end with single empty line
4652 print "<br/>\n" unless $skip_blank_line;
4656 # return link target (what link points to)
4657 sub git_get_link_target {
4658 my $hash = shift;
4659 my $link_target;
4661 # read link
4662 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4663 or return;
4665 local $/ = undef;
4666 $link_target = <$fd>;
4668 close $fd
4669 or return;
4671 return $link_target;
4674 # given link target, and the directory (basedir) the link is in,
4675 # return target of link relative to top directory (top tree);
4676 # return undef if it is not possible (including absolute links).
4677 sub normalize_link_target {
4678 my ($link_target, $basedir) = @_;
4680 # absolute symlinks (beginning with '/') cannot be normalized
4681 return if (substr($link_target, 0, 1) eq '/');
4683 # normalize link target to path from top (root) tree (dir)
4684 my $path;
4685 if ($basedir) {
4686 $path = $basedir . '/' . $link_target;
4687 } else {
4688 # we are in top (root) tree (dir)
4689 $path = $link_target;
4692 # remove //, /./, and /../
4693 my @path_parts;
4694 foreach my $part (split('/', $path)) {
4695 # discard '.' and ''
4696 next if (!$part || $part eq '.');
4697 # handle '..'
4698 if ($part eq '..') {
4699 if (@path_parts) {
4700 pop @path_parts;
4701 } else {
4702 # link leads outside repository (outside top dir)
4703 return;
4705 } else {
4706 push @path_parts, $part;
4709 $path = join('/', @path_parts);
4711 return $path;
4714 # print tree entry (row of git_tree), but without encompassing <tr> element
4715 sub git_print_tree_entry {
4716 my ($t, $basedir, $hash_base, $have_blame) = @_;
4718 my %base_key = ();
4719 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4721 # The format of a table row is: mode list link. Where mode is
4722 # the mode of the entry, list is the name of the entry, an href,
4723 # and link is the action links of the entry.
4725 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4726 if (exists $t->{'size'}) {
4727 print "<td class=\"size\">$t->{'size'}</td>\n";
4729 if ($t->{'type'} eq "blob") {
4730 print "<td class=\"list\">" .
4731 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4732 file_name=>"$basedir$t->{'name'}", %base_key),
4733 -class => "list"}, esc_path($t->{'name'}));
4734 if (S_ISLNK(oct $t->{'mode'})) {
4735 my $link_target = git_get_link_target($t->{'hash'});
4736 if ($link_target) {
4737 my $norm_target = normalize_link_target($link_target, $basedir);
4738 if (defined $norm_target) {
4739 print " -> " .
4740 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4741 file_name=>$norm_target),
4742 -title => $norm_target}, esc_path($link_target));
4743 } else {
4744 print " -> " . esc_path($link_target);
4748 print "</td>\n";
4749 print "<td class=\"link\">";
4750 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4751 file_name=>"$basedir$t->{'name'}", %base_key)},
4752 "blob");
4753 if ($have_blame) {
4754 print " | " .
4755 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4756 file_name=>"$basedir$t->{'name'}", %base_key)},
4757 "blame");
4759 if (defined $hash_base) {
4760 print " | " .
4761 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4762 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4763 "history");
4765 print " | " .
4766 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4767 file_name=>"$basedir$t->{'name'}")},
4768 "raw");
4769 print "</td>\n";
4771 } elsif ($t->{'type'} eq "tree") {
4772 print "<td class=\"list\">";
4773 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4774 file_name=>"$basedir$t->{'name'}",
4775 %base_key)},
4776 esc_path($t->{'name'}));
4777 print "</td>\n";
4778 print "<td class=\"link\">";
4779 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4780 file_name=>"$basedir$t->{'name'}",
4781 %base_key)},
4782 "tree");
4783 if (defined $hash_base) {
4784 print " | " .
4785 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4786 file_name=>"$basedir$t->{'name'}")},
4787 "history");
4789 print "</td>\n";
4790 } else {
4791 # unknown object: we can only present history for it
4792 # (this includes 'commit' object, i.e. submodule support)
4793 print "<td class=\"list\">" .
4794 esc_path($t->{'name'}) .
4795 "</td>\n";
4796 print "<td class=\"link\">";
4797 if (defined $hash_base) {
4798 print $cgi->a({-href => href(action=>"history",
4799 hash_base=>$hash_base,
4800 file_name=>"$basedir$t->{'name'}")},
4801 "history");
4803 print "</td>\n";
4807 ## ......................................................................
4808 ## functions printing large fragments of HTML
4810 # get pre-image filenames for merge (combined) diff
4811 sub fill_from_file_info {
4812 my ($diff, @parents) = @_;
4814 $diff->{'from_file'} = [ ];
4815 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4816 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4817 if ($diff->{'status'}[$i] eq 'R' ||
4818 $diff->{'status'}[$i] eq 'C') {
4819 $diff->{'from_file'}[$i] =
4820 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4824 return $diff;
4827 # is current raw difftree line of file deletion
4828 sub is_deleted {
4829 my $diffinfo = shift;
4831 return $diffinfo->{'to_id'} eq ('0' x 40);
4834 # does patch correspond to [previous] difftree raw line
4835 # $diffinfo - hashref of parsed raw diff format
4836 # $patchinfo - hashref of parsed patch diff format
4837 # (the same keys as in $diffinfo)
4838 sub is_patch_split {
4839 my ($diffinfo, $patchinfo) = @_;
4841 return defined $diffinfo && defined $patchinfo
4842 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4846 sub git_difftree_body {
4847 my ($difftree, $hash, @parents) = @_;
4848 my ($parent) = $parents[0];
4849 my $have_blame = gitweb_check_feature('blame');
4850 print "<div class=\"list_head\">\n";
4851 if ($#{$difftree} > 10) {
4852 print(($#{$difftree} + 1) . " files changed:\n");
4854 print "</div>\n";
4856 print "<table class=\"" .
4857 (@parents > 1 ? "combined " : "") .
4858 "diff_tree\">\n";
4860 # header only for combined diff in 'commitdiff' view
4861 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4862 if ($has_header) {
4863 # table header
4864 print "<thead><tr>\n" .
4865 "<th></th><th></th>\n"; # filename, patchN link
4866 for (my $i = 0; $i < @parents; $i++) {
4867 my $par = $parents[$i];
4868 print "<th>" .
4869 $cgi->a({-href => href(action=>"commitdiff",
4870 hash=>$hash, hash_parent=>$par),
4871 -title => 'commitdiff to parent number ' .
4872 ($i+1) . ': ' . substr($par,0,7)},
4873 $i+1) .
4874 "&nbsp;</th>\n";
4876 print "</tr></thead>\n<tbody>\n";
4879 my $alternate = 1;
4880 my $patchno = 0;
4881 foreach my $line (@{$difftree}) {
4882 my $diff = parsed_difftree_line($line);
4884 if ($alternate) {
4885 print "<tr class=\"dark\">\n";
4886 } else {
4887 print "<tr class=\"light\">\n";
4889 $alternate ^= 1;
4891 if (exists $diff->{'nparents'}) { # combined diff
4893 fill_from_file_info($diff, @parents)
4894 unless exists $diff->{'from_file'};
4896 if (!is_deleted($diff)) {
4897 # file exists in the result (child) commit
4898 print "<td>" .
4899 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4900 file_name=>$diff->{'to_file'},
4901 hash_base=>$hash),
4902 -class => "list"}, esc_path($diff->{'to_file'})) .
4903 "</td>\n";
4904 } else {
4905 print "<td>" .
4906 esc_path($diff->{'to_file'}) .
4907 "</td>\n";
4910 if ($action eq 'commitdiff') {
4911 # link to patch
4912 $patchno++;
4913 print "<td class=\"link\">" .
4914 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4915 "patch") .
4916 " | " .
4917 "</td>\n";
4920 my $has_history = 0;
4921 my $not_deleted = 0;
4922 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4923 my $hash_parent = $parents[$i];
4924 my $from_hash = $diff->{'from_id'}[$i];
4925 my $from_path = $diff->{'from_file'}[$i];
4926 my $status = $diff->{'status'}[$i];
4928 $has_history ||= ($status ne 'A');
4929 $not_deleted ||= ($status ne 'D');
4931 if ($status eq 'A') {
4932 print "<td class=\"link\" align=\"right\"> | </td>\n";
4933 } elsif ($status eq 'D') {
4934 print "<td class=\"link\">" .
4935 $cgi->a({-href => href(action=>"blob",
4936 hash_base=>$hash,
4937 hash=>$from_hash,
4938 file_name=>$from_path)},
4939 "blob" . ($i+1)) .
4940 " | </td>\n";
4941 } else {
4942 if ($diff->{'to_id'} eq $from_hash) {
4943 print "<td class=\"link nochange\">";
4944 } else {
4945 print "<td class=\"link\">";
4947 print $cgi->a({-href => href(action=>"blobdiff",
4948 hash=>$diff->{'to_id'},
4949 hash_parent=>$from_hash,
4950 hash_base=>$hash,
4951 hash_parent_base=>$hash_parent,
4952 file_name=>$diff->{'to_file'},
4953 file_parent=>$from_path)},
4954 "diff" . ($i+1)) .
4955 " | </td>\n";
4959 print "<td class=\"link\">";
4960 if ($not_deleted) {
4961 print $cgi->a({-href => href(action=>"blob",
4962 hash=>$diff->{'to_id'},
4963 file_name=>$diff->{'to_file'},
4964 hash_base=>$hash)},
4965 "blob");
4966 print " | " if ($has_history);
4968 if ($has_history) {
4969 print $cgi->a({-href => href(action=>"history",
4970 file_name=>$diff->{'to_file'},
4971 hash_base=>$hash)},
4972 "history");
4974 print "</td>\n";
4976 print "</tr>\n";
4977 next; # instead of 'else' clause, to avoid extra indent
4979 # else ordinary diff
4981 my ($to_mode_oct, $to_mode_str, $to_file_type);
4982 my ($from_mode_oct, $from_mode_str, $from_file_type);
4983 if ($diff->{'to_mode'} ne ('0' x 6)) {
4984 $to_mode_oct = oct $diff->{'to_mode'};
4985 if (S_ISREG($to_mode_oct)) { # only for regular file
4986 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4988 $to_file_type = file_type($diff->{'to_mode'});
4990 if ($diff->{'from_mode'} ne ('0' x 6)) {
4991 $from_mode_oct = oct $diff->{'from_mode'};
4992 if (S_ISREG($from_mode_oct)) { # only for regular file
4993 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4995 $from_file_type = file_type($diff->{'from_mode'});
4998 if ($diff->{'status'} eq "A") { # created
4999 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5000 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5001 $mode_chng .= "]</span>";
5002 print "<td>";
5003 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5004 hash_base=>$hash, file_name=>$diff->{'file'}),
5005 -class => "list"}, esc_path($diff->{'file'}));
5006 print "</td>\n";
5007 print "<td>$mode_chng</td>\n";
5008 print "<td class=\"link\">";
5009 if ($action eq 'commitdiff') {
5010 # link to patch
5011 $patchno++;
5012 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5013 "patch") .
5014 " | ";
5016 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5017 hash_base=>$hash, file_name=>$diff->{'file'})},
5018 "blob");
5019 print "</td>\n";
5021 } elsif ($diff->{'status'} eq "D") { # deleted
5022 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5023 print "<td>";
5024 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5025 hash_base=>$parent, file_name=>$diff->{'file'}),
5026 -class => "list"}, esc_path($diff->{'file'}));
5027 print "</td>\n";
5028 print "<td>$mode_chng</td>\n";
5029 print "<td class=\"link\">";
5030 if ($action eq 'commitdiff') {
5031 # link to patch
5032 $patchno++;
5033 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5034 "patch") .
5035 " | ";
5037 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5038 hash_base=>$parent, file_name=>$diff->{'file'})},
5039 "blob") . " | ";
5040 if ($have_blame) {
5041 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5042 file_name=>$diff->{'file'})},
5043 "blame") . " | ";
5045 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5046 file_name=>$diff->{'file'})},
5047 "history");
5048 print "</td>\n";
5050 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5051 my $mode_chnge = "";
5052 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5053 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5054 if ($from_file_type ne $to_file_type) {
5055 $mode_chnge .= " from $from_file_type to $to_file_type";
5057 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5058 if ($from_mode_str && $to_mode_str) {
5059 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5060 } elsif ($to_mode_str) {
5061 $mode_chnge .= " mode: $to_mode_str";
5064 $mode_chnge .= "]</span>\n";
5066 print "<td>";
5067 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5068 hash_base=>$hash, file_name=>$diff->{'file'}),
5069 -class => "list"}, esc_path($diff->{'file'}));
5070 print "</td>\n";
5071 print "<td>$mode_chnge</td>\n";
5072 print "<td class=\"link\">";
5073 if ($action eq 'commitdiff') {
5074 # link to patch
5075 $patchno++;
5076 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5077 "patch") .
5078 " | ";
5079 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5080 # "commit" view and modified file (not onlu mode changed)
5081 print $cgi->a({-href => href(action=>"blobdiff",
5082 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5083 hash_base=>$hash, hash_parent_base=>$parent,
5084 file_name=>$diff->{'file'})},
5085 "diff") .
5086 " | ";
5088 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5089 hash_base=>$hash, file_name=>$diff->{'file'})},
5090 "blob") . " | ";
5091 if ($have_blame) {
5092 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5093 file_name=>$diff->{'file'})},
5094 "blame") . " | ";
5096 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5097 file_name=>$diff->{'file'})},
5098 "history");
5099 print "</td>\n";
5101 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5102 my %status_name = ('R' => 'moved', 'C' => 'copied');
5103 my $nstatus = $status_name{$diff->{'status'}};
5104 my $mode_chng = "";
5105 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5106 # mode also for directories, so we cannot use $to_mode_str
5107 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5109 print "<td>" .
5110 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5111 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5112 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5113 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5114 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5115 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5116 -class => "list"}, esc_path($diff->{'from_file'})) .
5117 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5118 "<td class=\"link\">";
5119 if ($action eq 'commitdiff') {
5120 # link to patch
5121 $patchno++;
5122 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5123 "patch") .
5124 " | ";
5125 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5126 # "commit" view and modified file (not only pure rename or copy)
5127 print $cgi->a({-href => href(action=>"blobdiff",
5128 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5129 hash_base=>$hash, hash_parent_base=>$parent,
5130 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5131 "diff") .
5132 " | ";
5134 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5135 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5136 "blob") . " | ";
5137 if ($have_blame) {
5138 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5139 file_name=>$diff->{'to_file'})},
5140 "blame") . " | ";
5142 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5143 file_name=>$diff->{'to_file'})},
5144 "history");
5145 print "</td>\n";
5147 } # we should not encounter Unmerged (U) or Unknown (X) status
5148 print "</tr>\n";
5150 print "</tbody>" if $has_header;
5151 print "</table>\n";
5154 # Print context lines and then rem/add lines in a side-by-side manner.
5155 sub print_sidebyside_diff_lines {
5156 my ($ctx, $rem, $add) = @_;
5158 # print context block before add/rem block
5159 if (@$ctx) {
5160 print join '',
5161 '<div class="chunk_block ctx">',
5162 '<div class="old">',
5163 @$ctx,
5164 '</div>',
5165 '<div class="new">',
5166 @$ctx,
5167 '</div>',
5168 '</div>';
5171 if (!@$add) {
5172 # pure removal
5173 print join '',
5174 '<div class="chunk_block rem">',
5175 '<div class="old">',
5176 @$rem,
5177 '</div>',
5178 '</div>';
5179 } elsif (!@$rem) {
5180 # pure addition
5181 print join '',
5182 '<div class="chunk_block add">',
5183 '<div class="new">',
5184 @$add,
5185 '</div>',
5186 '</div>';
5187 } else {
5188 print join '',
5189 '<div class="chunk_block chg">',
5190 '<div class="old">',
5191 @$rem,
5192 '</div>',
5193 '<div class="new">',
5194 @$add,
5195 '</div>',
5196 '</div>';
5200 # Print context lines and then rem/add lines in inline manner.
5201 sub print_inline_diff_lines {
5202 my ($ctx, $rem, $add) = @_;
5204 print @$ctx, @$rem, @$add;
5207 # Format removed and added line, mark changed part and HTML-format them.
5208 # Implementation is based on contrib/diff-highlight
5209 sub format_rem_add_lines_pair {
5210 my ($rem, $add, $num_parents) = @_;
5212 # We need to untabify lines before split()'ing them;
5213 # otherwise offsets would be invalid.
5214 chomp $rem;
5215 chomp $add;
5216 $rem = untabify($rem);
5217 $add = untabify($add);
5219 my @rem = split(//, $rem);
5220 my @add = split(//, $add);
5221 my ($esc_rem, $esc_add);
5222 # Ignore leading +/- characters for each parent.
5223 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5224 my ($prefix_has_nonspace, $suffix_has_nonspace);
5226 my $shorter = (@rem < @add) ? @rem : @add;
5227 while ($prefix_len < $shorter) {
5228 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5230 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5231 $prefix_len++;
5234 while ($prefix_len + $suffix_len < $shorter) {
5235 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5237 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5238 $suffix_len++;
5241 # Mark lines that are different from each other, but have some common
5242 # part that isn't whitespace. If lines are completely different, don't
5243 # mark them because that would make output unreadable, especially if
5244 # diff consists of multiple lines.
5245 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5246 $esc_rem = esc_html_hl_regions($rem, 'marked',
5247 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5248 $esc_add = esc_html_hl_regions($add, 'marked',
5249 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5250 } else {
5251 $esc_rem = esc_html($rem, -nbsp=>1);
5252 $esc_add = esc_html($add, -nbsp=>1);
5255 return format_diff_line(\$esc_rem, 'rem'),
5256 format_diff_line(\$esc_add, 'add');
5259 # HTML-format diff context, removed and added lines.
5260 sub format_ctx_rem_add_lines {
5261 my ($ctx, $rem, $add, $num_parents) = @_;
5262 my (@new_ctx, @new_rem, @new_add);
5263 my $can_highlight = 0;
5264 my $is_combined = ($num_parents > 1);
5266 # Highlight if every removed line has a corresponding added line.
5267 if (@$add > 0 && @$add == @$rem) {
5268 $can_highlight = 1;
5270 # Highlight lines in combined diff only if the chunk contains
5271 # diff between the same version, e.g.
5273 # - a
5274 # - b
5275 # + c
5276 # + d
5278 # Otherwise the highlightling would be confusing.
5279 if ($is_combined) {
5280 for (my $i = 0; $i < @$add; $i++) {
5281 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5282 my $prefix_add = substr($add->[$i], 0, $num_parents);
5284 $prefix_rem =~ s/-/+/g;
5286 if ($prefix_rem ne $prefix_add) {
5287 $can_highlight = 0;
5288 last;
5294 if ($can_highlight) {
5295 for (my $i = 0; $i < @$add; $i++) {
5296 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5297 $rem->[$i], $add->[$i], $num_parents);
5298 push @new_rem, $line_rem;
5299 push @new_add, $line_add;
5301 } else {
5302 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5303 @new_add = map { format_diff_line($_, 'add') } @$add;
5306 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5308 return (\@new_ctx, \@new_rem, \@new_add);
5311 # Print context lines and then rem/add lines.
5312 sub print_diff_lines {
5313 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5314 my $is_combined = $num_parents > 1;
5316 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5317 $num_parents);
5319 if ($diff_style eq 'sidebyside' && !$is_combined) {
5320 print_sidebyside_diff_lines($ctx, $rem, $add);
5321 } else {
5322 # default 'inline' style and unknown styles
5323 print_inline_diff_lines($ctx, $rem, $add);
5327 sub print_diff_chunk {
5328 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5329 my (@ctx, @rem, @add);
5331 # The class of the previous line.
5332 my $prev_class = '';
5334 return unless @chunk;
5336 # incomplete last line might be among removed or added lines,
5337 # or both, or among context lines: find which
5338 for (my $i = 1; $i < @chunk; $i++) {
5339 if ($chunk[$i][0] eq 'incomplete') {
5340 $chunk[$i][0] = $chunk[$i-1][0];
5344 # guardian
5345 push @chunk, ["", ""];
5347 foreach my $line_info (@chunk) {
5348 my ($class, $line) = @$line_info;
5350 # print chunk headers
5351 if ($class && $class eq 'chunk_header') {
5352 print format_diff_line($line, $class, $from, $to);
5353 next;
5356 ## print from accumulator when have some add/rem lines or end
5357 # of chunk (flush context lines), or when have add and rem
5358 # lines and new block is reached (otherwise add/rem lines could
5359 # be reordered)
5360 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5361 (@rem && @add && $class ne $prev_class)) {
5362 print_diff_lines(\@ctx, \@rem, \@add,
5363 $diff_style, $num_parents);
5364 @ctx = @rem = @add = ();
5367 ## adding lines to accumulator
5368 # guardian value
5369 last unless $line;
5370 # rem, add or change
5371 if ($class eq 'rem') {
5372 push @rem, $line;
5373 } elsif ($class eq 'add') {
5374 push @add, $line;
5376 # context line
5377 if ($class eq 'ctx') {
5378 push @ctx, $line;
5381 $prev_class = $class;
5385 sub git_patchset_body {
5386 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5387 my ($hash_parent) = $hash_parents[0];
5389 my $is_combined = (@hash_parents > 1);
5390 my $patch_idx = 0;
5391 my $patch_number = 0;
5392 my $patch_line;
5393 my $diffinfo;
5394 my $to_name;
5395 my (%from, %to);
5396 my @chunk; # for side-by-side diff
5398 print "<div class=\"patchset\">\n";
5400 # skip to first patch
5401 while ($patch_line = <$fd>) {
5402 chomp $patch_line;
5404 last if ($patch_line =~ m/^diff /);
5407 PATCH:
5408 while ($patch_line) {
5410 # parse "git diff" header line
5411 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5412 # $1 is from_name, which we do not use
5413 $to_name = unquote($2);
5414 $to_name =~ s!^b/!!;
5415 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5416 # $1 is 'cc' or 'combined', which we do not use
5417 $to_name = unquote($2);
5418 } else {
5419 $to_name = undef;
5422 # check if current patch belong to current raw line
5423 # and parse raw git-diff line if needed
5424 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5425 # this is continuation of a split patch
5426 print "<div class=\"patch cont\">\n";
5427 } else {
5428 # advance raw git-diff output if needed
5429 $patch_idx++ if defined $diffinfo;
5431 # read and prepare patch information
5432 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5434 # compact combined diff output can have some patches skipped
5435 # find which patch (using pathname of result) we are at now;
5436 if ($is_combined) {
5437 while ($to_name ne $diffinfo->{'to_file'}) {
5438 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5439 format_diff_cc_simplified($diffinfo, @hash_parents) .
5440 "</div>\n"; # class="patch"
5442 $patch_idx++;
5443 $patch_number++;
5445 last if $patch_idx > $#$difftree;
5446 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5450 # modifies %from, %to hashes
5451 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5453 # this is first patch for raw difftree line with $patch_idx index
5454 # we index @$difftree array from 0, but number patches from 1
5455 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5458 # git diff header
5459 #assert($patch_line =~ m/^diff /) if DEBUG;
5460 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5461 $patch_number++;
5462 # print "git diff" header
5463 print format_git_diff_header_line($patch_line, $diffinfo,
5464 \%from, \%to);
5466 # print extended diff header
5467 print "<div class=\"diff extended_header\">\n";
5468 EXTENDED_HEADER:
5469 while ($patch_line = <$fd>) {
5470 chomp $patch_line;
5472 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5474 print format_extended_diff_header_line($patch_line, $diffinfo,
5475 \%from, \%to);
5477 print "</div>\n"; # class="diff extended_header"
5479 # from-file/to-file diff header
5480 if (! $patch_line) {
5481 print "</div>\n"; # class="patch"
5482 last PATCH;
5484 next PATCH if ($patch_line =~ m/^diff /);
5485 #assert($patch_line =~ m/^---/) if DEBUG;
5487 my $last_patch_line = $patch_line;
5488 $patch_line = <$fd>;
5489 chomp $patch_line;
5490 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5492 print format_diff_from_to_header($last_patch_line, $patch_line,
5493 $diffinfo, \%from, \%to,
5494 @hash_parents);
5496 # the patch itself
5497 LINE:
5498 while ($patch_line = <$fd>) {
5499 chomp $patch_line;
5501 next PATCH if ($patch_line =~ m/^diff /);
5503 my $class = diff_line_class($patch_line, \%from, \%to);
5505 if ($class eq 'chunk_header') {
5506 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5507 @chunk = ();
5510 push @chunk, [ $class, $patch_line ];
5513 } continue {
5514 if (@chunk) {
5515 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5516 @chunk = ();
5518 print "</div>\n"; # class="patch"
5521 # for compact combined (--cc) format, with chunk and patch simplification
5522 # the patchset might be empty, but there might be unprocessed raw lines
5523 for (++$patch_idx if $patch_number > 0;
5524 $patch_idx < @$difftree;
5525 ++$patch_idx) {
5526 # read and prepare patch information
5527 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5529 # generate anchor for "patch" links in difftree / whatchanged part
5530 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5531 format_diff_cc_simplified($diffinfo, @hash_parents) .
5532 "</div>\n"; # class="patch"
5534 $patch_number++;
5537 if ($patch_number == 0) {
5538 if (@hash_parents > 1) {
5539 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5540 } else {
5541 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5545 print "</div>\n"; # class="patchset"
5548 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5550 sub git_project_search_form {
5551 my ($searchtext, $search_use_regexp) = @_;
5553 my $limit = '';
5554 if ($project_filter) {
5555 $limit = " in '$project_filter/'";
5558 print "<div class=\"projsearch\">\n";
5559 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5560 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5561 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5562 if (defined $project_filter);
5563 print $cgi->textfield(-name => 's', -value => $searchtext,
5564 -title => "Search project by name and description$limit",
5565 -size => 60) . "\n" .
5566 "<span title=\"Extended regular expression\">" .
5567 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5568 -checked => $search_use_regexp) .
5569 "</span>\n" .
5570 $cgi->submit(-name => 'btnS', -value => 'Search') .
5571 $cgi->end_form() . "\n" .
5572 $cgi->a({-href => href(project => undef, searchtext => undef,
5573 project_filter => $project_filter)},
5574 esc_html("List all projects$limit")) . "<br />\n";
5575 print "</div>\n";
5578 # entry for given @keys needs filling if at least one of keys in list
5579 # is not present in %$project_info
5580 sub project_info_needs_filling {
5581 my ($project_info, @keys) = @_;
5583 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5584 foreach my $key (@keys) {
5585 if (!exists $project_info->{$key}) {
5586 return 1;
5589 return;
5592 # fills project list info (age, description, owner, category, forks, etc.)
5593 # for each project in the list, removing invalid projects from
5594 # returned list, or fill only specified info.
5596 # Invalid projects are removed from the returned list if and only if you
5597 # ask 'age' or 'age_string' to be filled, because they are the only fields
5598 # that run unconditionally git command that requires repository, and
5599 # therefore do always check if project repository is invalid.
5601 # USAGE:
5602 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5603 # ensures that 'descr_long' and 'ctags' fields are filled
5604 # * @project_list = fill_project_list_info(\@project_list)
5605 # ensures that all fields are filled (and invalid projects removed)
5607 # NOTE: modifies $projlist, but does not remove entries from it
5608 sub fill_project_list_info {
5609 my ($projlist, @wanted_keys) = @_;
5610 my @projects;
5611 my $filter_set = sub { return @_; };
5612 if (@wanted_keys) {
5613 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5614 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5617 my $show_ctags = gitweb_check_feature('ctags');
5618 PROJECT:
5619 foreach my $pr (@$projlist) {
5620 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5621 my (@activity) = git_get_last_activity($pr->{'path'});
5622 unless (@activity) {
5623 next PROJECT;
5625 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5627 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5628 my $descr = git_get_project_description($pr->{'path'}) || "";
5629 $descr = to_utf8($descr);
5630 $pr->{'descr_long'} = $descr;
5631 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5633 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5634 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5636 if ($show_ctags &&
5637 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5638 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5640 if ($projects_list_group_categories &&
5641 project_info_needs_filling($pr, $filter_set->('category'))) {
5642 my $cat = git_get_project_category($pr->{'path'}) ||
5643 $project_list_default_category;
5644 $pr->{'category'} = to_utf8($cat);
5647 push @projects, $pr;
5650 return @projects;
5653 sub sort_projects_list {
5654 my ($projlist, $order) = @_;
5656 sub order_str {
5657 my $key = shift;
5658 return sub { $a->{$key} cmp $b->{$key} };
5661 sub order_num_then_undef {
5662 my $key = shift;
5663 return sub {
5664 defined $a->{$key} ?
5665 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5666 (defined $b->{$key} ? 1 : 0)
5670 my %orderings = (
5671 project => order_str('path'),
5672 descr => order_str('descr_long'),
5673 owner => order_str('owner'),
5674 age => order_num_then_undef('age'),
5677 my $ordering = $orderings{$order};
5678 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5681 # returns a hash of categories, containing the list of project
5682 # belonging to each category
5683 sub build_projlist_by_category {
5684 my ($projlist, $from, $to) = @_;
5685 my %categories;
5687 $from = 0 unless defined $from;
5688 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5690 for (my $i = $from; $i <= $to; $i++) {
5691 my $pr = $projlist->[$i];
5692 push @{$categories{ $pr->{'category'} }}, $pr;
5695 return wantarray ? %categories : \%categories;
5698 # print 'sort by' <th> element, generating 'sort by $name' replay link
5699 # if that order is not selected
5700 sub print_sort_th {
5701 print format_sort_th(@_);
5704 sub format_sort_th {
5705 my ($name, $order, $header) = @_;
5706 my $sort_th = "";
5707 $header ||= ucfirst($name);
5709 if ($order eq $name) {
5710 $sort_th .= "<th>$header</th>\n";
5711 } else {
5712 $sort_th .= "<th>" .
5713 $cgi->a({-href => href(-replay=>1, order=>$name),
5714 -class => "header"}, $header) .
5715 "</th>\n";
5718 return $sort_th;
5721 sub git_project_list_rows {
5722 my ($projlist, $from, $to, $check_forks) = @_;
5724 $from = 0 unless defined $from;
5725 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5727 my $alternate = 1;
5728 for (my $i = $from; $i <= $to; $i++) {
5729 my $pr = $projlist->[$i];
5731 if ($alternate) {
5732 print "<tr class=\"dark\">\n";
5733 } else {
5734 print "<tr class=\"light\">\n";
5736 $alternate ^= 1;
5738 if ($check_forks) {
5739 print "<td>";
5740 if ($pr->{'forks'}) {
5741 my $nforks = scalar @{$pr->{'forks'}};
5742 if ($nforks > 0) {
5743 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5744 -title => "$nforks forks"}, "+");
5745 } else {
5746 print $cgi->span({-title => "$nforks forks"}, "+");
5749 print "</td>\n";
5751 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5752 -class => "list"},
5753 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5754 "</td>\n" .
5755 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5756 -class => "list",
5757 -title => $pr->{'descr_long'}},
5758 $search_regexp
5759 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5760 $pr->{'descr'}, $search_regexp)
5761 : esc_html($pr->{'descr'})) .
5762 "</td>\n";
5763 unless ($omit_owner) {
5764 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5766 unless ($omit_age_column) {
5767 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5768 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5770 print"<td class=\"link\">" .
5771 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5772 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5773 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5774 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5775 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5776 "</td>\n" .
5777 "</tr>\n";
5781 sub git_project_list_body {
5782 # actually uses global variable $project
5783 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5784 my @projects = @$projlist;
5786 my $check_forks = gitweb_check_feature('forks');
5787 my $show_ctags = gitweb_check_feature('ctags');
5788 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5789 $check_forks = undef
5790 if ($tagfilter || $search_regexp);
5792 # filtering out forks before filling info allows to do less work
5793 @projects = filter_forks_from_projects_list(\@projects)
5794 if ($check_forks);
5795 # search_projects_list pre-fills required info
5796 @projects = search_projects_list(\@projects,
5797 'search_regexp' => $search_regexp,
5798 'tagfilter' => $tagfilter)
5799 if ($tagfilter || $search_regexp);
5800 # fill the rest
5801 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5802 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5803 push @all_fields, 'owner' unless($omit_owner);
5804 @projects = fill_project_list_info(\@projects, @all_fields);
5806 $order ||= $default_projects_order;
5807 $from = 0 unless defined $from;
5808 $to = $#projects if (!defined $to || $#projects < $to);
5810 # short circuit
5811 if ($from > $to) {
5812 print "<center>\n".
5813 "<b>No such projects found</b><br />\n".
5814 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5815 "</center>\n<br />\n";
5816 return;
5819 @projects = sort_projects_list(\@projects, $order);
5821 if ($show_ctags) {
5822 my $ctags = git_gather_all_ctags(\@projects);
5823 my $cloud = git_populate_project_tagcloud($ctags);
5824 print git_show_project_tagcloud($cloud, 64);
5827 print "<table class=\"project_list\">\n";
5828 unless ($no_header) {
5829 print "<tr>\n";
5830 if ($check_forks) {
5831 print "<th></th>\n";
5833 print_sort_th('project', $order, 'Project');
5834 print_sort_th('descr', $order, 'Description');
5835 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5836 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5837 print "<th></th>\n" . # for links
5838 "</tr>\n";
5841 if ($projects_list_group_categories) {
5842 # only display categories with projects in the $from-$to window
5843 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5844 my %categories = build_projlist_by_category(\@projects, $from, $to);
5845 foreach my $cat (sort keys %categories) {
5846 unless ($cat eq "") {
5847 print "<tr>\n";
5848 if ($check_forks) {
5849 print "<td></td>\n";
5851 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5852 print "</tr>\n";
5855 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5857 } else {
5858 git_project_list_rows(\@projects, $from, $to, $check_forks);
5861 if (defined $extra) {
5862 print "<tr>\n";
5863 if ($check_forks) {
5864 print "<td></td>\n";
5866 print "<td colspan=\"5\">$extra</td>\n" .
5867 "</tr>\n";
5869 print "</table>\n";
5872 sub git_log_body {
5873 # uses global variable $project
5874 my ($commitlist, $from, $to, $refs, $extra) = @_;
5876 $from = 0 unless defined $from;
5877 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5879 for (my $i = 0; $i <= $to; $i++) {
5880 my %co = %{$commitlist->[$i]};
5881 next if !%co;
5882 my $commit = $co{'id'};
5883 my $ref = format_ref_marker($refs, $commit);
5884 git_print_header_div('commit',
5885 "<span class=\"age\">$co{'age_string'}</span>" .
5886 esc_html($co{'title'}) . $ref,
5887 $commit);
5888 print "<div class=\"title_text\">\n" .
5889 "<div class=\"log_link\">\n" .
5890 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5891 " | " .
5892 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5893 " | " .
5894 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5895 "<br/>\n" .
5896 "</div>\n";
5897 git_print_authorship(\%co, -tag => 'span');
5898 print "<br/>\n</div>\n";
5900 print "<div class=\"log_body\">\n";
5901 git_print_log($co{'comment'}, -final_empty_line=> 1);
5902 print "</div>\n";
5904 if ($extra) {
5905 print "<div class=\"page_nav\">\n";
5906 print "$extra\n";
5907 print "</div>\n";
5911 sub git_shortlog_body {
5912 # uses global variable $project
5913 my ($commitlist, $from, $to, $refs, $extra) = @_;
5915 $from = 0 unless defined $from;
5916 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5918 print "<table class=\"shortlog\">\n";
5919 my $alternate = 1;
5920 for (my $i = $from; $i <= $to; $i++) {
5921 my %co = %{$commitlist->[$i]};
5922 my $commit = $co{'id'};
5923 my $ref = format_ref_marker($refs, $commit);
5924 if ($alternate) {
5925 print "<tr class=\"dark\">\n";
5926 } else {
5927 print "<tr class=\"light\">\n";
5929 $alternate ^= 1;
5930 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5931 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5932 format_author_html('td', \%co, 10) . "<td>";
5933 print format_subject_html($co{'title'}, $co{'title_short'},
5934 href(action=>"commit", hash=>$commit), $ref);
5935 print "</td>\n" .
5936 "<td class=\"link\">" .
5937 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5938 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5939 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5940 my $snapshot_links = format_snapshot_links($commit);
5941 if (defined $snapshot_links) {
5942 print " | " . $snapshot_links;
5944 print "</td>\n" .
5945 "</tr>\n";
5947 if (defined $extra) {
5948 print "<tr>\n" .
5949 "<td colspan=\"4\">$extra</td>\n" .
5950 "</tr>\n";
5952 print "</table>\n";
5955 sub git_history_body {
5956 # Warning: assumes constant type (blob or tree) during history
5957 my ($commitlist, $from, $to, $refs, $extra,
5958 $file_name, $file_hash, $ftype) = @_;
5960 $from = 0 unless defined $from;
5961 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5963 print "<table class=\"history\">\n";
5964 my $alternate = 1;
5965 for (my $i = $from; $i <= $to; $i++) {
5966 my %co = %{$commitlist->[$i]};
5967 if (!%co) {
5968 next;
5970 my $commit = $co{'id'};
5972 my $ref = format_ref_marker($refs, $commit);
5974 if ($alternate) {
5975 print "<tr class=\"dark\">\n";
5976 } else {
5977 print "<tr class=\"light\">\n";
5979 $alternate ^= 1;
5980 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5981 # shortlog: format_author_html('td', \%co, 10)
5982 format_author_html('td', \%co, 15, 3) . "<td>";
5983 # originally git_history used chop_str($co{'title'}, 50)
5984 print format_subject_html($co{'title'}, $co{'title_short'},
5985 href(action=>"commit", hash=>$commit), $ref);
5986 print "</td>\n" .
5987 "<td class=\"link\">" .
5988 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5989 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5991 if ($ftype eq 'blob') {
5992 my $blob_current = $file_hash;
5993 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5994 if (defined $blob_current && defined $blob_parent &&
5995 $blob_current ne $blob_parent) {
5996 print " | " .
5997 $cgi->a({-href => href(action=>"blobdiff",
5998 hash=>$blob_current, hash_parent=>$blob_parent,
5999 hash_base=>$hash_base, hash_parent_base=>$commit,
6000 file_name=>$file_name)},
6001 "diff to current");
6004 print "</td>\n" .
6005 "</tr>\n";
6007 if (defined $extra) {
6008 print "<tr>\n" .
6009 "<td colspan=\"4\">$extra</td>\n" .
6010 "</tr>\n";
6012 print "</table>\n";
6015 sub git_tags_body {
6016 # uses global variable $project
6017 my ($taglist, $from, $to, $extra) = @_;
6018 $from = 0 unless defined $from;
6019 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6021 print "<table class=\"tags\">\n";
6022 my $alternate = 1;
6023 for (my $i = $from; $i <= $to; $i++) {
6024 my $entry = $taglist->[$i];
6025 my %tag = %$entry;
6026 my $comment = $tag{'subject'};
6027 my $comment_short;
6028 if (defined $comment) {
6029 $comment_short = chop_str($comment, 30, 5);
6031 if ($alternate) {
6032 print "<tr class=\"dark\">\n";
6033 } else {
6034 print "<tr class=\"light\">\n";
6036 $alternate ^= 1;
6037 if (defined $tag{'age'}) {
6038 print "<td><i>$tag{'age'}</i></td>\n";
6039 } else {
6040 print "<td></td>\n";
6042 print "<td>" .
6043 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6044 -class => "list name"}, esc_html($tag{'name'})) .
6045 "</td>\n" .
6046 "<td>";
6047 if (defined $comment) {
6048 print format_subject_html($comment, $comment_short,
6049 href(action=>"tag", hash=>$tag{'id'}));
6051 print "</td>\n" .
6052 "<td class=\"selflink\">";
6053 if ($tag{'type'} eq "tag") {
6054 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6055 } else {
6056 print "&nbsp;";
6058 print "</td>\n" .
6059 "<td class=\"link\">" . " | " .
6060 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6061 if ($tag{'reftype'} eq "commit") {
6062 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6063 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6064 } elsif ($tag{'reftype'} eq "blob") {
6065 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6067 print "</td>\n" .
6068 "</tr>";
6070 if (defined $extra) {
6071 print "<tr>\n" .
6072 "<td colspan=\"5\">$extra</td>\n" .
6073 "</tr>\n";
6075 print "</table>\n";
6078 sub git_heads_body {
6079 # uses global variable $project
6080 my ($headlist, $head_at, $from, $to, $extra) = @_;
6081 $from = 0 unless defined $from;
6082 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6084 print "<table class=\"heads\">\n";
6085 my $alternate = 1;
6086 for (my $i = $from; $i <= $to; $i++) {
6087 my $entry = $headlist->[$i];
6088 my %ref = %$entry;
6089 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6090 if ($alternate) {
6091 print "<tr class=\"dark\">\n";
6092 } else {
6093 print "<tr class=\"light\">\n";
6095 $alternate ^= 1;
6096 print "<td><i>$ref{'age'}</i></td>\n" .
6097 ($curr ? "<td class=\"current_head\">" : "<td>") .
6098 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6099 -class => "list name"},esc_html($ref{'name'})) .
6100 "</td>\n" .
6101 "<td class=\"link\">" .
6102 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6103 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6104 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6105 "</td>\n" .
6106 "</tr>";
6108 if (defined $extra) {
6109 print "<tr>\n" .
6110 "<td colspan=\"3\">$extra</td>\n" .
6111 "</tr>\n";
6113 print "</table>\n";
6116 # Display a single remote block
6117 sub git_remote_block {
6118 my ($remote, $rdata, $limit, $head) = @_;
6120 my $heads = $rdata->{'heads'};
6121 my $fetch = $rdata->{'fetch'};
6122 my $push = $rdata->{'push'};
6124 my $urls_table = "<table class=\"projects_list\">\n" ;
6126 if (defined $fetch) {
6127 if ($fetch eq $push) {
6128 $urls_table .= format_repo_url("URL", $fetch);
6129 } else {
6130 $urls_table .= format_repo_url("Fetch URL", $fetch);
6131 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6133 } elsif (defined $push) {
6134 $urls_table .= format_repo_url("Push URL", $push);
6135 } else {
6136 $urls_table .= format_repo_url("", "No remote URL");
6139 $urls_table .= "</table>\n";
6141 my $dots;
6142 if (defined $limit && $limit < @$heads) {
6143 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6146 print $urls_table;
6147 git_heads_body($heads, $head, 0, $limit, $dots);
6150 # Display a list of remote names with the respective fetch and push URLs
6151 sub git_remotes_list {
6152 my ($remotedata, $limit) = @_;
6153 print "<table class=\"heads\">\n";
6154 my $alternate = 1;
6155 my @remotes = sort keys %$remotedata;
6157 my $limited = $limit && $limit < @remotes;
6159 $#remotes = $limit - 1 if $limited;
6161 while (my $remote = shift @remotes) {
6162 my $rdata = $remotedata->{$remote};
6163 my $fetch = $rdata->{'fetch'};
6164 my $push = $rdata->{'push'};
6165 if ($alternate) {
6166 print "<tr class=\"dark\">\n";
6167 } else {
6168 print "<tr class=\"light\">\n";
6170 $alternate ^= 1;
6171 print "<td>" .
6172 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6173 -class=> "list name"},esc_html($remote)) .
6174 "</td>";
6175 print "<td class=\"link\">" .
6176 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6177 " | " .
6178 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6179 "</td>";
6181 print "</tr>\n";
6184 if ($limited) {
6185 print "<tr>\n" .
6186 "<td colspan=\"3\">" .
6187 $cgi->a({-href => href(action=>"remotes")}, "...") .
6188 "</td>\n" . "</tr>\n";
6191 print "</table>";
6194 # Display remote heads grouped by remote, unless there are too many
6195 # remotes, in which case we only display the remote names
6196 sub git_remotes_body {
6197 my ($remotedata, $limit, $head) = @_;
6198 if ($limit and $limit < keys %$remotedata) {
6199 git_remotes_list($remotedata, $limit);
6200 } else {
6201 fill_remote_heads($remotedata);
6202 while (my ($remote, $rdata) = each %$remotedata) {
6203 git_print_section({-class=>"remote", -id=>$remote},
6204 ["remotes", $remote, $remote], sub {
6205 git_remote_block($remote, $rdata, $limit, $head);
6211 sub git_search_message {
6212 my %co = @_;
6214 my $greptype;
6215 if ($searchtype eq 'commit') {
6216 $greptype = "--grep=";
6217 } elsif ($searchtype eq 'author') {
6218 $greptype = "--author=";
6219 } elsif ($searchtype eq 'committer') {
6220 $greptype = "--committer=";
6222 $greptype .= $searchtext;
6223 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6224 $greptype, '--regexp-ignore-case',
6225 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6227 my $paging_nav = '';
6228 if ($page > 0) {
6229 $paging_nav .=
6230 $cgi->a({-href => href(-replay=>1, page=>undef)},
6231 "first") .
6232 " &sdot; " .
6233 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6234 -accesskey => "p", -title => "Alt-p"}, "prev");
6235 } else {
6236 $paging_nav .= "first &sdot; prev";
6238 my $next_link = '';
6239 if ($#commitlist >= 100) {
6240 $next_link =
6241 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6242 -accesskey => "n", -title => "Alt-n"}, "next");
6243 $paging_nav .= " &sdot; $next_link";
6244 } else {
6245 $paging_nav .= " &sdot; next";
6248 git_header_html();
6250 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6251 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6252 if ($page == 0 && !@commitlist) {
6253 print "<p>No match.</p>\n";
6254 } else {
6255 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6258 git_footer_html();
6261 sub git_search_changes {
6262 my %co = @_;
6264 local $/ = "\n";
6265 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6266 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6267 ($search_use_regexp ? '--pickaxe-regex' : ())
6268 or die_error(500, "Open git-log failed");
6270 git_header_html();
6272 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6273 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6275 print "<table class=\"pickaxe search\">\n";
6276 my $alternate = 1;
6277 undef %co;
6278 my @files;
6279 while (my $line = <$fd>) {
6280 chomp $line;
6281 next unless $line;
6283 my %set = parse_difftree_raw_line($line);
6284 if (defined $set{'commit'}) {
6285 # finish previous commit
6286 if (%co) {
6287 print "</td>\n" .
6288 "<td class=\"link\">" .
6289 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6290 "commit") .
6291 " | " .
6292 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6293 hash_base=>$co{'id'})},
6294 "tree") .
6295 "</td>\n" .
6296 "</tr>\n";
6299 if ($alternate) {
6300 print "<tr class=\"dark\">\n";
6301 } else {
6302 print "<tr class=\"light\">\n";
6304 $alternate ^= 1;
6305 %co = parse_commit($set{'commit'});
6306 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6307 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6308 "<td><i>$author</i></td>\n" .
6309 "<td>" .
6310 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6311 -class => "list subject"},
6312 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6313 } elsif (defined $set{'to_id'}) {
6314 next if ($set{'to_id'} =~ m/^0{40}$/);
6316 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6317 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6318 -class => "list"},
6319 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6320 "<br/>\n";
6323 close $fd;
6325 # finish last commit (warning: repetition!)
6326 if (%co) {
6327 print "</td>\n" .
6328 "<td class=\"link\">" .
6329 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6330 "commit") .
6331 " | " .
6332 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6333 hash_base=>$co{'id'})},
6334 "tree") .
6335 "</td>\n" .
6336 "</tr>\n";
6339 print "</table>\n";
6341 git_footer_html();
6344 sub git_search_files {
6345 my %co = @_;
6347 local $/ = "\n";
6348 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6349 $search_use_regexp ? ('-E', '-i') : '-F',
6350 $searchtext, $co{'tree'}
6351 or die_error(500, "Open git-grep failed");
6353 git_header_html();
6355 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6356 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6358 print "<table class=\"grep_search\">\n";
6359 my $alternate = 1;
6360 my $matches = 0;
6361 my $lastfile = '';
6362 my $file_href;
6363 while (my $line = <$fd>) {
6364 chomp $line;
6365 my ($file, $lno, $ltext, $binary);
6366 last if ($matches++ > 1000);
6367 if ($line =~ /^Binary file (.+) matches$/) {
6368 $file = $1;
6369 $binary = 1;
6370 } else {
6371 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6372 $file =~ s/^$co{'tree'}://;
6374 if ($file ne $lastfile) {
6375 $lastfile and print "</td></tr>\n";
6376 if ($alternate++) {
6377 print "<tr class=\"dark\">\n";
6378 } else {
6379 print "<tr class=\"light\">\n";
6381 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6382 file_name=>$file);
6383 print "<td class=\"list\">".
6384 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6385 print "</td><td>\n";
6386 $lastfile = $file;
6388 if ($binary) {
6389 print "<div class=\"binary\">Binary file</div>\n";
6390 } else {
6391 $ltext = untabify($ltext);
6392 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6393 $ltext = esc_html($1, -nbsp=>1);
6394 $ltext .= '<span class="match">';
6395 $ltext .= esc_html($2, -nbsp=>1);
6396 $ltext .= '</span>';
6397 $ltext .= esc_html($3, -nbsp=>1);
6398 } else {
6399 $ltext = esc_html($ltext, -nbsp=>1);
6401 print "<div class=\"pre\">" .
6402 $cgi->a({-href => $file_href.'#l'.$lno,
6403 -class => "linenr"}, sprintf('%4i', $lno)) .
6404 ' ' . $ltext . "</div>\n";
6407 if ($lastfile) {
6408 print "</td></tr>\n";
6409 if ($matches > 1000) {
6410 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6412 } else {
6413 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6415 close $fd;
6417 print "</table>\n";
6419 git_footer_html();
6422 sub git_search_grep_body {
6423 my ($commitlist, $from, $to, $extra) = @_;
6424 $from = 0 unless defined $from;
6425 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6427 print "<table class=\"commit_search\">\n";
6428 my $alternate = 1;
6429 for (my $i = $from; $i <= $to; $i++) {
6430 my %co = %{$commitlist->[$i]};
6431 if (!%co) {
6432 next;
6434 my $commit = $co{'id'};
6435 if ($alternate) {
6436 print "<tr class=\"dark\">\n";
6437 } else {
6438 print "<tr class=\"light\">\n";
6440 $alternate ^= 1;
6441 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6442 format_author_html('td', \%co, 15, 5) .
6443 "<td>" .
6444 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6445 -class => "list subject"},
6446 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6447 my $comment = $co{'comment'};
6448 foreach my $line (@$comment) {
6449 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6450 my ($lead, $match, $trail) = ($1, $2, $3);
6451 $match = chop_str($match, 70, 5, 'center');
6452 my $contextlen = int((80 - length($match))/2);
6453 $contextlen = 30 if ($contextlen > 30);
6454 $lead = chop_str($lead, $contextlen, 10, 'left');
6455 $trail = chop_str($trail, $contextlen, 10, 'right');
6457 $lead = esc_html($lead);
6458 $match = esc_html($match);
6459 $trail = esc_html($trail);
6461 print "$lead<span class=\"match\">$match</span>$trail<br />";
6464 print "</td>\n" .
6465 "<td class=\"link\">" .
6466 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6467 " | " .
6468 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6469 " | " .
6470 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6471 print "</td>\n" .
6472 "</tr>\n";
6474 if (defined $extra) {
6475 print "<tr>\n" .
6476 "<td colspan=\"3\">$extra</td>\n" .
6477 "</tr>\n";
6479 print "</table>\n";
6482 ## ======================================================================
6483 ## ======================================================================
6484 ## actions
6486 sub git_project_list {
6487 my $order = $input_params{'order'};
6488 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6489 die_error(400, "Unknown order parameter");
6492 my @list = git_get_projects_list($project_filter, $strict_export);
6493 if (!@list) {
6494 die_error(404, "No projects found");
6497 git_header_html();
6498 if (defined $home_text && -f $home_text) {
6499 print "<div class=\"index_include\">\n";
6500 insert_file($home_text);
6501 print "</div>\n";
6504 git_project_search_form($searchtext, $search_use_regexp);
6505 git_project_list_body(\@list, $order);
6506 git_footer_html();
6509 sub git_forks {
6510 my $order = $input_params{'order'};
6511 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6512 die_error(400, "Unknown order parameter");
6515 my $filter = $project;
6516 $filter =~ s/\.git$//;
6517 my @list = git_get_projects_list($filter);
6518 if (!@list) {
6519 die_error(404, "No forks found");
6522 git_header_html();
6523 git_print_page_nav('','');
6524 git_print_header_div('summary', "$project forks");
6525 git_project_list_body(\@list, $order);
6526 git_footer_html();
6529 sub git_project_index {
6530 my @projects = git_get_projects_list($project_filter, $strict_export);
6531 if (!@projects) {
6532 die_error(404, "No projects found");
6535 print $cgi->header(
6536 -type => 'text/plain',
6537 -charset => 'utf-8',
6538 -content_disposition => 'inline; filename="index.aux"');
6540 foreach my $pr (@projects) {
6541 if (!exists $pr->{'owner'}) {
6542 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6545 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6546 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6547 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6548 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6549 $path =~ s/ /\+/g;
6550 $owner =~ s/ /\+/g;
6552 print "$path $owner\n";
6556 sub git_summary {
6557 my $descr = git_get_project_description($project) || "none";
6558 my %co = parse_commit("HEAD");
6559 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6560 my $head = $co{'id'};
6561 my $remote_heads = gitweb_check_feature('remote_heads');
6563 my $owner = git_get_project_owner($project);
6565 my $refs = git_get_references();
6566 # These get_*_list functions return one more to allow us to see if
6567 # there are more ...
6568 my @taglist = git_get_tags_list(16);
6569 my @headlist = git_get_heads_list(16);
6570 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6571 my @forklist;
6572 my $check_forks = gitweb_check_feature('forks');
6574 if ($check_forks) {
6575 # find forks of a project
6576 my $filter = $project;
6577 $filter =~ s/\.git$//;
6578 @forklist = git_get_projects_list($filter);
6579 # filter out forks of forks
6580 @forklist = filter_forks_from_projects_list(\@forklist)
6581 if (@forklist);
6584 git_header_html();
6585 git_print_page_nav('summary','', $head);
6587 print "<div class=\"title\">&nbsp;</div>\n";
6588 print "<table class=\"projects_list\">\n" .
6589 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6590 if ($owner and not $omit_owner) {
6591 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6593 if (defined $cd{'rfc2822'}) {
6594 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6595 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6598 # use per project git URL list in $projectroot/$project/cloneurl
6599 # or make project git URL from git base URL and project name
6600 my $url_tag = "URL";
6601 my @url_list = git_get_project_url_list($project);
6602 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6603 foreach my $git_url (@url_list) {
6604 next unless $git_url;
6605 print format_repo_url($url_tag, $git_url);
6606 $url_tag = "";
6609 # Tag cloud
6610 my $show_ctags = gitweb_check_feature('ctags');
6611 if ($show_ctags) {
6612 my $ctags = git_get_project_ctags($project);
6613 if (%$ctags) {
6614 # without ability to add tags, don't show if there are none
6615 my $cloud = git_populate_project_tagcloud($ctags);
6616 print "<tr id=\"metadata_ctags\">" .
6617 "<td>content tags</td>" .
6618 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6619 "</tr>\n";
6623 print "</table>\n";
6625 # If XSS prevention is on, we don't include README.html.
6626 # TODO: Allow a readme in some safe format.
6627 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6628 print "<div class=\"title\">readme</div>\n" .
6629 "<div class=\"readme\">\n";
6630 insert_file("$projectroot/$project/README.html");
6631 print "\n</div>\n"; # class="readme"
6634 # we need to request one more than 16 (0..15) to check if
6635 # those 16 are all
6636 my @commitlist = $head ? parse_commits($head, 17) : ();
6637 if (@commitlist) {
6638 git_print_header_div('shortlog');
6639 git_shortlog_body(\@commitlist, 0, 15, $refs,
6640 $#commitlist <= 15 ? undef :
6641 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6644 if (@taglist) {
6645 git_print_header_div('tags');
6646 git_tags_body(\@taglist, 0, 15,
6647 $#taglist <= 15 ? undef :
6648 $cgi->a({-href => href(action=>"tags")}, "..."));
6651 if (@headlist) {
6652 git_print_header_div('heads');
6653 git_heads_body(\@headlist, $head, 0, 15,
6654 $#headlist <= 15 ? undef :
6655 $cgi->a({-href => href(action=>"heads")}, "..."));
6658 if (%remotedata) {
6659 git_print_header_div('remotes');
6660 git_remotes_body(\%remotedata, 15, $head);
6663 if (@forklist) {
6664 git_print_header_div('forks');
6665 git_project_list_body(\@forklist, 'age', 0, 15,
6666 $#forklist <= 15 ? undef :
6667 $cgi->a({-href => href(action=>"forks")}, "..."),
6668 'no_header');
6671 git_footer_html();
6674 sub git_tag {
6675 my %tag = parse_tag($hash);
6677 if (! %tag) {
6678 die_error(404, "Unknown tag object");
6681 my $head = git_get_head_hash($project);
6682 git_header_html();
6683 git_print_page_nav('','', $head,undef,$head);
6684 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6685 print "<div class=\"title_text\">\n" .
6686 "<table class=\"object_header\">\n" .
6687 "<tr>\n" .
6688 "<td>object</td>\n" .
6689 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6690 $tag{'object'}) . "</td>\n" .
6691 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6692 $tag{'type'}) . "</td>\n" .
6693 "</tr>\n";
6694 if (defined($tag{'author'})) {
6695 git_print_authorship_rows(\%tag, 'author');
6697 print "</table>\n\n" .
6698 "</div>\n";
6699 print "<div class=\"page_body\">";
6700 my $comment = $tag{'comment'};
6701 foreach my $line (@$comment) {
6702 chomp $line;
6703 print esc_html($line, -nbsp=>1) . "<br/>\n";
6705 print "</div>\n";
6706 git_footer_html();
6709 sub git_blame_common {
6710 my $format = shift || 'porcelain';
6711 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6712 $format = 'incremental';
6713 $action = 'blame_incremental'; # for page title etc
6716 # permissions
6717 gitweb_check_feature('blame')
6718 or die_error(403, "Blame view not allowed");
6720 # error checking
6721 die_error(400, "No file name given") unless $file_name;
6722 $hash_base ||= git_get_head_hash($project);
6723 die_error(404, "Couldn't find base commit") unless $hash_base;
6724 my %co = parse_commit($hash_base)
6725 or die_error(404, "Commit not found");
6726 my $ftype = "blob";
6727 if (!defined $hash) {
6728 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6729 or die_error(404, "Error looking up file");
6730 } else {
6731 $ftype = git_get_type($hash);
6732 if ($ftype !~ "blob") {
6733 die_error(400, "Object is not a blob");
6737 my $fd;
6738 if ($format eq 'incremental') {
6739 # get file contents (as base)
6740 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6741 or die_error(500, "Open git-cat-file failed");
6742 } elsif ($format eq 'data') {
6743 # run git-blame --incremental
6744 open $fd, "-|", git_cmd(), "blame", "--incremental",
6745 $hash_base, "--", $file_name
6746 or die_error(500, "Open git-blame --incremental failed");
6747 } else {
6748 # run git-blame --porcelain
6749 open $fd, "-|", git_cmd(), "blame", '-p',
6750 $hash_base, '--', $file_name
6751 or die_error(500, "Open git-blame --porcelain failed");
6753 binmode $fd, ':utf8';
6755 # incremental blame data returns early
6756 if ($format eq 'data') {
6757 print $cgi->header(
6758 -type=>"text/plain", -charset => "utf-8",
6759 -status=> "200 OK");
6760 local $| = 1; # output autoflush
6761 while (my $line = <$fd>) {
6762 print to_utf8($line);
6764 close $fd
6765 or print "ERROR $!\n";
6767 print 'END';
6768 if (defined $t0 && gitweb_check_feature('timed')) {
6769 print ' '.
6770 tv_interval($t0, [ gettimeofday() ]).
6771 ' '.$number_of_git_cmds;
6773 print "\n";
6775 return;
6778 # page header
6779 git_header_html();
6780 my $formats_nav =
6781 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6782 "blob") .
6783 " | ";
6784 if ($format eq 'incremental') {
6785 $formats_nav .=
6786 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6787 "blame") . " (non-incremental)";
6788 } else {
6789 $formats_nav .=
6790 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6791 "blame") . " (incremental)";
6793 $formats_nav .=
6794 " | " .
6795 $cgi->a({-href => href(action=>"history", -replay=>1)},
6796 "history") .
6797 " | " .
6798 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6799 "HEAD");
6800 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6801 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6802 git_print_page_path($file_name, $ftype, $hash_base);
6804 # page body
6805 if ($format eq 'incremental') {
6806 print "<noscript>\n<div class=\"error\"><center><b>\n".
6807 "This page requires JavaScript to run.\n Use ".
6808 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6809 'this page').
6810 " instead.\n".
6811 "</b></center></div>\n</noscript>\n";
6813 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6816 print qq!<div class="page_body">\n!;
6817 print qq!<div id="progress_info">... / ...</div>\n!
6818 if ($format eq 'incremental');
6819 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6820 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6821 qq!<thead>\n!.
6822 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6823 qq!</thead>\n!.
6824 qq!<tbody>\n!;
6826 my @rev_color = qw(light dark);
6827 my $num_colors = scalar(@rev_color);
6828 my $current_color = 0;
6830 if ($format eq 'incremental') {
6831 my $color_class = $rev_color[$current_color];
6833 #contents of a file
6834 my $linenr = 0;
6835 LINE:
6836 while (my $line = <$fd>) {
6837 chomp $line;
6838 $linenr++;
6840 print qq!<tr id="l$linenr" class="$color_class">!.
6841 qq!<td class="sha1"><a href=""> </a></td>!.
6842 qq!<td class="linenr">!.
6843 qq!<a class="linenr" href="">$linenr</a></td>!;
6844 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6845 print qq!</tr>\n!;
6848 } else { # porcelain, i.e. ordinary blame
6849 my %metainfo = (); # saves information about commits
6851 # blame data
6852 LINE:
6853 while (my $line = <$fd>) {
6854 chomp $line;
6855 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6856 # no <lines in group> for subsequent lines in group of lines
6857 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6858 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6859 if (!exists $metainfo{$full_rev}) {
6860 $metainfo{$full_rev} = { 'nprevious' => 0 };
6862 my $meta = $metainfo{$full_rev};
6863 my $data;
6864 while ($data = <$fd>) {
6865 chomp $data;
6866 last if ($data =~ s/^\t//); # contents of line
6867 if ($data =~ /^(\S+)(?: (.*))?$/) {
6868 $meta->{$1} = $2 unless exists $meta->{$1};
6870 if ($data =~ /^previous /) {
6871 $meta->{'nprevious'}++;
6874 my $short_rev = substr($full_rev, 0, 8);
6875 my $author = $meta->{'author'};
6876 my %date =
6877 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6878 my $date = $date{'iso-tz'};
6879 if ($group_size) {
6880 $current_color = ($current_color + 1) % $num_colors;
6882 my $tr_class = $rev_color[$current_color];
6883 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6884 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6885 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6886 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6887 if ($group_size) {
6888 print "<td class=\"sha1\"";
6889 print " title=\"". esc_html($author) . ", $date\"";
6890 print " rowspan=\"$group_size\"" if ($group_size > 1);
6891 print ">";
6892 print $cgi->a({-href => href(action=>"commit",
6893 hash=>$full_rev,
6894 file_name=>$file_name)},
6895 esc_html($short_rev));
6896 if ($group_size >= 2) {
6897 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6898 if (@author_initials) {
6899 print "<br />" .
6900 esc_html(join('', @author_initials));
6901 # or join('.', ...)
6904 print "</td>\n";
6906 # 'previous' <sha1 of parent commit> <filename at commit>
6907 if (exists $meta->{'previous'} &&
6908 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6909 $meta->{'parent'} = $1;
6910 $meta->{'file_parent'} = unquote($2);
6912 my $linenr_commit =
6913 exists($meta->{'parent'}) ?
6914 $meta->{'parent'} : $full_rev;
6915 my $linenr_filename =
6916 exists($meta->{'file_parent'}) ?
6917 $meta->{'file_parent'} : unquote($meta->{'filename'});
6918 my $blamed = href(action => 'blame',
6919 file_name => $linenr_filename,
6920 hash_base => $linenr_commit);
6921 print "<td class=\"linenr\">";
6922 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6923 -class => "linenr" },
6924 esc_html($lineno));
6925 print "</td>";
6926 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6927 print "</tr>\n";
6928 } # end while
6932 # footer
6933 print "</tbody>\n".
6934 "</table>\n"; # class="blame"
6935 print "</div>\n"; # class="blame_body"
6936 close $fd
6937 or print "Reading blob failed\n";
6939 git_footer_html();
6942 sub git_blame {
6943 git_blame_common();
6946 sub git_blame_incremental {
6947 git_blame_common('incremental');
6950 sub git_blame_data {
6951 git_blame_common('data');
6954 sub git_tags {
6955 my $head = git_get_head_hash($project);
6956 git_header_html();
6957 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6958 git_print_header_div('summary', $project);
6960 my @tagslist = git_get_tags_list();
6961 if (@tagslist) {
6962 git_tags_body(\@tagslist);
6964 git_footer_html();
6967 sub git_heads {
6968 my $head = git_get_head_hash($project);
6969 git_header_html();
6970 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6971 git_print_header_div('summary', $project);
6973 my @headslist = git_get_heads_list();
6974 if (@headslist) {
6975 git_heads_body(\@headslist, $head);
6977 git_footer_html();
6980 # used both for single remote view and for list of all the remotes
6981 sub git_remotes {
6982 gitweb_check_feature('remote_heads')
6983 or die_error(403, "Remote heads view is disabled");
6985 my $head = git_get_head_hash($project);
6986 my $remote = $input_params{'hash'};
6988 my $remotedata = git_get_remotes_list($remote);
6989 die_error(500, "Unable to get remote information") unless defined $remotedata;
6991 unless (%$remotedata) {
6992 die_error(404, defined $remote ?
6993 "Remote $remote not found" :
6994 "No remotes found");
6997 git_header_html(undef, undef, -action_extra => $remote);
6998 git_print_page_nav('', '', $head, undef, $head,
6999 format_ref_views($remote ? '' : 'remotes'));
7001 fill_remote_heads($remotedata);
7002 if (defined $remote) {
7003 git_print_header_div('remotes', "$remote remote for $project");
7004 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7005 } else {
7006 git_print_header_div('summary', "$project remotes");
7007 git_remotes_body($remotedata, undef, $head);
7010 git_footer_html();
7013 sub git_blob_plain {
7014 my $type = shift;
7015 my $expires;
7017 if (!defined $hash) {
7018 if (defined $file_name) {
7019 my $base = $hash_base || git_get_head_hash($project);
7020 $hash = git_get_hash_by_path($base, $file_name, "blob")
7021 or die_error(404, "Cannot find file");
7022 } else {
7023 die_error(400, "No file name defined");
7025 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7026 # blobs defined by non-textual hash id's can be cached
7027 $expires = "+1d";
7030 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7031 or die_error(500, "Open git-cat-file blob '$hash' failed");
7033 # content-type (can include charset)
7034 $type = blob_contenttype($fd, $file_name, $type);
7036 # "save as" filename, even when no $file_name is given
7037 my $save_as = "$hash";
7038 if (defined $file_name) {
7039 $save_as = $file_name;
7040 } elsif ($type =~ m/^text\//) {
7041 $save_as .= '.txt';
7044 # With XSS prevention on, blobs of all types except a few known safe
7045 # ones are served with "Content-Disposition: attachment" to make sure
7046 # they don't run in our security domain. For certain image types,
7047 # blob view writes an <img> tag referring to blob_plain view, and we
7048 # want to be sure not to break that by serving the image as an
7049 # attachment (though Firefox 3 doesn't seem to care).
7050 my $sandbox = $prevent_xss &&
7051 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7053 # serve text/* as text/plain
7054 if ($prevent_xss &&
7055 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7056 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7057 my $rest = $1;
7058 $rest = defined $rest ? $rest : '';
7059 $type = "text/plain$rest";
7062 print $cgi->header(
7063 -type => $type,
7064 -expires => $expires,
7065 -content_disposition =>
7066 ($sandbox ? 'attachment' : 'inline')
7067 . '; filename="' . $save_as . '"');
7068 local $/ = undef;
7069 binmode STDOUT, ':raw';
7070 print <$fd>;
7071 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7072 close $fd;
7075 sub git_blob {
7076 my $expires;
7078 if (!defined $hash) {
7079 if (defined $file_name) {
7080 my $base = $hash_base || git_get_head_hash($project);
7081 $hash = git_get_hash_by_path($base, $file_name, "blob")
7082 or die_error(404, "Cannot find file");
7083 } else {
7084 die_error(400, "No file name defined");
7086 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7087 # blobs defined by non-textual hash id's can be cached
7088 $expires = "+1d";
7091 my $have_blame = gitweb_check_feature('blame');
7092 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7093 or die_error(500, "Couldn't cat $file_name, $hash");
7094 my $mimetype = blob_mimetype($fd, $file_name);
7095 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7096 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7097 close $fd;
7098 return git_blob_plain($mimetype);
7100 # we can have blame only for text/* mimetype
7101 $have_blame &&= ($mimetype =~ m!^text/!);
7103 my $highlight = gitweb_check_feature('highlight');
7104 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7105 $fd = run_highlighter($fd, $highlight, $syntax)
7106 if $syntax;
7108 git_header_html(undef, $expires);
7109 my $formats_nav = '';
7110 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7111 if (defined $file_name) {
7112 if ($have_blame) {
7113 $formats_nav .=
7114 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7115 "blame") .
7116 " | ";
7118 $formats_nav .=
7119 $cgi->a({-href => href(action=>"history", -replay=>1)},
7120 "history") .
7121 " | " .
7122 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7123 "raw") .
7124 " | " .
7125 $cgi->a({-href => href(action=>"blob",
7126 hash_base=>"HEAD", file_name=>$file_name)},
7127 "HEAD");
7128 } else {
7129 $formats_nav .=
7130 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7131 "raw");
7133 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7134 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7135 } else {
7136 print "<div class=\"page_nav\">\n" .
7137 "<br/><br/></div>\n" .
7138 "<div class=\"title\">".esc_html($hash)."</div>\n";
7140 git_print_page_path($file_name, "blob", $hash_base);
7141 print "<div class=\"page_body\">\n";
7142 if ($mimetype =~ m!^image/!) {
7143 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7144 if ($file_name) {
7145 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7147 print qq! src="! .
7148 href(action=>"blob_plain", hash=>$hash,
7149 hash_base=>$hash_base, file_name=>$file_name) .
7150 qq!" />\n!;
7151 } else {
7152 my $nr;
7153 while (my $line = <$fd>) {
7154 chomp $line;
7155 $nr++;
7156 $line = untabify($line);
7157 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7158 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7159 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7162 close $fd
7163 or print "Reading blob failed.\n";
7164 print "</div>";
7165 git_footer_html();
7168 sub git_tree {
7169 if (!defined $hash_base) {
7170 $hash_base = "HEAD";
7172 if (!defined $hash) {
7173 if (defined $file_name) {
7174 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7175 } else {
7176 $hash = $hash_base;
7179 die_error(404, "No such tree") unless defined($hash);
7181 my $show_sizes = gitweb_check_feature('show-sizes');
7182 my $have_blame = gitweb_check_feature('blame');
7184 my @entries = ();
7186 local $/ = "\0";
7187 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7188 ($show_sizes ? '-l' : ()), @extra_options, $hash
7189 or die_error(500, "Open git-ls-tree failed");
7190 @entries = map { chomp; $_ } <$fd>;
7191 close $fd
7192 or die_error(404, "Reading tree failed");
7195 my $refs = git_get_references();
7196 my $ref = format_ref_marker($refs, $hash_base);
7197 git_header_html();
7198 my $basedir = '';
7199 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7200 my @views_nav = ();
7201 if (defined $file_name) {
7202 push @views_nav,
7203 $cgi->a({-href => href(action=>"history", -replay=>1)},
7204 "history"),
7205 $cgi->a({-href => href(action=>"tree",
7206 hash_base=>"HEAD", file_name=>$file_name)},
7207 "HEAD"),
7209 my $snapshot_links = format_snapshot_links($hash);
7210 if (defined $snapshot_links) {
7211 # FIXME: Should be available when we have no hash base as well.
7212 push @views_nav, $snapshot_links;
7214 git_print_page_nav('tree','', $hash_base, undef, undef,
7215 join(' | ', @views_nav));
7216 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7217 } else {
7218 undef $hash_base;
7219 print "<div class=\"page_nav\">\n";
7220 print "<br/><br/></div>\n";
7221 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7223 if (defined $file_name) {
7224 $basedir = $file_name;
7225 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7226 $basedir .= '/';
7228 git_print_page_path($file_name, 'tree', $hash_base);
7230 print "<div class=\"page_body\">\n";
7231 print "<table class=\"tree\">\n";
7232 my $alternate = 1;
7233 # '..' (top directory) link if possible
7234 if (defined $hash_base &&
7235 defined $file_name && $file_name =~ m![^/]+$!) {
7236 if ($alternate) {
7237 print "<tr class=\"dark\">\n";
7238 } else {
7239 print "<tr class=\"light\">\n";
7241 $alternate ^= 1;
7243 my $up = $file_name;
7244 $up =~ s!/?[^/]+$!!;
7245 undef $up unless $up;
7246 # based on git_print_tree_entry
7247 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7248 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7249 print '<td class="list">';
7250 print $cgi->a({-href => href(action=>"tree",
7251 hash_base=>$hash_base,
7252 file_name=>$up)},
7253 "..");
7254 print "</td>\n";
7255 print "<td class=\"link\"></td>\n";
7257 print "</tr>\n";
7259 foreach my $line (@entries) {
7260 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7262 if ($alternate) {
7263 print "<tr class=\"dark\">\n";
7264 } else {
7265 print "<tr class=\"light\">\n";
7267 $alternate ^= 1;
7269 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7271 print "</tr>\n";
7273 print "</table>\n" .
7274 "</div>";
7275 git_footer_html();
7278 sub sanitize_for_filename {
7279 my $name = shift;
7281 $name =~ s!/!-!g;
7282 $name =~ s/[^[:alnum:]_.-]//g;
7284 return $name;
7287 sub snapshot_name {
7288 my ($project, $hash) = @_;
7290 # path/to/project.git -> project
7291 # path/to/project/.git -> project
7292 my $name = to_utf8($project);
7293 $name =~ s,([^/])/*\.git$,$1,;
7294 $name = sanitize_for_filename(basename($name));
7296 my $ver = $hash;
7297 if ($hash =~ /^[0-9a-fA-F]+$/) {
7298 # shorten SHA-1 hash
7299 my $full_hash = git_get_full_hash($project, $hash);
7300 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7301 $ver = git_get_short_hash($project, $hash);
7303 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7304 # tags don't need shortened SHA-1 hash
7305 $ver = $1;
7306 } else {
7307 # branches and other need shortened SHA-1 hash
7308 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7309 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7310 my $ref_dir = (defined $1) ? $1 : '';
7311 $ver = $2;
7313 $ref_dir = sanitize_for_filename($ref_dir);
7314 # for refs neither in heads nor remotes we want to
7315 # add a ref dir to archive name
7316 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7317 $ver = $ref_dir . '-' . $ver;
7320 $ver .= '-' . git_get_short_hash($project, $hash);
7322 # special case of sanitization for filename - we change
7323 # slashes to dots instead of dashes
7324 # in case of hierarchical branch names
7325 $ver =~ s!/!.!g;
7326 $ver =~ s/[^[:alnum:]_.-]//g;
7328 # name = project-version_string
7329 $name = "$name-$ver";
7331 return wantarray ? ($name, $name) : $name;
7334 sub exit_if_unmodified_since {
7335 my ($latest_epoch) = @_;
7336 our $cgi;
7338 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7339 if (defined $if_modified) {
7340 my $since;
7341 if (eval { require HTTP::Date; 1; }) {
7342 $since = HTTP::Date::str2time($if_modified);
7343 } elsif (eval { require Time::ParseDate; 1; }) {
7344 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7346 if (defined $since && $latest_epoch <= $since) {
7347 my %latest_date = parse_date($latest_epoch);
7348 print $cgi->header(
7349 -last_modified => $latest_date{'rfc2822'},
7350 -status => '304 Not Modified');
7351 goto DONE_GITWEB;
7356 sub git_snapshot {
7357 my $format = $input_params{'snapshot_format'};
7358 if (!@snapshot_fmts) {
7359 die_error(403, "Snapshots not allowed");
7361 # default to first supported snapshot format
7362 $format ||= $snapshot_fmts[0];
7363 if ($format !~ m/^[a-z0-9]+$/) {
7364 die_error(400, "Invalid snapshot format parameter");
7365 } elsif (!exists($known_snapshot_formats{$format})) {
7366 die_error(400, "Unknown snapshot format");
7367 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7368 die_error(403, "Snapshot format not allowed");
7369 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7370 die_error(403, "Unsupported snapshot format");
7373 my $type = git_get_type("$hash^{}");
7374 if (!$type) {
7375 die_error(404, 'Object does not exist');
7376 } elsif ($type eq 'blob') {
7377 die_error(400, 'Object is not a tree-ish');
7380 my ($name, $prefix) = snapshot_name($project, $hash);
7381 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7383 my %co = parse_commit($hash);
7384 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7386 my $cmd = quote_command(
7387 git_cmd(), 'archive',
7388 "--format=$known_snapshot_formats{$format}{'format'}",
7389 "--prefix=$prefix/", $hash);
7390 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7391 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7394 $filename =~ s/(["\\])/\\$1/g;
7395 my %latest_date;
7396 if (%co) {
7397 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7400 print $cgi->header(
7401 -type => $known_snapshot_formats{$format}{'type'},
7402 -content_disposition => 'inline; filename="' . $filename . '"',
7403 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7404 -status => '200 OK');
7406 open my $fd, "-|", $cmd
7407 or die_error(500, "Execute git-archive failed");
7408 binmode STDOUT, ':raw';
7409 print <$fd>;
7410 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7411 close $fd;
7414 sub git_log_generic {
7415 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7417 my $head = git_get_head_hash($project);
7418 if (!defined $base) {
7419 $base = $head;
7421 if (!defined $page) {
7422 $page = 0;
7424 my $refs = git_get_references();
7426 my $commit_hash = $base;
7427 if (defined $parent) {
7428 $commit_hash = "$parent..$base";
7430 my @commitlist =
7431 parse_commits($commit_hash, 101, (100 * $page),
7432 defined $file_name ? ($file_name, "--full-history") : ());
7434 my $ftype;
7435 if (!defined $file_hash && defined $file_name) {
7436 # some commits could have deleted file in question,
7437 # and not have it in tree, but one of them has to have it
7438 for (my $i = 0; $i < @commitlist; $i++) {
7439 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7440 last if defined $file_hash;
7443 if (defined $file_hash) {
7444 $ftype = git_get_type($file_hash);
7446 if (defined $file_name && !defined $ftype) {
7447 die_error(500, "Unknown type of object");
7449 my %co;
7450 if (defined $file_name) {
7451 %co = parse_commit($base)
7452 or die_error(404, "Unknown commit object");
7456 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7457 my $next_link = '';
7458 if ($#commitlist >= 100) {
7459 $next_link =
7460 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7461 -accesskey => "n", -title => "Alt-n"}, "next");
7463 my $patch_max = gitweb_get_feature('patches');
7464 if ($patch_max && !defined $file_name) {
7465 if ($patch_max < 0 || @commitlist <= $patch_max) {
7466 $paging_nav .= " &sdot; " .
7467 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7468 "patches");
7472 git_header_html();
7473 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7474 if (defined $file_name) {
7475 git_print_header_div('commit', esc_html($co{'title'}), $base);
7476 } else {
7477 git_print_header_div('summary', $project)
7479 git_print_page_path($file_name, $ftype, $hash_base)
7480 if (defined $file_name);
7482 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7483 $file_name, $file_hash, $ftype);
7485 git_footer_html();
7488 sub git_log {
7489 git_log_generic('log', \&git_log_body,
7490 $hash, $hash_parent);
7493 sub git_commit {
7494 $hash ||= $hash_base || "HEAD";
7495 my %co = parse_commit($hash)
7496 or die_error(404, "Unknown commit object");
7498 my $parent = $co{'parent'};
7499 my $parents = $co{'parents'}; # listref
7501 # we need to prepare $formats_nav before any parameter munging
7502 my $formats_nav;
7503 if (!defined $parent) {
7504 # --root commitdiff
7505 $formats_nav .= '(initial)';
7506 } elsif (@$parents == 1) {
7507 # single parent commit
7508 $formats_nav .=
7509 '(parent: ' .
7510 $cgi->a({-href => href(action=>"commit",
7511 hash=>$parent)},
7512 esc_html(substr($parent, 0, 7))) .
7513 ')';
7514 } else {
7515 # merge commit
7516 $formats_nav .=
7517 '(merge: ' .
7518 join(' ', map {
7519 $cgi->a({-href => href(action=>"commit",
7520 hash=>$_)},
7521 esc_html(substr($_, 0, 7)));
7522 } @$parents ) .
7523 ')';
7525 if (gitweb_check_feature('patches') && @$parents <= 1) {
7526 $formats_nav .= " | " .
7527 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7528 "patch");
7531 if (!defined $parent) {
7532 $parent = "--root";
7534 my @difftree;
7535 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7536 @diff_opts,
7537 (@$parents <= 1 ? $parent : '-c'),
7538 $hash, "--"
7539 or die_error(500, "Open git-diff-tree failed");
7540 @difftree = map { chomp; $_ } <$fd>;
7541 close $fd or die_error(404, "Reading git-diff-tree failed");
7543 # non-textual hash id's can be cached
7544 my $expires;
7545 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7546 $expires = "+1d";
7548 my $refs = git_get_references();
7549 my $ref = format_ref_marker($refs, $co{'id'});
7551 git_header_html(undef, $expires);
7552 git_print_page_nav('commit', '',
7553 $hash, $co{'tree'}, $hash,
7554 $formats_nav);
7556 if (defined $co{'parent'}) {
7557 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7558 } else {
7559 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7561 print "<div class=\"title_text\">\n" .
7562 "<table class=\"object_header\">\n";
7563 git_print_authorship_rows(\%co);
7564 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7565 print "<tr>" .
7566 "<td>tree</td>" .
7567 "<td class=\"sha1\">" .
7568 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7569 class => "list"}, $co{'tree'}) .
7570 "</td>" .
7571 "<td class=\"link\">" .
7572 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7573 "tree");
7574 my $snapshot_links = format_snapshot_links($hash);
7575 if (defined $snapshot_links) {
7576 print " | " . $snapshot_links;
7578 print "</td>" .
7579 "</tr>\n";
7581 foreach my $par (@$parents) {
7582 print "<tr>" .
7583 "<td>parent</td>" .
7584 "<td class=\"sha1\">" .
7585 $cgi->a({-href => href(action=>"commit", hash=>$par),
7586 class => "list"}, $par) .
7587 "</td>" .
7588 "<td class=\"link\">" .
7589 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7590 " | " .
7591 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7592 "</td>" .
7593 "</tr>\n";
7595 print "</table>".
7596 "</div>\n";
7598 print "<div class=\"page_body\">\n";
7599 git_print_log($co{'comment'});
7600 print "</div>\n";
7602 git_difftree_body(\@difftree, $hash, @$parents);
7604 git_footer_html();
7607 sub git_object {
7608 # object is defined by:
7609 # - hash or hash_base alone
7610 # - hash_base and file_name
7611 my $type;
7613 # - hash or hash_base alone
7614 if ($hash || ($hash_base && !defined $file_name)) {
7615 my $object_id = $hash || $hash_base;
7617 open my $fd, "-|", quote_command(
7618 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7619 or die_error(404, "Object does not exist");
7620 $type = <$fd>;
7621 chomp $type;
7622 close $fd
7623 or die_error(404, "Object does not exist");
7625 # - hash_base and file_name
7626 } elsif ($hash_base && defined $file_name) {
7627 $file_name =~ s,/+$,,;
7629 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7630 or die_error(404, "Base object does not exist");
7632 # here errors should not happen
7633 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7634 or die_error(500, "Open git-ls-tree failed");
7635 my $line = <$fd>;
7636 close $fd;
7638 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7639 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7640 die_error(404, "File or directory for given base does not exist");
7642 $type = $2;
7643 $hash = $3;
7644 } else {
7645 die_error(400, "Not enough information to find object");
7648 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7649 hash=>$hash, hash_base=>$hash_base,
7650 file_name=>$file_name),
7651 -status => '302 Found');
7654 sub git_blobdiff {
7655 my $format = shift || 'html';
7656 my $diff_style = $input_params{'diff_style'} || 'inline';
7658 my $fd;
7659 my @difftree;
7660 my %diffinfo;
7661 my $expires;
7663 # preparing $fd and %diffinfo for git_patchset_body
7664 # new style URI
7665 if (defined $hash_base && defined $hash_parent_base) {
7666 if (defined $file_name) {
7667 # read raw output
7668 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7669 $hash_parent_base, $hash_base,
7670 "--", (defined $file_parent ? $file_parent : ()), $file_name
7671 or die_error(500, "Open git-diff-tree failed");
7672 @difftree = map { chomp; $_ } <$fd>;
7673 close $fd
7674 or die_error(404, "Reading git-diff-tree failed");
7675 @difftree
7676 or die_error(404, "Blob diff not found");
7678 } elsif (defined $hash &&
7679 $hash =~ /[0-9a-fA-F]{40}/) {
7680 # try to find filename from $hash
7682 # read filtered raw output
7683 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7684 $hash_parent_base, $hash_base, "--"
7685 or die_error(500, "Open git-diff-tree failed");
7686 @difftree =
7687 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7688 # $hash == to_id
7689 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7690 map { chomp; $_ } <$fd>;
7691 close $fd
7692 or die_error(404, "Reading git-diff-tree failed");
7693 @difftree
7694 or die_error(404, "Blob diff not found");
7696 } else {
7697 die_error(400, "Missing one of the blob diff parameters");
7700 if (@difftree > 1) {
7701 die_error(400, "Ambiguous blob diff specification");
7704 %diffinfo = parse_difftree_raw_line($difftree[0]);
7705 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7706 $file_name ||= $diffinfo{'to_file'};
7708 $hash_parent ||= $diffinfo{'from_id'};
7709 $hash ||= $diffinfo{'to_id'};
7711 # non-textual hash id's can be cached
7712 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7713 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7714 $expires = '+1d';
7717 # open patch output
7718 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7719 '-p', ($format eq 'html' ? "--full-index" : ()),
7720 $hash_parent_base, $hash_base,
7721 "--", (defined $file_parent ? $file_parent : ()), $file_name
7722 or die_error(500, "Open git-diff-tree failed");
7725 # old/legacy style URI -- not generated anymore since 1.4.3.
7726 if (!%diffinfo) {
7727 die_error('404 Not Found', "Missing one of the blob diff parameters")
7730 # header
7731 if ($format eq 'html') {
7732 my $formats_nav =
7733 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7734 "raw");
7735 $formats_nav .= diff_style_nav($diff_style);
7736 git_header_html(undef, $expires);
7737 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7738 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7739 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7740 } else {
7741 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7742 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7744 if (defined $file_name) {
7745 git_print_page_path($file_name, "blob", $hash_base);
7746 } else {
7747 print "<div class=\"page_path\"></div>\n";
7750 } elsif ($format eq 'plain') {
7751 print $cgi->header(
7752 -type => 'text/plain',
7753 -charset => 'utf-8',
7754 -expires => $expires,
7755 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7757 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7759 } else {
7760 die_error(400, "Unknown blobdiff format");
7763 # patch
7764 if ($format eq 'html') {
7765 print "<div class=\"page_body\">\n";
7767 git_patchset_body($fd, $diff_style,
7768 [ \%diffinfo ], $hash_base, $hash_parent_base);
7769 close $fd;
7771 print "</div>\n"; # class="page_body"
7772 git_footer_html();
7774 } else {
7775 while (my $line = <$fd>) {
7776 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7777 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7779 print $line;
7781 last if $line =~ m!^\+\+\+!;
7783 local $/ = undef;
7784 print <$fd>;
7785 close $fd;
7789 sub git_blobdiff_plain {
7790 git_blobdiff('plain');
7793 # assumes that it is added as later part of already existing navigation,
7794 # so it returns "| foo | bar" rather than just "foo | bar"
7795 sub diff_style_nav {
7796 my ($diff_style, $is_combined) = @_;
7797 $diff_style ||= 'inline';
7799 return "" if ($is_combined);
7801 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7802 my %styles = @styles;
7803 @styles =
7804 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7806 return join '',
7807 map { " | ".$_ }
7808 map {
7809 $_ eq $diff_style ? $styles{$_} :
7810 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7811 } @styles;
7814 sub git_commitdiff {
7815 my %params = @_;
7816 my $format = $params{-format} || 'html';
7817 my $diff_style = $input_params{'diff_style'} || 'inline';
7819 my ($patch_max) = gitweb_get_feature('patches');
7820 if ($format eq 'patch') {
7821 die_error(403, "Patch view not allowed") unless $patch_max;
7824 $hash ||= $hash_base || "HEAD";
7825 my %co = parse_commit($hash)
7826 or die_error(404, "Unknown commit object");
7828 # choose format for commitdiff for merge
7829 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7830 $hash_parent = '--cc';
7832 # we need to prepare $formats_nav before almost any parameter munging
7833 my $formats_nav;
7834 if ($format eq 'html') {
7835 $formats_nav =
7836 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7837 "raw");
7838 if ($patch_max && @{$co{'parents'}} <= 1) {
7839 $formats_nav .= " | " .
7840 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7841 "patch");
7843 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7845 if (defined $hash_parent &&
7846 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7847 # commitdiff with two commits given
7848 my $hash_parent_short = $hash_parent;
7849 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7850 $hash_parent_short = substr($hash_parent, 0, 7);
7852 $formats_nav .=
7853 ' (from';
7854 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7855 if ($co{'parents'}[$i] eq $hash_parent) {
7856 $formats_nav .= ' parent ' . ($i+1);
7857 last;
7860 $formats_nav .= ': ' .
7861 $cgi->a({-href => href(-replay=>1,
7862 hash=>$hash_parent, hash_base=>undef)},
7863 esc_html($hash_parent_short)) .
7864 ')';
7865 } elsif (!$co{'parent'}) {
7866 # --root commitdiff
7867 $formats_nav .= ' (initial)';
7868 } elsif (scalar @{$co{'parents'}} == 1) {
7869 # single parent commit
7870 $formats_nav .=
7871 ' (parent: ' .
7872 $cgi->a({-href => href(-replay=>1,
7873 hash=>$co{'parent'}, hash_base=>undef)},
7874 esc_html(substr($co{'parent'}, 0, 7))) .
7875 ')';
7876 } else {
7877 # merge commit
7878 if ($hash_parent eq '--cc') {
7879 $formats_nav .= ' | ' .
7880 $cgi->a({-href => href(-replay=>1,
7881 hash=>$hash, hash_parent=>'-c')},
7882 'combined');
7883 } else { # $hash_parent eq '-c'
7884 $formats_nav .= ' | ' .
7885 $cgi->a({-href => href(-replay=>1,
7886 hash=>$hash, hash_parent=>'--cc')},
7887 'compact');
7889 $formats_nav .=
7890 ' (merge: ' .
7891 join(' ', map {
7892 $cgi->a({-href => href(-replay=>1,
7893 hash=>$_, hash_base=>undef)},
7894 esc_html(substr($_, 0, 7)));
7895 } @{$co{'parents'}} ) .
7896 ')';
7900 my $hash_parent_param = $hash_parent;
7901 if (!defined $hash_parent_param) {
7902 # --cc for multiple parents, --root for parentless
7903 $hash_parent_param =
7904 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7907 # read commitdiff
7908 my $fd;
7909 my @difftree;
7910 if ($format eq 'html') {
7911 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7912 "--no-commit-id", "--patch-with-raw", "--full-index",
7913 $hash_parent_param, $hash, "--"
7914 or die_error(500, "Open git-diff-tree failed");
7916 while (my $line = <$fd>) {
7917 chomp $line;
7918 # empty line ends raw part of diff-tree output
7919 last unless $line;
7920 push @difftree, scalar parse_difftree_raw_line($line);
7923 } elsif ($format eq 'plain') {
7924 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7925 '-p', $hash_parent_param, $hash, "--"
7926 or die_error(500, "Open git-diff-tree failed");
7927 } elsif ($format eq 'patch') {
7928 # For commit ranges, we limit the output to the number of
7929 # patches specified in the 'patches' feature.
7930 # For single commits, we limit the output to a single patch,
7931 # diverging from the git-format-patch default.
7932 my @commit_spec = ();
7933 if ($hash_parent) {
7934 if ($patch_max > 0) {
7935 push @commit_spec, "-$patch_max";
7937 push @commit_spec, '-n', "$hash_parent..$hash";
7938 } else {
7939 if ($params{-single}) {
7940 push @commit_spec, '-1';
7941 } else {
7942 if ($patch_max > 0) {
7943 push @commit_spec, "-$patch_max";
7945 push @commit_spec, "-n";
7947 push @commit_spec, '--root', $hash;
7949 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7950 '--encoding=utf8', '--stdout', @commit_spec
7951 or die_error(500, "Open git-format-patch failed");
7952 } else {
7953 die_error(400, "Unknown commitdiff format");
7956 # non-textual hash id's can be cached
7957 my $expires;
7958 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7959 $expires = "+1d";
7962 # write commit message
7963 if ($format eq 'html') {
7964 my $refs = git_get_references();
7965 my $ref = format_ref_marker($refs, $co{'id'});
7967 git_header_html(undef, $expires);
7968 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7969 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7970 print "<div class=\"title_text\">\n" .
7971 "<table class=\"object_header\">\n";
7972 git_print_authorship_rows(\%co);
7973 print "</table>".
7974 "</div>\n";
7975 print "<div class=\"page_body\">\n";
7976 if (@{$co{'comment'}} > 1) {
7977 print "<div class=\"log\">\n";
7978 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7979 print "</div>\n"; # class="log"
7982 } elsif ($format eq 'plain') {
7983 my $refs = git_get_references("tags");
7984 my $tagname = git_get_rev_name_tags($hash);
7985 my $filename = basename($project) . "-$hash.patch";
7987 print $cgi->header(
7988 -type => 'text/plain',
7989 -charset => 'utf-8',
7990 -expires => $expires,
7991 -content_disposition => 'inline; filename="' . "$filename" . '"');
7992 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7993 print "From: " . to_utf8($co{'author'}) . "\n";
7994 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7995 print "Subject: " . to_utf8($co{'title'}) . "\n";
7997 print "X-Git-Tag: $tagname\n" if $tagname;
7998 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8000 foreach my $line (@{$co{'comment'}}) {
8001 print to_utf8($line) . "\n";
8003 print "---\n\n";
8004 } elsif ($format eq 'patch') {
8005 my $filename = basename($project) . "-$hash.patch";
8007 print $cgi->header(
8008 -type => 'text/plain',
8009 -charset => 'utf-8',
8010 -expires => $expires,
8011 -content_disposition => 'inline; filename="' . "$filename" . '"');
8014 # write patch
8015 if ($format eq 'html') {
8016 my $use_parents = !defined $hash_parent ||
8017 $hash_parent eq '-c' || $hash_parent eq '--cc';
8018 git_difftree_body(\@difftree, $hash,
8019 $use_parents ? @{$co{'parents'}} : $hash_parent);
8020 print "<br/>\n";
8022 git_patchset_body($fd, $diff_style,
8023 \@difftree, $hash,
8024 $use_parents ? @{$co{'parents'}} : $hash_parent);
8025 close $fd;
8026 print "</div>\n"; # class="page_body"
8027 git_footer_html();
8029 } elsif ($format eq 'plain') {
8030 local $/ = undef;
8031 print <$fd>;
8032 close $fd
8033 or print "Reading git-diff-tree failed\n";
8034 } elsif ($format eq 'patch') {
8035 local $/ = undef;
8036 print <$fd>;
8037 close $fd
8038 or print "Reading git-format-patch failed\n";
8042 sub git_commitdiff_plain {
8043 git_commitdiff(-format => 'plain');
8046 # format-patch-style patches
8047 sub git_patch {
8048 git_commitdiff(-format => 'patch', -single => 1);
8051 sub git_patches {
8052 git_commitdiff(-format => 'patch');
8055 sub git_history {
8056 git_log_generic('history', \&git_history_body,
8057 $hash_base, $hash_parent_base,
8058 $file_name, $hash);
8061 sub git_search {
8062 $searchtype ||= 'commit';
8064 # check if appropriate features are enabled
8065 gitweb_check_feature('search')
8066 or die_error(403, "Search is disabled");
8067 if ($searchtype eq 'pickaxe') {
8068 # pickaxe may take all resources of your box and run for several minutes
8069 # with every query - so decide by yourself how public you make this feature
8070 gitweb_check_feature('pickaxe')
8071 or die_error(403, "Pickaxe search is disabled");
8073 if ($searchtype eq 'grep') {
8074 # grep search might be potentially CPU-intensive, too
8075 gitweb_check_feature('grep')
8076 or die_error(403, "Grep search is disabled");
8079 if (!defined $searchtext) {
8080 die_error(400, "Text field is empty");
8082 if (!defined $hash) {
8083 $hash = git_get_head_hash($project);
8085 my %co = parse_commit($hash);
8086 if (!%co) {
8087 die_error(404, "Unknown commit object");
8089 if (!defined $page) {
8090 $page = 0;
8093 if ($searchtype eq 'commit' ||
8094 $searchtype eq 'author' ||
8095 $searchtype eq 'committer') {
8096 git_search_message(%co);
8097 } elsif ($searchtype eq 'pickaxe') {
8098 git_search_changes(%co);
8099 } elsif ($searchtype eq 'grep') {
8100 git_search_files(%co);
8101 } else {
8102 die_error(400, "Unknown search type");
8106 sub git_search_help {
8107 git_header_html();
8108 git_print_page_nav('','', $hash,$hash,$hash);
8109 print <<EOT;
8110 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8111 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8112 the pattern entered is recognized as the POSIX extended
8113 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8114 insensitive).</p>
8115 <dl>
8116 <dt><b>commit</b></dt>
8117 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8119 my $have_grep = gitweb_check_feature('grep');
8120 if ($have_grep) {
8121 print <<EOT;
8122 <dt><b>grep</b></dt>
8123 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8124 a different one) are searched for the given pattern. On large trees, this search can take
8125 a while and put some strain on the server, so please use it with some consideration. Note that
8126 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8127 case-sensitive.</dd>
8130 print <<EOT;
8131 <dt><b>author</b></dt>
8132 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8133 <dt><b>committer</b></dt>
8134 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8136 my $have_pickaxe = gitweb_check_feature('pickaxe');
8137 if ($have_pickaxe) {
8138 print <<EOT;
8139 <dt><b>pickaxe</b></dt>
8140 <dd>All commits that caused the string to appear or disappear from any file (changes that
8141 added, removed or "modified" the string) will be listed. This search can take a while and
8142 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8143 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8146 print "</dl>\n";
8147 git_footer_html();
8150 sub git_shortlog {
8151 git_log_generic('shortlog', \&git_shortlog_body,
8152 $hash, $hash_parent);
8155 ## ......................................................................
8156 ## feeds (RSS, Atom; OPML)
8158 sub git_feed {
8159 my $format = shift || 'atom';
8160 my $have_blame = gitweb_check_feature('blame');
8162 # Atom: http://www.atomenabled.org/developers/syndication/
8163 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8164 if ($format ne 'rss' && $format ne 'atom') {
8165 die_error(400, "Unknown web feed format");
8168 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8169 my $head = $hash || 'HEAD';
8170 my @commitlist = parse_commits($head, 150, 0, $file_name);
8172 my %latest_commit;
8173 my %latest_date;
8174 my $content_type = "application/$format+xml";
8175 if (defined $cgi->http('HTTP_ACCEPT') &&
8176 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8177 # browser (feed reader) prefers text/xml
8178 $content_type = 'text/xml';
8180 if (defined($commitlist[0])) {
8181 %latest_commit = %{$commitlist[0]};
8182 my $latest_epoch = $latest_commit{'committer_epoch'};
8183 exit_if_unmodified_since($latest_epoch);
8184 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8186 print $cgi->header(
8187 -type => $content_type,
8188 -charset => 'utf-8',
8189 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8190 -status => '200 OK');
8192 # Optimization: skip generating the body if client asks only
8193 # for Last-Modified date.
8194 return if ($cgi->request_method() eq 'HEAD');
8196 # header variables
8197 my $title = "$site_name - $project/$action";
8198 my $feed_type = 'log';
8199 if (defined $hash) {
8200 $title .= " - '$hash'";
8201 $feed_type = 'branch log';
8202 if (defined $file_name) {
8203 $title .= " :: $file_name";
8204 $feed_type = 'history';
8206 } elsif (defined $file_name) {
8207 $title .= " - $file_name";
8208 $feed_type = 'history';
8210 $title .= " $feed_type";
8211 $title = esc_html($title);
8212 my $descr = git_get_project_description($project);
8213 if (defined $descr) {
8214 $descr = esc_html($descr);
8215 } else {
8216 $descr = "$project " .
8217 ($format eq 'rss' ? 'RSS' : 'Atom') .
8218 " feed";
8220 my $owner = git_get_project_owner($project);
8221 $owner = esc_html($owner);
8223 #header
8224 my $alt_url;
8225 if (defined $file_name) {
8226 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8227 } elsif (defined $hash) {
8228 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8229 } else {
8230 $alt_url = href(-full=>1, action=>"summary");
8232 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8233 if ($format eq 'rss') {
8234 print <<XML;
8235 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8236 <channel>
8238 print "<title>$title</title>\n" .
8239 "<link>$alt_url</link>\n" .
8240 "<description>$descr</description>\n" .
8241 "<language>en</language>\n" .
8242 # project owner is responsible for 'editorial' content
8243 "<managingEditor>$owner</managingEditor>\n";
8244 if (defined $logo || defined $favicon) {
8245 # prefer the logo to the favicon, since RSS
8246 # doesn't allow both
8247 my $img = esc_url($logo || $favicon);
8248 print "<image>\n" .
8249 "<url>$img</url>\n" .
8250 "<title>$title</title>\n" .
8251 "<link>$alt_url</link>\n" .
8252 "</image>\n";
8254 if (%latest_date) {
8255 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8256 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8258 print "<generator>gitweb v.$version/$git_version</generator>\n";
8259 } elsif ($format eq 'atom') {
8260 print <<XML;
8261 <feed xmlns="http://www.w3.org/2005/Atom">
8263 print "<title>$title</title>\n" .
8264 "<subtitle>$descr</subtitle>\n" .
8265 '<link rel="alternate" type="text/html" href="' .
8266 $alt_url . '" />' . "\n" .
8267 '<link rel="self" type="' . $content_type . '" href="' .
8268 $cgi->self_url() . '" />' . "\n" .
8269 "<id>" . href(-full=>1) . "</id>\n" .
8270 # use project owner for feed author
8271 "<author><name>$owner</name></author>\n";
8272 if (defined $favicon) {
8273 print "<icon>" . esc_url($favicon) . "</icon>\n";
8275 if (defined $logo) {
8276 # not twice as wide as tall: 72 x 27 pixels
8277 print "<logo>" . esc_url($logo) . "</logo>\n";
8279 if (! %latest_date) {
8280 # dummy date to keep the feed valid until commits trickle in:
8281 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8282 } else {
8283 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8285 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8288 # contents
8289 for (my $i = 0; $i <= $#commitlist; $i++) {
8290 my %co = %{$commitlist[$i]};
8291 my $commit = $co{'id'};
8292 # we read 150, we always show 30 and the ones more recent than 48 hours
8293 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8294 last;
8296 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8298 # get list of changed files
8299 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8300 $co{'parent'} || "--root",
8301 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8302 or next;
8303 my @difftree = map { chomp; $_ } <$fd>;
8304 close $fd
8305 or next;
8307 # print element (entry, item)
8308 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8309 if ($format eq 'rss') {
8310 print "<item>\n" .
8311 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8312 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8313 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8314 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8315 "<link>$co_url</link>\n" .
8316 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8317 "<content:encoded>" .
8318 "<![CDATA[\n";
8319 } elsif ($format eq 'atom') {
8320 print "<entry>\n" .
8321 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8322 "<updated>$cd{'iso-8601'}</updated>\n" .
8323 "<author>\n" .
8324 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8325 if ($co{'author_email'}) {
8326 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8328 print "</author>\n" .
8329 # use committer for contributor
8330 "<contributor>\n" .
8331 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8332 if ($co{'committer_email'}) {
8333 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8335 print "</contributor>\n" .
8336 "<published>$cd{'iso-8601'}</published>\n" .
8337 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8338 "<id>$co_url</id>\n" .
8339 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8340 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8342 my $comment = $co{'comment'};
8343 print "<pre>\n";
8344 foreach my $line (@$comment) {
8345 $line = esc_html($line);
8346 print "$line\n";
8348 print "</pre><ul>\n";
8349 foreach my $difftree_line (@difftree) {
8350 my %difftree = parse_difftree_raw_line($difftree_line);
8351 next if !$difftree{'from_id'};
8353 my $file = $difftree{'file'} || $difftree{'to_file'};
8355 print "<li>" .
8356 "[" .
8357 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8358 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8359 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8360 file_name=>$file, file_parent=>$difftree{'from_file'}),
8361 -title => "diff"}, 'D');
8362 if ($have_blame) {
8363 print $cgi->a({-href => href(-full=>1, action=>"blame",
8364 file_name=>$file, hash_base=>$commit),
8365 -title => "blame"}, 'B');
8367 # if this is not a feed of a file history
8368 if (!defined $file_name || $file_name ne $file) {
8369 print $cgi->a({-href => href(-full=>1, action=>"history",
8370 file_name=>$file, hash=>$commit),
8371 -title => "history"}, 'H');
8373 $file = esc_path($file);
8374 print "] ".
8375 "$file</li>\n";
8377 if ($format eq 'rss') {
8378 print "</ul>]]>\n" .
8379 "</content:encoded>\n" .
8380 "</item>\n";
8381 } elsif ($format eq 'atom') {
8382 print "</ul>\n</div>\n" .
8383 "</content>\n" .
8384 "</entry>\n";
8388 # end of feed
8389 if ($format eq 'rss') {
8390 print "</channel>\n</rss>\n";
8391 } elsif ($format eq 'atom') {
8392 print "</feed>\n";
8396 sub git_rss {
8397 git_feed('rss');
8400 sub git_atom {
8401 git_feed('atom');
8404 sub git_opml {
8405 my @list = git_get_projects_list($project_filter, $strict_export);
8406 if (!@list) {
8407 die_error(404, "No projects found");
8410 print $cgi->header(
8411 -type => 'text/xml',
8412 -charset => 'utf-8',
8413 -content_disposition => 'inline; filename="opml.xml"');
8415 my $title = esc_html($site_name);
8416 my $filter = " within subdirectory ";
8417 if (defined $project_filter) {
8418 $filter .= esc_html($project_filter);
8419 } else {
8420 $filter = "";
8422 print <<XML;
8423 <?xml version="1.0" encoding="utf-8"?>
8424 <opml version="1.0">
8425 <head>
8426 <title>$title OPML Export$filter</title>
8427 </head>
8428 <body>
8429 <outline text="git RSS feeds">
8432 foreach my $pr (@list) {
8433 my %proj = %$pr;
8434 my $head = git_get_head_hash($proj{'path'});
8435 if (!defined $head) {
8436 next;
8438 $git_dir = "$projectroot/$proj{'path'}";
8439 my %co = parse_commit($head);
8440 if (!%co) {
8441 next;
8444 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8445 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8446 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8447 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8449 print <<XML;
8450 </outline>
8451 </body>
8452 </opml>