Merge commit 'refs/top-bases/t/email/obfuscate' into t/email/obfuscate
[git/gitweb.git] / gitweb / gitweb.perl
blob0ed03266cf94f7c95abf33e21cb11e88d046f20a
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 and getpeername fails
714 # with ENOTCONN, then FCGI mode will be activated automatically in just the
715 # same way as though the --fcgi option had been given instead.
716 our $auto_fcgi = 0;
718 # read and parse gitweb config file given by its parameter.
719 # returns true on success, false on recoverable error, allowing
720 # to chain this subroutine, using first file that exists.
721 # dies on errors during parsing config file, as it is unrecoverable.
722 sub read_config_file {
723 my $filename = shift;
724 return unless defined $filename;
725 # die if there are errors parsing config file
726 if (-e $filename) {
727 do $filename;
728 die $@ if $@;
729 return 1;
731 return;
734 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
735 sub evaluate_gitweb_config {
736 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
737 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
738 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
740 # Protect against duplications of file names, to not read config twice.
741 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
742 # there possibility of duplication of filename there doesn't matter.
743 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
744 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
746 # Common system-wide settings for convenience.
747 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
748 read_config_file($GITWEB_CONFIG_COMMON);
750 # Use first config file that exists. This means use the per-instance
751 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
752 read_config_file($GITWEB_CONFIG) and return;
753 read_config_file($GITWEB_CONFIG_SYSTEM);
756 our $encode_object;
758 sub evaluate_encoding {
759 my $requested = $fallback_encoding || 'ISO-8859-1';
760 my $obj = Encode::find_encoding($requested) or
761 die_error(400, "Requested fallback encoding not found");
762 if ($obj->name eq 'iso-8859-1') {
763 # Use Windows-1252 instead as required by the HTML 5 standard
764 my $altobj = Encode::find_encoding('Windows-1252');
765 $obj = $altobj if $altobj;
767 $encode_object = $obj;
770 sub evaluate_email_obfuscate {
771 # email obfuscation
772 our $email;
773 if (!$email && eval { require HTML::Email::Obfuscate; 1 }) {
774 $email = HTML::Email::Obfuscate->new(lite => 1);
778 # Get loadavg of system, to compare against $maxload.
779 # Currently it requires '/proc/loadavg' present to get loadavg;
780 # if it is not present it returns 0, which means no load checking.
781 sub get_loadavg {
782 if( -e '/proc/loadavg' ){
783 open my $fd, '<', '/proc/loadavg'
784 or return 0;
785 my @load = split(/\s+/, scalar <$fd>);
786 close $fd;
788 # The first three columns measure CPU and IO utilization of the last one,
789 # five, and 10 minute periods. The fourth column shows the number of
790 # currently running processes and the total number of processes in the m/n
791 # format. The last column displays the last process ID used.
792 return $load[0] || 0;
794 # additional checks for load average should go here for things that don't export
795 # /proc/loadavg
797 return 0;
800 # version of the core git binary
801 our $git_version;
802 sub evaluate_git_version {
803 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
804 $number_of_git_cmds++;
807 sub check_loadavg {
808 if (defined $maxload && get_loadavg() > $maxload) {
809 die_error(503, "The load average on the server is too high");
813 # ======================================================================
814 # input validation and dispatch
816 # input parameters can be collected from a variety of sources (presently, CGI
817 # and PATH_INFO), so we define an %input_params hash that collects them all
818 # together during validation: this allows subsequent uses (e.g. href()) to be
819 # agnostic of the parameter origin
821 our %input_params = ();
823 # input parameters are stored with the long parameter name as key. This will
824 # also be used in the href subroutine to convert parameters to their CGI
825 # equivalent, and since the href() usage is the most frequent one, we store
826 # the name -> CGI key mapping here, instead of the reverse.
828 # XXX: Warning: If you touch this, check the search form for updating,
829 # too.
831 our @cgi_param_mapping = (
832 project => "p",
833 action => "a",
834 file_name => "f",
835 file_parent => "fp",
836 hash => "h",
837 hash_parent => "hp",
838 hash_base => "hb",
839 hash_parent_base => "hpb",
840 page => "pg",
841 order => "o",
842 searchtext => "s",
843 searchtype => "st",
844 snapshot_format => "sf",
845 extra_options => "opt",
846 search_use_regexp => "sr",
847 ctag => "by_tag",
848 diff_style => "ds",
849 project_filter => "pf",
850 # this must be last entry (for manipulation from JavaScript)
851 javascript => "js"
853 our %cgi_param_mapping = @cgi_param_mapping;
855 # we will also need to know the possible actions, for validation
856 our %actions = (
857 "blame" => \&git_blame,
858 "blame_incremental" => \&git_blame_incremental,
859 "blame_data" => \&git_blame_data,
860 "blobdiff" => \&git_blobdiff,
861 "blobdiff_plain" => \&git_blobdiff_plain,
862 "blob" => \&git_blob,
863 "blob_plain" => \&git_blob_plain,
864 "commitdiff" => \&git_commitdiff,
865 "commitdiff_plain" => \&git_commitdiff_plain,
866 "commit" => \&git_commit,
867 "forks" => \&git_forks,
868 "heads" => \&git_heads,
869 "history" => \&git_history,
870 "log" => \&git_log,
871 "patch" => \&git_patch,
872 "patches" => \&git_patches,
873 "remotes" => \&git_remotes,
874 "rss" => \&git_rss,
875 "atom" => \&git_atom,
876 "search" => \&git_search,
877 "search_help" => \&git_search_help,
878 "shortlog" => \&git_shortlog,
879 "summary" => \&git_summary,
880 "tag" => \&git_tag,
881 "tags" => \&git_tags,
882 "tree" => \&git_tree,
883 "snapshot" => \&git_snapshot,
884 "object" => \&git_object,
885 # those below don't need $project
886 "opml" => \&git_opml,
887 "project_list" => \&git_project_list,
888 "project_index" => \&git_project_index,
891 # finally, we have the hash of allowed extra_options for the commands that
892 # allow them
893 our %allowed_options = (
894 "--no-merges" => [ qw(rss atom log shortlog history) ],
897 # fill %input_params with the CGI parameters. All values except for 'opt'
898 # should be single values, but opt can be an array. We should probably
899 # build an array of parameters that can be multi-valued, but since for the time
900 # being it's only this one, we just single it out
901 sub evaluate_query_params {
902 our $cgi;
904 while (my ($name, $symbol) = each %cgi_param_mapping) {
905 if ($symbol eq 'opt') {
906 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
907 } else {
908 $input_params{$name} = decode_utf8($cgi->param($symbol));
913 # now read PATH_INFO and update the parameter list for missing parameters
914 sub evaluate_path_info {
915 return if defined $input_params{'project'};
916 return if !$path_info;
917 $path_info =~ s,^/+,,;
918 return if !$path_info;
920 # find which part of PATH_INFO is project
921 my $project = $path_info;
922 $project =~ s,/+$,,;
923 while ($project && !check_head_link("$projectroot/$project")) {
924 $project =~ s,/*[^/]*$,,;
926 return unless $project;
927 $input_params{'project'} = $project;
929 # do not change any parameters if an action is given using the query string
930 return if $input_params{'action'};
931 $path_info =~ s,^\Q$project\E/*,,;
933 # next, check if we have an action
934 my $action = $path_info;
935 $action =~ s,/.*$,,;
936 if (exists $actions{$action}) {
937 $path_info =~ s,^$action/*,,;
938 $input_params{'action'} = $action;
941 # list of actions that want hash_base instead of hash, but can have no
942 # pathname (f) parameter
943 my @wants_base = (
944 'tree',
945 'history',
948 # we want to catch, among others
949 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
950 my ($parentrefname, $parentpathname, $refname, $pathname) =
951 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
953 # first, analyze the 'current' part
954 if (defined $pathname) {
955 # we got "branch:filename" or "branch:dir/"
956 # we could use git_get_type(branch:pathname), but:
957 # - it needs $git_dir
958 # - it does a git() call
959 # - the convention of terminating directories with a slash
960 # makes it superfluous
961 # - embedding the action in the PATH_INFO would make it even
962 # more superfluous
963 $pathname =~ s,^/+,,;
964 if (!$pathname || substr($pathname, -1) eq "/") {
965 $input_params{'action'} ||= "tree";
966 $pathname =~ s,/$,,;
967 } else {
968 # the default action depends on whether we had parent info
969 # or not
970 if ($parentrefname) {
971 $input_params{'action'} ||= "blobdiff_plain";
972 } else {
973 $input_params{'action'} ||= "blob_plain";
976 $input_params{'hash_base'} ||= $refname;
977 $input_params{'file_name'} ||= $pathname;
978 } elsif (defined $refname) {
979 # we got "branch". In this case we have to choose if we have to
980 # set hash or hash_base.
982 # Most of the actions without a pathname only want hash to be
983 # set, except for the ones specified in @wants_base that want
984 # hash_base instead. It should also be noted that hand-crafted
985 # links having 'history' as an action and no pathname or hash
986 # set will fail, but that happens regardless of PATH_INFO.
987 if (defined $parentrefname) {
988 # if there is parent let the default be 'shortlog' action
989 # (for http://git.example.com/repo.git/A..B links); if there
990 # is no parent, dispatch will detect type of object and set
991 # action appropriately if required (if action is not set)
992 $input_params{'action'} ||= "shortlog";
994 if ($input_params{'action'} &&
995 grep { $_ eq $input_params{'action'} } @wants_base) {
996 $input_params{'hash_base'} ||= $refname;
997 } else {
998 $input_params{'hash'} ||= $refname;
1002 # next, handle the 'parent' part, if present
1003 if (defined $parentrefname) {
1004 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1005 # someproject/blobdiff/oldrev..newrev:/filename
1006 if ($parentpathname) {
1007 $parentpathname =~ s,^/+,,;
1008 $parentpathname =~ s,/$,,;
1009 $input_params{'file_parent'} ||= $parentpathname;
1010 } else {
1011 $input_params{'file_parent'} ||= $input_params{'file_name'};
1013 # we assume that hash_parent_base is wanted if a path was specified,
1014 # or if the action wants hash_base instead of hash
1015 if (defined $input_params{'file_parent'} ||
1016 grep { $_ eq $input_params{'action'} } @wants_base) {
1017 $input_params{'hash_parent_base'} ||= $parentrefname;
1018 } else {
1019 $input_params{'hash_parent'} ||= $parentrefname;
1023 # for the snapshot action, we allow URLs in the form
1024 # $project/snapshot/$hash.ext
1025 # where .ext determines the snapshot and gets removed from the
1026 # passed $refname to provide the $hash.
1028 # To be able to tell that $refname includes the format extension, we
1029 # require the following two conditions to be satisfied:
1030 # - the hash input parameter MUST have been set from the $refname part
1031 # of the URL (i.e. they must be equal)
1032 # - the snapshot format MUST NOT have been defined already (e.g. from
1033 # CGI parameter sf)
1034 # It's also useless to try any matching unless $refname has a dot,
1035 # so we check for that too
1036 if (defined $input_params{'action'} &&
1037 $input_params{'action'} eq 'snapshot' &&
1038 defined $refname && index($refname, '.') != -1 &&
1039 $refname eq $input_params{'hash'} &&
1040 !defined $input_params{'snapshot_format'}) {
1041 # We loop over the known snapshot formats, checking for
1042 # extensions. Allowed extensions are both the defined suffix
1043 # (which includes the initial dot already) and the snapshot
1044 # format key itself, with a prepended dot
1045 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1046 my $hash = $refname;
1047 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1048 next;
1050 my $sfx = $1;
1051 # a valid suffix was found, so set the snapshot format
1052 # and reset the hash parameter
1053 $input_params{'snapshot_format'} = $fmt;
1054 $input_params{'hash'} = $hash;
1055 # we also set the format suffix to the one requested
1056 # in the URL: this way a request for e.g. .tgz returns
1057 # a .tgz instead of a .tar.gz
1058 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1059 last;
1064 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1065 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1066 $searchtext, $search_regexp, $project_filter);
1067 sub evaluate_and_validate_params {
1068 our $action = $input_params{'action'};
1069 if (defined $action) {
1070 if (!is_valid_action($action)) {
1071 die_error(400, "Invalid action parameter");
1075 # parameters which are pathnames
1076 our $project = $input_params{'project'};
1077 if (defined $project) {
1078 if (!is_valid_project($project)) {
1079 undef $project;
1080 die_error(404, "No such project");
1084 our $project_filter = $input_params{'project_filter'};
1085 if (defined $project_filter) {
1086 if (!is_valid_pathname($project_filter)) {
1087 die_error(404, "Invalid project_filter parameter");
1091 our $file_name = $input_params{'file_name'};
1092 if (defined $file_name) {
1093 if (!is_valid_pathname($file_name)) {
1094 die_error(400, "Invalid file parameter");
1098 our $file_parent = $input_params{'file_parent'};
1099 if (defined $file_parent) {
1100 if (!is_valid_pathname($file_parent)) {
1101 die_error(400, "Invalid file parent parameter");
1105 # parameters which are refnames
1106 our $hash = $input_params{'hash'};
1107 if (defined $hash) {
1108 if (!is_valid_refname($hash)) {
1109 die_error(400, "Invalid hash parameter");
1113 our $hash_parent = $input_params{'hash_parent'};
1114 if (defined $hash_parent) {
1115 if (!is_valid_refname($hash_parent)) {
1116 die_error(400, "Invalid hash parent parameter");
1120 our $hash_base = $input_params{'hash_base'};
1121 if (defined $hash_base) {
1122 if (!is_valid_refname($hash_base)) {
1123 die_error(400, "Invalid hash base parameter");
1127 our @extra_options = @{$input_params{'extra_options'}};
1128 # @extra_options is always defined, since it can only be (currently) set from
1129 # CGI, and $cgi->param() returns the empty array in array context if the param
1130 # is not set
1131 foreach my $opt (@extra_options) {
1132 if (not exists $allowed_options{$opt}) {
1133 die_error(400, "Invalid option parameter");
1135 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1136 die_error(400, "Invalid option parameter for this action");
1140 our $hash_parent_base = $input_params{'hash_parent_base'};
1141 if (defined $hash_parent_base) {
1142 if (!is_valid_refname($hash_parent_base)) {
1143 die_error(400, "Invalid hash parent base parameter");
1147 # other parameters
1148 our $page = $input_params{'page'};
1149 if (defined $page) {
1150 if ($page =~ m/[^0-9]/) {
1151 die_error(400, "Invalid page parameter");
1155 our $searchtype = $input_params{'searchtype'};
1156 if (defined $searchtype) {
1157 if ($searchtype =~ m/[^a-z]/) {
1158 die_error(400, "Invalid searchtype parameter");
1162 our $search_use_regexp = $input_params{'search_use_regexp'};
1164 our $searchtext = $input_params{'searchtext'};
1165 our $search_regexp = undef;
1166 if (defined $searchtext) {
1167 if (length($searchtext) < 2) {
1168 die_error(403, "At least two characters are required for search parameter");
1170 if ($search_use_regexp) {
1171 $search_regexp = $searchtext;
1172 if (!eval { qr/$search_regexp/; 1; }) {
1173 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1174 die_error(400, "Invalid search regexp '$search_regexp'",
1175 esc_html($error));
1177 } else {
1178 $search_regexp = quotemeta $searchtext;
1183 # path to the current git repository
1184 our $git_dir;
1185 sub evaluate_git_dir {
1186 our $git_dir = "$projectroot/$project" if $project;
1189 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1190 sub configure_gitweb_features {
1191 # list of supported snapshot formats
1192 our @snapshot_fmts = gitweb_get_feature('snapshot');
1193 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1195 # check that the avatar feature is set to a known provider name,
1196 # and for each provider check if the dependencies are satisfied.
1197 # if the provider name is invalid or the dependencies are not met,
1198 # reset $git_avatar to the empty string.
1199 our ($git_avatar) = gitweb_get_feature('avatar');
1200 if ($git_avatar eq 'gravatar') {
1201 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1202 } elsif ($git_avatar eq 'picon') {
1203 # no dependencies
1204 } else {
1205 $git_avatar = '';
1208 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1209 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1212 sub get_branch_refs {
1213 return ('heads', @extra_branch_refs);
1216 # custom error handler: 'die <message>' is Internal Server Error
1217 sub handle_errors_html {
1218 my $msg = shift; # it is already HTML escaped
1220 # to avoid infinite loop where error occurs in die_error,
1221 # change handler to default handler, disabling handle_errors_html
1222 set_message("Error occurred when inside die_error:\n$msg");
1224 # you cannot jump out of die_error when called as error handler;
1225 # the subroutine set via CGI::Carp::set_message is called _after_
1226 # HTTP headers are already written, so it cannot write them itself
1227 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1229 set_message(\&handle_errors_html);
1231 # dispatch
1232 sub dispatch {
1233 if (!defined $action) {
1234 if (defined $hash) {
1235 $action = git_get_type($hash);
1236 $action or die_error(404, "Object does not exist");
1237 } elsif (defined $hash_base && defined $file_name) {
1238 $action = git_get_type("$hash_base:$file_name");
1239 $action or die_error(404, "File or directory does not exist");
1240 } elsif (defined $project) {
1241 $action = 'summary';
1242 } else {
1243 $action = 'project_list';
1246 if (!defined($actions{$action})) {
1247 die_error(400, "Unknown action");
1249 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1250 !$project) {
1251 die_error(400, "Project needed");
1253 $actions{$action}->();
1256 sub reset_timer {
1257 our $t0 = [ gettimeofday() ]
1258 if defined $t0;
1259 our $number_of_git_cmds = 0;
1262 our $first_request = 1;
1263 our $evaluate_uri_force = undef;
1264 sub run_request {
1265 reset_timer();
1267 # Only allow GET and HEAD methods
1268 if (!$ENV{'REQUEST_METHOD'} || ($ENV{'REQUEST_METHOD'} ne 'GET' && $ENV{'REQUEST_METHOD'} ne 'HEAD')) {
1269 print <<EOT;
1270 Status: 405 Method Not Allowed
1271 Content-Type: text/plain
1272 Allow: GET,HEAD
1274 405 Method Not Allowed
1276 return;
1279 evaluate_uri();
1280 &$evaluate_uri_force() if $evaluate_uri_force;
1281 if ($per_request_config) {
1282 if (ref($per_request_config) eq 'CODE') {
1283 $per_request_config->();
1284 } elsif (!$first_request) {
1285 evaluate_gitweb_config();
1286 evaluate_email_obfuscate();
1289 check_loadavg();
1291 # $projectroot and $projects_list might be set in gitweb config file
1292 $projects_list ||= $projectroot;
1294 evaluate_query_params();
1295 evaluate_path_info();
1296 evaluate_and_validate_params();
1297 evaluate_git_dir();
1299 configure_gitweb_features();
1301 dispatch();
1304 our $is_last_request = sub { 1 };
1305 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1306 our $CGI = 'CGI';
1307 our $cgi;
1308 our $fcgi_mode = 0;
1309 our $fcgi_nproc_active = 0;
1310 sub is_fcgi {
1311 use Errno;
1312 my $stdinfno = fileno STDIN;
1313 return 0 unless defined $stdinfno && $stdinfno == 0;
1314 return 0 unless getsockname STDIN;
1315 return 0 if getpeername STDIN;
1316 return $!{ENOTCONN}?1:0;
1318 sub configure_as_fcgi {
1319 return if $fcgi_mode;
1321 require CGI::Fast;
1322 our $CGI = 'CGI::Fast';
1324 $fcgi_mode = 1;
1325 $first_request = 0;
1326 my $request_number = 0;
1327 # let each child service 100 requests
1328 our $is_last_request = sub { ++$request_number > 100 };
1330 sub evaluate_argv {
1331 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1332 configure_as_fcgi()
1333 if $script_name =~ /\.fcgi$/ || ($auto_fcgi && is_fcgi());
1335 my $nproc_sub = sub {
1336 my ($arg, $val) = @_;
1337 return unless eval { require FCGI::ProcManager; 1; };
1338 $fcgi_nproc_active = 1;
1339 my $proc_manager = FCGI::ProcManager->new({
1340 n_processes => $val,
1342 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1343 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1344 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1346 if (@ARGV) {
1347 require Getopt::Long;
1348 Getopt::Long::GetOptions(
1349 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1350 'nproc|n=i' => $nproc_sub,
1353 if (!$fcgi_nproc_active && defined $ENV{'GITWEB_FCGI_NPROC'} && $ENV{'GITWEB_FCGI_NPROC'} =~ /^\d+$/) {
1354 &$nproc_sub('nproc', $ENV{'GITWEB_FCGI_NPROC'});
1358 sub run {
1359 evaluate_gitweb_config();
1360 evaluate_encoding();
1361 evaluate_email_obfuscate();
1362 evaluate_git_version();
1363 my ($ml, $mi, $bu, $hl, $subroutine) = ($my_url, $my_uri, $base_url, $home_link, '');
1364 $subroutine .= '$my_url = $ml;' if defined $my_url && $my_url ne '';
1365 $subroutine .= '$my_uri = $mi;' if defined $my_uri; # this one can be ""
1366 $subroutine .= '$base_url = $bu;' if defined $base_url && $base_url ne '';
1367 $subroutine .= '$home_link = $hl;' if defined $home_link && $home_link ne '';
1368 $evaluate_uri_force = eval "sub {$subroutine}" if $subroutine;
1369 $first_request = 1;
1370 evaluate_argv();
1372 $pre_listen_hook->()
1373 if $pre_listen_hook;
1375 REQUEST:
1376 while ($cgi = $CGI->new()) {
1377 $pre_dispatch_hook->()
1378 if $pre_dispatch_hook;
1380 run_request();
1382 $post_dispatch_hook->()
1383 if $post_dispatch_hook;
1384 $first_request = 0;
1386 last REQUEST if ($is_last_request->());
1389 DONE_GITWEB:
1393 run();
1395 if (defined caller) {
1396 # wrapped in a subroutine processing requests,
1397 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1398 return;
1399 } else {
1400 # pure CGI script, serving single request
1401 exit;
1404 ## ======================================================================
1405 ## action links
1407 # possible values of extra options
1408 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1409 # -replay => 1 - start from a current view (replay with modifications)
1410 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1411 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1412 sub href {
1413 my %params = @_;
1414 # default is to use -absolute url() i.e. $my_uri
1415 my $href = $params{-full} ? $my_url : $my_uri;
1417 # implicit -replay, must be first of implicit params
1418 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1420 $params{'project'} = $project unless exists $params{'project'};
1422 if ($params{-replay}) {
1423 while (my ($name, $symbol) = each %cgi_param_mapping) {
1424 if (!exists $params{$name}) {
1425 $params{$name} = $input_params{$name};
1430 my $use_pathinfo = gitweb_check_feature('pathinfo');
1431 if (defined $params{'project'} &&
1432 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1433 # try to put as many parameters as possible in PATH_INFO:
1434 # - project name
1435 # - action
1436 # - hash_parent or hash_parent_base:/file_parent
1437 # - hash or hash_base:/filename
1438 # - the snapshot_format as an appropriate suffix
1440 # When the script is the root DirectoryIndex for the domain,
1441 # $href here would be something like http://gitweb.example.com/
1442 # Thus, we strip any trailing / from $href, to spare us double
1443 # slashes in the final URL
1444 $href =~ s,/$,,;
1446 # Then add the project name, if present
1447 $href .= "/".esc_path_info($params{'project'});
1448 delete $params{'project'};
1450 # since we destructively absorb parameters, we keep this
1451 # boolean that remembers if we're handling a snapshot
1452 my $is_snapshot = $params{'action'} eq 'snapshot';
1454 # Summary just uses the project path URL, any other action is
1455 # added to the URL
1456 if (defined $params{'action'}) {
1457 $href .= "/".esc_path_info($params{'action'})
1458 unless $params{'action'} eq 'summary';
1459 delete $params{'action'};
1462 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1463 # stripping nonexistent or useless pieces
1464 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1465 || $params{'hash_parent'} || $params{'hash'});
1466 if (defined $params{'hash_base'}) {
1467 if (defined $params{'hash_parent_base'}) {
1468 $href .= esc_path_info($params{'hash_parent_base'});
1469 # skip the file_parent if it's the same as the file_name
1470 if (defined $params{'file_parent'}) {
1471 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1472 delete $params{'file_parent'};
1473 } elsif ($params{'file_parent'} !~ /\.\./) {
1474 $href .= ":/".esc_path_info($params{'file_parent'});
1475 delete $params{'file_parent'};
1478 $href .= "..";
1479 delete $params{'hash_parent'};
1480 delete $params{'hash_parent_base'};
1481 } elsif (defined $params{'hash_parent'}) {
1482 $href .= esc_path_info($params{'hash_parent'}). "..";
1483 delete $params{'hash_parent'};
1486 $href .= esc_path_info($params{'hash_base'});
1487 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1488 $href .= ":/".esc_path_info($params{'file_name'});
1489 delete $params{'file_name'};
1491 delete $params{'hash'};
1492 delete $params{'hash_base'};
1493 } elsif (defined $params{'hash'}) {
1494 $href .= esc_path_info($params{'hash'});
1495 delete $params{'hash'};
1498 # If the action was a snapshot, we can absorb the
1499 # snapshot_format parameter too
1500 if ($is_snapshot) {
1501 my $fmt = $params{'snapshot_format'};
1502 # snapshot_format should always be defined when href()
1503 # is called, but just in case some code forgets, we
1504 # fall back to the default
1505 $fmt ||= $snapshot_fmts[0];
1506 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1507 delete $params{'snapshot_format'};
1511 # now encode the parameters explicitly
1512 my @result = ();
1513 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1514 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1515 if (defined $params{$name}) {
1516 if (ref($params{$name}) eq "ARRAY") {
1517 foreach my $par (@{$params{$name}}) {
1518 push @result, $symbol . "=" . esc_param($par);
1520 } else {
1521 push @result, $symbol . "=" . esc_param($params{$name});
1525 $href .= "?" . join(';', @result) if scalar @result;
1527 # final transformation: trailing spaces must be escaped (URI-encoded)
1528 $href =~ s/(\s+)$/CGI::escape($1)/e;
1530 if ($params{-anchor}) {
1531 $href .= "#".esc_param($params{-anchor});
1534 return $href;
1538 ## ======================================================================
1539 ## validation, quoting/unquoting and escaping
1541 sub is_valid_action {
1542 my $input = shift;
1543 return undef unless exists $actions{$input};
1544 return 1;
1547 sub is_valid_project {
1548 my $input = shift;
1550 return unless defined $input;
1551 if (!is_valid_pathname($input) ||
1552 !(-d "$projectroot/$input") ||
1553 !check_export_ok("$projectroot/$input") ||
1554 ($strict_export && !project_in_list($input))) {
1555 return undef;
1556 } else {
1557 return 1;
1561 sub is_valid_pathname {
1562 my $input = shift;
1564 return undef unless defined $input;
1565 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1566 # at the beginning, at the end, and between slashes.
1567 # also this catches doubled slashes
1568 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1569 return undef;
1571 # no null characters
1572 if ($input =~ m!\0!) {
1573 return undef;
1575 return 1;
1578 sub is_valid_ref_format {
1579 my $input = shift;
1581 return undef unless defined $input;
1582 # restrictions on ref name according to git-check-ref-format
1583 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1584 return undef;
1586 return 1;
1589 sub is_valid_refname {
1590 my $input = shift;
1592 return undef unless defined $input;
1593 # textual hashes are O.K.
1594 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1595 return 1;
1597 # it must be correct pathname
1598 is_valid_pathname($input) or return undef;
1599 # check git-check-ref-format restrictions
1600 is_valid_ref_format($input) or return undef;
1601 return 1;
1604 # decode sequences of octets in utf8 into Perl's internal form,
1605 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1606 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1607 sub to_utf8 {
1608 my $str = shift;
1609 return undef unless defined $str;
1611 if (utf8::is_utf8($str) || utf8::decode($str)) {
1612 return $str;
1613 } else {
1614 return $encode_object->decode($str, Encode::FB_DEFAULT);
1618 # quote unsafe chars, but keep the slash, even when it's not
1619 # correct, but quoted slashes look too horrible in bookmarks
1620 sub esc_param {
1621 my $str = shift;
1622 return undef unless defined $str;
1623 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1624 $str =~ s/ /\+/g;
1625 return $str;
1628 # the quoting rules for path_info fragment are slightly different
1629 sub esc_path_info {
1630 my $str = shift;
1631 return undef unless defined $str;
1633 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1634 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1636 return $str;
1639 # quote unsafe chars in whole URL, so some characters cannot be quoted
1640 sub esc_url {
1641 my $str = shift;
1642 return undef unless defined $str;
1643 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1644 $str =~ s/ /\+/g;
1645 return $str;
1648 # quote unsafe characters in HTML attributes
1649 sub esc_attr {
1651 # for XHTML conformance escaping '"' to '&quot;' is not enough
1652 return esc_html(@_);
1655 # replace invalid utf8 character with SUBSTITUTION sequence
1656 sub esc_html {
1657 my $str = shift;
1658 my %opts = @_;
1660 return undef unless defined $str;
1662 $str = to_utf8($str);
1663 $str = $cgi->escapeHTML($str);
1664 if ($opts{'-nbsp'}) {
1665 $str =~ s/ /&nbsp;/g;
1667 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1668 return $str;
1671 # quote control characters and escape filename to HTML
1672 sub esc_path {
1673 my $str = shift;
1674 my %opts = @_;
1676 return undef unless defined $str;
1678 $str = to_utf8($str);
1679 $str = $cgi->escapeHTML($str);
1680 if ($opts{'-nbsp'}) {
1681 $str =~ s/ /&nbsp;/g;
1683 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1684 return $str;
1687 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1688 sub sanitize {
1689 my $str = shift;
1691 return undef unless defined $str;
1693 $str = to_utf8($str);
1694 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1695 return $str;
1698 # Make control characters "printable", using character escape codes (CEC)
1699 sub quot_cec {
1700 my $cntrl = shift;
1701 my %opts = @_;
1702 my %es = ( # character escape codes, aka escape sequences
1703 "\t" => '\t', # tab (HT)
1704 "\n" => '\n', # line feed (LF)
1705 "\r" => '\r', # carrige return (CR)
1706 "\f" => '\f', # form feed (FF)
1707 "\b" => '\b', # backspace (BS)
1708 "\a" => '\a', # alarm (bell) (BEL)
1709 "\e" => '\e', # escape (ESC)
1710 "\013" => '\v', # vertical tab (VT)
1711 "\000" => '\0', # nul character (NUL)
1713 my $chr = ( (exists $es{$cntrl})
1714 ? $es{$cntrl}
1715 : sprintf('\%2x', ord($cntrl)) );
1716 if ($opts{-nohtml}) {
1717 return $chr;
1718 } else {
1719 return "<span class=\"cntrl\">$chr</span>";
1723 # Alternatively use unicode control pictures codepoints,
1724 # Unicode "printable representation" (PR)
1725 sub quot_upr {
1726 my $cntrl = shift;
1727 my %opts = @_;
1729 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1730 if ($opts{-nohtml}) {
1731 return $chr;
1732 } else {
1733 return "<span class=\"cntrl\">$chr</span>";
1737 # git may return quoted and escaped filenames
1738 sub unquote {
1739 my $str = shift;
1741 sub unq {
1742 my $seq = shift;
1743 my %es = ( # character escape codes, aka escape sequences
1744 't' => "\t", # tab (HT, TAB)
1745 'n' => "\n", # newline (NL)
1746 'r' => "\r", # return (CR)
1747 'f' => "\f", # form feed (FF)
1748 'b' => "\b", # backspace (BS)
1749 'a' => "\a", # alarm (bell) (BEL)
1750 'e' => "\e", # escape (ESC)
1751 'v' => "\013", # vertical tab (VT)
1754 if ($seq =~ m/^[0-7]{1,3}$/) {
1755 # octal char sequence
1756 return chr(oct($seq));
1757 } elsif (exists $es{$seq}) {
1758 # C escape sequence, aka character escape code
1759 return $es{$seq};
1761 # quoted ordinary character
1762 return $seq;
1765 if ($str =~ m/^"(.*)"$/) {
1766 # needs unquoting
1767 $str = $1;
1768 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1770 return $str;
1773 # escape tabs (convert tabs to spaces)
1774 sub untabify {
1775 my $line = shift;
1777 while ((my $pos = index($line, "\t")) != -1) {
1778 if (my $count = (8 - ($pos % 8))) {
1779 my $spaces = ' ' x $count;
1780 $line =~ s/\t/$spaces/;
1784 return $line;
1787 sub project_in_list {
1788 my $project = shift;
1789 my @list = git_get_projects_list();
1790 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1793 ## ----------------------------------------------------------------------
1794 ## HTML aware string manipulation
1796 # Try to chop given string on a word boundary between position
1797 # $len and $len+$add_len. If there is no word boundary there,
1798 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1799 # (marking chopped part) would be longer than given string.
1800 sub chop_str {
1801 my $str = shift;
1802 my $len = shift;
1803 my $add_len = shift || 10;
1804 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1806 # Make sure perl knows it is utf8 encoded so we don't
1807 # cut in the middle of a utf8 multibyte char.
1808 $str = to_utf8($str);
1810 # allow only $len chars, but don't cut a word if it would fit in $add_len
1811 # if it doesn't fit, cut it if it's still longer than the dots we would add
1812 # remove chopped character entities entirely
1814 # when chopping in the middle, distribute $len into left and right part
1815 # return early if chopping wouldn't make string shorter
1816 if ($where eq 'center') {
1817 return $str if ($len + 5 >= length($str)); # filler is length 5
1818 $len = int($len/2);
1819 } else {
1820 return $str if ($len + 4 >= length($str)); # filler is length 4
1823 # regexps: ending and beginning with word part up to $add_len
1824 my $endre = qr/.{$len}\w{0,$add_len}/;
1825 my $begre = qr/\w{0,$add_len}.{$len}/;
1827 if ($where eq 'left') {
1828 $str =~ m/^(.*?)($begre)$/;
1829 my ($lead, $body) = ($1, $2);
1830 if (length($lead) > 4) {
1831 $lead = " ...";
1833 return "$lead$body";
1835 } elsif ($where eq 'center') {
1836 $str =~ m/^($endre)(.*)$/;
1837 my ($left, $str) = ($1, $2);
1838 $str =~ m/^(.*?)($begre)$/;
1839 my ($mid, $right) = ($1, $2);
1840 if (length($mid) > 5) {
1841 $mid = " ... ";
1843 return "$left$mid$right";
1845 } else {
1846 $str =~ m/^($endre)(.*)$/;
1847 my $body = $1;
1848 my $tail = $2;
1849 if (length($tail) > 4) {
1850 $tail = "... ";
1852 return "$body$tail";
1856 # pass-through email filter, obfuscating it when possible
1857 sub email_obfuscate {
1858 our $email;
1859 my ($str) = @_;
1860 if ($email) {
1861 $str = $email->escape_html($str);
1862 # Stock HTML::Email::Obfuscate version likes to produce
1863 # invalid XHTML...
1864 $str =~ s#<(/?)B>#<$1b>#g;
1865 return $str;
1866 } else {
1867 $str = esc_html($str);
1868 $str =~ s/@/&#x40;/;
1869 return $str;
1873 # takes the same arguments as chop_str, but also wraps a <span> around the
1874 # result with a title attribute if it does get chopped. Additionally, the
1875 # string is HTML-escaped.
1876 sub chop_and_escape_str {
1877 my ($str) = @_;
1879 my $chopped = chop_str(@_);
1880 $str = to_utf8($str);
1881 if ($chopped eq $str) {
1882 return email_obfuscate($chopped);
1883 } else {
1884 $str =~ s/[[:cntrl:]]/?/g;
1885 return $cgi->span({-title=>$str}, email_obfuscate($chopped));
1889 # Highlight selected fragments of string, using given CSS class,
1890 # and escape HTML. It is assumed that fragments do not overlap.
1891 # Regions are passed as list of pairs (array references).
1893 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1894 # '<span class="mark">foo</span>bar'
1895 sub esc_html_hl_regions {
1896 my ($str, $css_class, @sel) = @_;
1897 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1898 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1899 return esc_html($str, %opts) unless @sel;
1901 my $out = '';
1902 my $pos = 0;
1904 for my $s (@sel) {
1905 my ($begin, $end) = @$s;
1907 # Don't create empty <span> elements.
1908 next if $end <= $begin;
1910 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1911 %opts);
1913 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1914 if ($begin - $pos > 0);
1915 $out .= $cgi->span({-class => $css_class}, $escaped);
1917 $pos = $end;
1919 $out .= esc_html(substr($str, $pos), %opts)
1920 if ($pos < length($str));
1922 return $out;
1925 # return positions of beginning and end of each match
1926 sub matchpos_list {
1927 my ($str, $regexp) = @_;
1928 return unless (defined $str && defined $regexp);
1930 my @matches;
1931 while ($str =~ /$regexp/g) {
1932 push @matches, [$-[0], $+[0]];
1934 return @matches;
1937 # highlight match (if any), and escape HTML
1938 sub esc_html_match_hl {
1939 my ($str, $regexp) = @_;
1940 return esc_html($str) unless defined $regexp;
1942 my @matches = matchpos_list($str, $regexp);
1943 return esc_html($str) unless @matches;
1945 return esc_html_hl_regions($str, 'match', @matches);
1949 # highlight match (if any) of shortened string, and escape HTML
1950 sub esc_html_match_hl_chopped {
1951 my ($str, $chopped, $regexp) = @_;
1952 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1954 my @matches = matchpos_list($str, $regexp);
1955 return esc_html($chopped) unless @matches;
1957 # filter matches so that we mark chopped string
1958 my $tail = "... "; # see chop_str
1959 unless ($chopped =~ s/\Q$tail\E$//) {
1960 $tail = '';
1962 my $chop_len = length($chopped);
1963 my $tail_len = length($tail);
1964 my @filtered;
1966 for my $m (@matches) {
1967 if ($m->[0] > $chop_len) {
1968 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1969 last;
1970 } elsif ($m->[1] > $chop_len) {
1971 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1972 last;
1974 push @filtered, $m;
1977 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1980 ## ----------------------------------------------------------------------
1981 ## functions returning short strings
1983 # CSS class for given age value (in seconds)
1984 sub age_class {
1985 my $age = shift;
1987 if (!defined $age) {
1988 return "noage";
1989 } elsif ($age < 60*60*2) {
1990 return "age0";
1991 } elsif ($age < 60*60*24*2) {
1992 return "age1";
1993 } else {
1994 return "age2";
1998 # convert age in seconds to "nn units ago" string
1999 sub age_string {
2000 my $age = shift;
2001 my $age_str;
2003 if ($age > 60*60*24*365*2) {
2004 $age_str = (int $age/60/60/24/365);
2005 $age_str .= " years ago";
2006 } elsif ($age > 60*60*24*(365/12)*2) {
2007 $age_str = int $age/60/60/24/(365/12);
2008 $age_str .= " months ago";
2009 } elsif ($age > 60*60*24*7*2) {
2010 $age_str = int $age/60/60/24/7;
2011 $age_str .= " weeks ago";
2012 } elsif ($age > 60*60*24*2) {
2013 $age_str = int $age/60/60/24;
2014 $age_str .= " days ago";
2015 } elsif ($age > 60*60*2) {
2016 $age_str = int $age/60/60;
2017 $age_str .= " hours ago";
2018 } elsif ($age > 60*2) {
2019 $age_str = int $age/60;
2020 $age_str .= " min ago";
2021 } elsif ($age > 2) {
2022 $age_str = int $age;
2023 $age_str .= " sec ago";
2024 } else {
2025 $age_str .= " right now";
2027 return $age_str;
2030 use constant {
2031 S_IFINVALID => 0030000,
2032 S_IFGITLINK => 0160000,
2035 # submodule/subproject, a commit object reference
2036 sub S_ISGITLINK {
2037 my $mode = shift;
2039 return (($mode & S_IFMT) == S_IFGITLINK)
2042 # convert file mode in octal to symbolic file mode string
2043 sub mode_str {
2044 my $mode = oct shift;
2046 if (S_ISGITLINK($mode)) {
2047 return 'm---------';
2048 } elsif (S_ISDIR($mode & S_IFMT)) {
2049 return 'drwxr-xr-x';
2050 } elsif (S_ISLNK($mode)) {
2051 return 'lrwxrwxrwx';
2052 } elsif (S_ISREG($mode)) {
2053 # git cares only about the executable bit
2054 if ($mode & S_IXUSR) {
2055 return '-rwxr-xr-x';
2056 } else {
2057 return '-rw-r--r--';
2059 } else {
2060 return '----------';
2064 # convert file mode in octal to file type string
2065 sub file_type {
2066 my $mode = shift;
2068 if ($mode !~ m/^[0-7]+$/) {
2069 return $mode;
2070 } else {
2071 $mode = oct $mode;
2074 if (S_ISGITLINK($mode)) {
2075 return "submodule";
2076 } elsif (S_ISDIR($mode & S_IFMT)) {
2077 return "directory";
2078 } elsif (S_ISLNK($mode)) {
2079 return "symlink";
2080 } elsif (S_ISREG($mode)) {
2081 return "file";
2082 } else {
2083 return "unknown";
2087 # convert file mode in octal to file type description string
2088 sub file_type_long {
2089 my $mode = shift;
2091 if ($mode !~ m/^[0-7]+$/) {
2092 return $mode;
2093 } else {
2094 $mode = oct $mode;
2097 if (S_ISGITLINK($mode)) {
2098 return "submodule";
2099 } elsif (S_ISDIR($mode & S_IFMT)) {
2100 return "directory";
2101 } elsif (S_ISLNK($mode)) {
2102 return "symlink";
2103 } elsif (S_ISREG($mode)) {
2104 if ($mode & S_IXUSR) {
2105 return "executable";
2106 } else {
2107 return "file";
2109 } else {
2110 return "unknown";
2115 ## ----------------------------------------------------------------------
2116 ## functions returning short HTML fragments, or transforming HTML fragments
2117 ## which don't belong to other sections
2119 # format line of commit message.
2120 sub format_log_line_html {
2121 my $line = shift;
2123 $line = esc_html($line, -nbsp=>1);
2124 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2125 $cgi->a({-href => href(action=>"object", hash=>$1),
2126 -class => "text"}, $1);
2127 }eg;
2129 return $line;
2132 # format marker of refs pointing to given object
2134 # the destination action is chosen based on object type and current context:
2135 # - for annotated tags, we choose the tag view unless it's the current view
2136 # already, in which case we go to shortlog view
2137 # - for other refs, we keep the current view if we're in history, shortlog or
2138 # log view, and select shortlog otherwise
2139 sub format_ref_marker {
2140 my ($refs, $id) = @_;
2141 my $markers = '';
2143 if (defined $refs->{$id}) {
2144 foreach my $ref (@{$refs->{$id}}) {
2145 # this code exploits the fact that non-lightweight tags are the
2146 # only indirect objects, and that they are the only objects for which
2147 # we want to use tag instead of shortlog as action
2148 my ($type, $name) = qw();
2149 my $indirect = ($ref =~ s/\^\{\}$//);
2150 # e.g. tags/v2.6.11 or heads/next
2151 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2152 $type = $1;
2153 $name = $2;
2154 } else {
2155 $type = "ref";
2156 $name = $ref;
2159 my $class = $type;
2160 $class .= " indirect" if $indirect;
2162 my $dest_action = "shortlog";
2164 if ($indirect) {
2165 $dest_action = "tag" unless $action eq "tag";
2166 } elsif ($action =~ /^(history|(short)?log)$/) {
2167 $dest_action = $action;
2170 my $dest = "";
2171 $dest .= "refs/" unless $ref =~ m!^refs/!;
2172 $dest .= $ref;
2174 my $link = $cgi->a({
2175 -href => href(
2176 action=>$dest_action,
2177 hash=>$dest
2178 )}, $name);
2180 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2181 $link . "</span>";
2185 if ($markers) {
2186 return ' <span class="refs">'. $markers . '</span>';
2187 } else {
2188 return "";
2192 # format, perhaps shortened and with markers, title line
2193 sub format_subject_html {
2194 my ($long, $short, $href, $extra) = @_;
2195 $extra = '' unless defined($extra);
2197 if (length($short) < length($long)) {
2198 $long =~ s/[[:cntrl:]]/?/g;
2199 return $cgi->a({-href => $href, -class => "list subject",
2200 -title => to_utf8($long)},
2201 esc_html($short)) . $extra;
2202 } else {
2203 return $cgi->a({-href => $href, -class => "list subject"},
2204 esc_html($long)) . $extra;
2208 # Rather than recomputing the url for an email multiple times, we cache it
2209 # after the first hit. This gives a visible benefit in views where the avatar
2210 # for the same email is used repeatedly (e.g. shortlog).
2211 # The cache is shared by all avatar engines (currently gravatar only), which
2212 # are free to use it as preferred. Since only one avatar engine is used for any
2213 # given page, there's no risk for cache conflicts.
2214 our %avatar_cache = ();
2216 # Compute the picon url for a given email, by using the picon search service over at
2217 # http://www.cs.indiana.edu/picons/search.html
2218 sub picon_url {
2219 my $email = lc shift;
2220 if (!$avatar_cache{$email}) {
2221 my ($user, $domain) = split('@', $email);
2222 $avatar_cache{$email} =
2223 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2224 "$domain/$user/" .
2225 "users+domains+unknown/up/single";
2227 return $avatar_cache{$email};
2230 # Compute the gravatar url for a given email, if it's not in the cache already.
2231 # Gravatar stores only the part of the URL before the size, since that's the
2232 # one computationally more expensive. This also allows reuse of the cache for
2233 # different sizes (for this particular engine).
2234 sub gravatar_url {
2235 my $email = lc shift;
2236 my $size = shift;
2237 $avatar_cache{$email} ||=
2238 "//www.gravatar.com/avatar/" .
2239 Digest::MD5::md5_hex($email) . "?s=";
2240 return $avatar_cache{$email} . $size;
2243 # Insert an avatar for the given $email at the given $size if the feature
2244 # is enabled.
2245 sub git_get_avatar {
2246 my ($email, %opts) = @_;
2247 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2248 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2249 $opts{-size} ||= 'default';
2250 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2251 my $url = "";
2252 if ($git_avatar eq 'gravatar') {
2253 $url = gravatar_url($email, $size);
2254 } elsif ($git_avatar eq 'picon') {
2255 $url = picon_url($email);
2257 # Other providers can be added by extending the if chain, defining $url
2258 # as needed. If no variant puts something in $url, we assume avatars
2259 # are completely disabled/unavailable.
2260 if ($url) {
2261 return $pre_white .
2262 "<img width=\"$size\" " .
2263 "class=\"avatar\" " .
2264 "src=\"".esc_url($url)."\" " .
2265 "alt=\"\" " .
2266 "/>" . $post_white;
2267 } else {
2268 return "";
2272 sub format_search_author {
2273 my ($author, $searchtype, $displaytext) = @_;
2274 my $have_search = gitweb_check_feature('search');
2276 if ($have_search) {
2277 my $performed = "";
2278 if ($searchtype eq 'author') {
2279 $performed = "authored";
2280 } elsif ($searchtype eq 'committer') {
2281 $performed = "committed";
2284 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2285 searchtext=>$author,
2286 searchtype=>$searchtype), class=>"list",
2287 title=>"Search for commits $performed by $author"},
2288 $displaytext);
2290 } else {
2291 return $displaytext;
2295 # format the author name of the given commit with the given tag
2296 # the author name is chopped and escaped according to the other
2297 # optional parameters (see chop_str).
2298 sub format_author_html {
2299 my $tag = shift;
2300 my $co = shift;
2301 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2302 return "<$tag class=\"author\">" .
2303 format_search_author($co->{'author_name'}, "author",
2304 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2305 $author) .
2306 "</$tag>";
2309 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2310 sub format_git_diff_header_line {
2311 my $line = shift;
2312 my $diffinfo = shift;
2313 my ($from, $to) = @_;
2315 if ($diffinfo->{'nparents'}) {
2316 # combined diff
2317 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2318 if ($to->{'href'}) {
2319 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2320 esc_path($to->{'file'}));
2321 } else { # file was deleted (no href)
2322 $line .= esc_path($to->{'file'});
2324 } else {
2325 # "ordinary" diff
2326 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2327 if ($from->{'href'}) {
2328 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2329 'a/' . esc_path($from->{'file'}));
2330 } else { # file was added (no href)
2331 $line .= 'a/' . esc_path($from->{'file'});
2333 $line .= ' ';
2334 if ($to->{'href'}) {
2335 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2336 'b/' . esc_path($to->{'file'}));
2337 } else { # file was deleted
2338 $line .= 'b/' . esc_path($to->{'file'});
2342 return "<div class=\"diff header\">$line</div>\n";
2345 # format extended diff header line, before patch itself
2346 sub format_extended_diff_header_line {
2347 my $line = shift;
2348 my $diffinfo = shift;
2349 my ($from, $to) = @_;
2351 # match <path>
2352 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2353 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2354 esc_path($from->{'file'}));
2356 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2357 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2358 esc_path($to->{'file'}));
2360 # match single <mode>
2361 if ($line =~ m/\s(\d{6})$/) {
2362 $line .= '<span class="info"> (' .
2363 file_type_long($1) .
2364 ')</span>';
2366 # match <hash>
2367 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2368 # can match only for combined diff
2369 $line = 'index ';
2370 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2371 if ($from->{'href'}[$i]) {
2372 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2373 -class=>"hash"},
2374 substr($diffinfo->{'from_id'}[$i],0,7));
2375 } else {
2376 $line .= '0' x 7;
2378 # separator
2379 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2381 $line .= '..';
2382 if ($to->{'href'}) {
2383 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2384 substr($diffinfo->{'to_id'},0,7));
2385 } else {
2386 $line .= '0' x 7;
2389 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2390 # can match only for ordinary diff
2391 my ($from_link, $to_link);
2392 if ($from->{'href'}) {
2393 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2394 substr($diffinfo->{'from_id'},0,7));
2395 } else {
2396 $from_link = '0' x 7;
2398 if ($to->{'href'}) {
2399 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2400 substr($diffinfo->{'to_id'},0,7));
2401 } else {
2402 $to_link = '0' x 7;
2404 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2405 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2408 return $line . "<br/>\n";
2411 # format from-file/to-file diff header
2412 sub format_diff_from_to_header {
2413 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2414 my $line;
2415 my $result = '';
2417 $line = $from_line;
2418 #assert($line =~ m/^---/) if DEBUG;
2419 # no extra formatting for "^--- /dev/null"
2420 if (! $diffinfo->{'nparents'}) {
2421 # ordinary (single parent) diff
2422 if ($line =~ m!^--- "?a/!) {
2423 if ($from->{'href'}) {
2424 $line = '--- a/' .
2425 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2426 esc_path($from->{'file'}));
2427 } else {
2428 $line = '--- a/' .
2429 esc_path($from->{'file'});
2432 $result .= qq!<div class="diff from_file">$line</div>\n!;
2434 } else {
2435 # combined diff (merge commit)
2436 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2437 if ($from->{'href'}[$i]) {
2438 $line = '--- ' .
2439 $cgi->a({-href=>href(action=>"blobdiff",
2440 hash_parent=>$diffinfo->{'from_id'}[$i],
2441 hash_parent_base=>$parents[$i],
2442 file_parent=>$from->{'file'}[$i],
2443 hash=>$diffinfo->{'to_id'},
2444 hash_base=>$hash,
2445 file_name=>$to->{'file'}),
2446 -class=>"path",
2447 -title=>"diff" . ($i+1)},
2448 $i+1) .
2449 '/' .
2450 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2451 esc_path($from->{'file'}[$i]));
2452 } else {
2453 $line = '--- /dev/null';
2455 $result .= qq!<div class="diff from_file">$line</div>\n!;
2459 $line = $to_line;
2460 #assert($line =~ m/^\+\+\+/) if DEBUG;
2461 # no extra formatting for "^+++ /dev/null"
2462 if ($line =~ m!^\+\+\+ "?b/!) {
2463 if ($to->{'href'}) {
2464 $line = '+++ b/' .
2465 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2466 esc_path($to->{'file'}));
2467 } else {
2468 $line = '+++ b/' .
2469 esc_path($to->{'file'});
2472 $result .= qq!<div class="diff to_file">$line</div>\n!;
2474 return $result;
2477 # create note for patch simplified by combined diff
2478 sub format_diff_cc_simplified {
2479 my ($diffinfo, @parents) = @_;
2480 my $result = '';
2482 $result .= "<div class=\"diff header\">" .
2483 "diff --cc ";
2484 if (!is_deleted($diffinfo)) {
2485 $result .= $cgi->a({-href => href(action=>"blob",
2486 hash_base=>$hash,
2487 hash=>$diffinfo->{'to_id'},
2488 file_name=>$diffinfo->{'to_file'}),
2489 -class => "path"},
2490 esc_path($diffinfo->{'to_file'}));
2491 } else {
2492 $result .= esc_path($diffinfo->{'to_file'});
2494 $result .= "</div>\n" . # class="diff header"
2495 "<div class=\"diff nodifferences\">" .
2496 "Simple merge" .
2497 "</div>\n"; # class="diff nodifferences"
2499 return $result;
2502 sub diff_line_class {
2503 my ($line, $from, $to) = @_;
2505 # ordinary diff
2506 my $num_sign = 1;
2507 # combined diff
2508 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2509 $num_sign = scalar @{$from->{'href'}};
2512 my @diff_line_classifier = (
2513 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2514 { regexp => qr/^\\/, class => "incomplete" },
2515 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2516 # classifier for context must come before classifier add/rem,
2517 # or we would have to use more complicated regexp, for example
2518 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2519 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2520 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2522 for my $clsfy (@diff_line_classifier) {
2523 return $clsfy->{'class'}
2524 if ($line =~ $clsfy->{'regexp'});
2527 # fallback
2528 return "";
2531 # assumes that $from and $to are defined and correctly filled,
2532 # and that $line holds a line of chunk header for unified diff
2533 sub format_unidiff_chunk_header {
2534 my ($line, $from, $to) = @_;
2536 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2537 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2539 $from_lines = 0 unless defined $from_lines;
2540 $to_lines = 0 unless defined $to_lines;
2542 if ($from->{'href'}) {
2543 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2544 -class=>"list"}, $from_text);
2546 if ($to->{'href'}) {
2547 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2548 -class=>"list"}, $to_text);
2550 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2551 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2552 return $line;
2555 # assumes that $from and $to are defined and correctly filled,
2556 # and that $line holds a line of chunk header for combined diff
2557 sub format_cc_diff_chunk_header {
2558 my ($line, $from, $to) = @_;
2560 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2561 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2563 @from_text = split(' ', $ranges);
2564 for (my $i = 0; $i < @from_text; ++$i) {
2565 ($from_start[$i], $from_nlines[$i]) =
2566 (split(',', substr($from_text[$i], 1)), 0);
2569 $to_text = pop @from_text;
2570 $to_start = pop @from_start;
2571 $to_nlines = pop @from_nlines;
2573 $line = "<span class=\"chunk_info\">$prefix ";
2574 for (my $i = 0; $i < @from_text; ++$i) {
2575 if ($from->{'href'}[$i]) {
2576 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2577 -class=>"list"}, $from_text[$i]);
2578 } else {
2579 $line .= $from_text[$i];
2581 $line .= " ";
2583 if ($to->{'href'}) {
2584 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2585 -class=>"list"}, $to_text);
2586 } else {
2587 $line .= $to_text;
2589 $line .= " $prefix</span>" .
2590 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2591 return $line;
2594 # process patch (diff) line (not to be used for diff headers),
2595 # returning HTML-formatted (but not wrapped) line.
2596 # If the line is passed as a reference, it is treated as HTML and not
2597 # esc_html()'ed.
2598 sub format_diff_line {
2599 my ($line, $diff_class, $from, $to) = @_;
2601 if (ref($line)) {
2602 $line = $$line;
2603 } else {
2604 chomp $line;
2605 $line = untabify($line);
2607 if ($from && $to && $line =~ m/^\@{2} /) {
2608 $line = format_unidiff_chunk_header($line, $from, $to);
2609 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2610 $line = format_cc_diff_chunk_header($line, $from, $to);
2611 } else {
2612 $line = esc_html($line, -nbsp=>1);
2616 my $diff_classes = "diff";
2617 $diff_classes .= " $diff_class" if ($diff_class);
2618 $line = "<div class=\"$diff_classes\">$line</div>\n";
2620 return $line;
2623 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2624 # linked. Pass the hash of the tree/commit to snapshot.
2625 sub format_snapshot_links {
2626 my ($hash) = @_;
2627 my $num_fmts = @snapshot_fmts;
2628 if ($num_fmts > 1) {
2629 # A parenthesized list of links bearing format names.
2630 # e.g. "snapshot (_tar.gz_ _zip_)"
2631 return "snapshot (" . join(' ', map
2632 $cgi->a({
2633 -href => href(
2634 action=>"snapshot",
2635 hash=>$hash,
2636 snapshot_format=>$_
2638 }, $known_snapshot_formats{$_}{'display'})
2639 , @snapshot_fmts) . ")";
2640 } elsif ($num_fmts == 1) {
2641 # A single "snapshot" link whose tooltip bears the format name.
2642 # i.e. "_snapshot_"
2643 my ($fmt) = @snapshot_fmts;
2644 return
2645 $cgi->a({
2646 -href => href(
2647 action=>"snapshot",
2648 hash=>$hash,
2649 snapshot_format=>$fmt
2651 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2652 }, "snapshot");
2653 } else { # $num_fmts == 0
2654 return undef;
2658 ## ......................................................................
2659 ## functions returning values to be passed, perhaps after some
2660 ## transformation, to other functions; e.g. returning arguments to href()
2662 # returns hash to be passed to href to generate gitweb URL
2663 # in -title key it returns description of link
2664 sub get_feed_info {
2665 my $format = shift || 'Atom';
2666 my %res = (action => lc($format));
2667 my $matched_ref = 0;
2669 # feed links are possible only for project views
2670 return unless (defined $project);
2671 # some views should link to OPML, or to generic project feed,
2672 # or don't have specific feed yet (so they should use generic)
2673 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2675 my $branch = undef;
2676 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2677 # (fullname) to differentiate from tag links; this also makes
2678 # possible to detect branch links
2679 for my $ref (get_branch_refs()) {
2680 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2681 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2682 $branch = $1;
2683 $matched_ref = $ref;
2684 last;
2687 # find log type for feed description (title)
2688 my $type = 'log';
2689 if (defined $file_name) {
2690 $type = "history of $file_name";
2691 $type .= "/" if ($action eq 'tree');
2692 $type .= " on '$branch'" if (defined $branch);
2693 } else {
2694 $type = "log of $branch" if (defined $branch);
2697 $res{-title} = $type;
2698 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2699 $res{'file_name'} = $file_name;
2701 return %res;
2704 ## ----------------------------------------------------------------------
2705 ## git utility subroutines, invoking git commands
2707 # returns path to the core git executable and the --git-dir parameter as list
2708 sub git_cmd {
2709 $number_of_git_cmds++;
2710 return $GIT, '--git-dir='.$git_dir;
2713 # quote the given arguments for passing them to the shell
2714 # quote_command("command", "arg 1", "arg with ' and ! characters")
2715 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2716 # Try to avoid using this function wherever possible.
2717 sub quote_command {
2718 return join(' ',
2719 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2722 # get HEAD ref of given project as hash
2723 sub git_get_head_hash {
2724 return git_get_full_hash(shift, 'HEAD');
2727 sub git_get_full_hash {
2728 return git_get_hash(@_);
2731 sub git_get_short_hash {
2732 return git_get_hash(@_, '--short=7');
2735 sub git_get_hash {
2736 my ($project, $hash, @options) = @_;
2737 my $o_git_dir = $git_dir;
2738 my $retval = undef;
2739 $git_dir = "$projectroot/$project";
2740 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2741 '--verify', '-q', @options, $hash) {
2742 $retval = <$fd>;
2743 chomp $retval if defined $retval;
2744 close $fd;
2746 if (defined $o_git_dir) {
2747 $git_dir = $o_git_dir;
2749 return $retval;
2752 # get type of given object
2753 sub git_get_type {
2754 my $hash = shift;
2756 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2757 my $type = <$fd>;
2758 close $fd or return;
2759 chomp $type;
2760 return $type;
2763 # repository configuration
2764 our $config_file = '';
2765 our %config;
2767 # store multiple values for single key as anonymous array reference
2768 # single values stored directly in the hash, not as [ <value> ]
2769 sub hash_set_multi {
2770 my ($hash, $key, $value) = @_;
2772 if (!exists $hash->{$key}) {
2773 $hash->{$key} = $value;
2774 } elsif (!ref $hash->{$key}) {
2775 $hash->{$key} = [ $hash->{$key}, $value ];
2776 } else {
2777 push @{$hash->{$key}}, $value;
2781 # return hash of git project configuration
2782 # optionally limited to some section, e.g. 'gitweb'
2783 sub git_parse_project_config {
2784 my $section_regexp = shift;
2785 my %config;
2787 local $/ = "\0";
2789 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2790 or return;
2792 while (my $keyval = <$fh>) {
2793 chomp $keyval;
2794 my ($key, $value) = split(/\n/, $keyval, 2);
2796 hash_set_multi(\%config, $key, $value)
2797 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2799 close $fh;
2801 return %config;
2804 # convert config value to boolean: 'true' or 'false'
2805 # no value, number > 0, 'true' and 'yes' values are true
2806 # rest of values are treated as false (never as error)
2807 sub config_to_bool {
2808 my $val = shift;
2810 return 1 if !defined $val; # section.key
2812 # strip leading and trailing whitespace
2813 $val =~ s/^\s+//;
2814 $val =~ s/\s+$//;
2816 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2817 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2820 # convert config value to simple decimal number
2821 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2822 # to be multiplied by 1024, 1048576, or 1073741824
2823 sub config_to_int {
2824 my $val = shift;
2826 # strip leading and trailing whitespace
2827 $val =~ s/^\s+//;
2828 $val =~ s/\s+$//;
2830 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2831 $unit = lc($unit);
2832 # unknown unit is treated as 1
2833 return $num * ($unit eq 'g' ? 1073741824 :
2834 $unit eq 'm' ? 1048576 :
2835 $unit eq 'k' ? 1024 : 1);
2837 return $val;
2840 # convert config value to array reference, if needed
2841 sub config_to_multi {
2842 my $val = shift;
2844 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2847 sub git_get_project_config {
2848 my ($key, $type) = @_;
2850 return unless defined $git_dir;
2852 # key sanity check
2853 return unless ($key);
2854 # only subsection, if exists, is case sensitive,
2855 # and not lowercased by 'git config -z -l'
2856 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2857 $lo =~ s/_//g;
2858 $key = join(".", lc($hi), $mi, lc($lo));
2859 return if ($lo =~ /\W/ || $hi =~ /\W/);
2860 } else {
2861 $key = lc($key);
2862 $key =~ s/_//g;
2863 return if ($key =~ /\W/);
2865 $key =~ s/^gitweb\.//;
2867 # type sanity check
2868 if (defined $type) {
2869 $type =~ s/^--//;
2870 $type = undef
2871 unless ($type eq 'bool' || $type eq 'int');
2874 # get config
2875 if (!defined $config_file ||
2876 $config_file ne "$git_dir/config") {
2877 %config = git_parse_project_config('gitweb');
2878 $config_file = "$git_dir/config";
2881 # check if config variable (key) exists
2882 return unless exists $config{"gitweb.$key"};
2884 # ensure given type
2885 if (!defined $type) {
2886 return $config{"gitweb.$key"};
2887 } elsif ($type eq 'bool') {
2888 # backward compatibility: 'git config --bool' returns true/false
2889 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2890 } elsif ($type eq 'int') {
2891 return config_to_int($config{"gitweb.$key"});
2893 return $config{"gitweb.$key"};
2896 # get hash of given path at given ref
2897 sub git_get_hash_by_path {
2898 my $base = shift;
2899 my $path = shift || return undef;
2900 my $type = shift;
2902 $path =~ s,/+$,,;
2904 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2905 or die_error(500, "Open git-ls-tree failed");
2906 my $line = <$fd>;
2907 close $fd or return undef;
2909 if (!defined $line) {
2910 # there is no tree or hash given by $path at $base
2911 return undef;
2914 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2915 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2916 if (defined $type && $type ne $2) {
2917 # type doesn't match
2918 return undef;
2920 return $3;
2923 # get path of entry with given hash at given tree-ish (ref)
2924 # used to get 'from' filename for combined diff (merge commit) for renames
2925 sub git_get_path_by_hash {
2926 my $base = shift || return;
2927 my $hash = shift || return;
2929 local $/ = "\0";
2931 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2932 or return undef;
2933 while (my $line = <$fd>) {
2934 chomp $line;
2936 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2937 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2938 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2939 close $fd;
2940 return $1;
2943 close $fd;
2944 return undef;
2947 ## ......................................................................
2948 ## git utility functions, directly accessing git repository
2950 # get the value of config variable either from file named as the variable
2951 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2952 # configuration variable in the repository config file.
2953 sub git_get_file_or_project_config {
2954 my ($path, $name) = @_;
2956 $git_dir = "$projectroot/$path";
2957 open my $fd, '<', "$git_dir/$name"
2958 or return git_get_project_config($name);
2959 my $conf = <$fd>;
2960 close $fd;
2961 if (defined $conf) {
2962 chomp $conf;
2964 return $conf;
2967 sub git_get_project_description {
2968 my $path = shift;
2969 return git_get_file_or_project_config($path, 'description');
2972 sub git_get_project_category {
2973 my $path = shift;
2974 return git_get_file_or_project_config($path, 'category');
2978 # supported formats:
2979 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2980 # - if its contents is a number, use it as tag weight,
2981 # - otherwise add a tag with weight 1
2982 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2983 # the same value multiple times increases tag weight
2984 # * `gitweb.ctag' multi-valued repo config variable
2985 sub git_get_project_ctags {
2986 my $project = shift;
2987 my $ctags = {};
2989 $git_dir = "$projectroot/$project";
2990 if (opendir my $dh, "$git_dir/ctags") {
2991 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2992 foreach my $tagfile (@files) {
2993 open my $ct, '<', $tagfile
2994 or next;
2995 my $val = <$ct>;
2996 chomp $val if $val;
2997 close $ct;
2999 (my $ctag = $tagfile) =~ s#.*/##;
3000 if ($val =~ /^\d+$/) {
3001 $ctags->{$ctag} = $val;
3002 } else {
3003 $ctags->{$ctag} = 1;
3006 closedir $dh;
3008 } elsif (open my $fh, '<', "$git_dir/ctags") {
3009 while (my $line = <$fh>) {
3010 chomp $line;
3011 $ctags->{$line}++ if $line;
3013 close $fh;
3015 } else {
3016 my $taglist = config_to_multi(git_get_project_config('ctag'));
3017 foreach my $tag (@$taglist) {
3018 $ctags->{$tag}++;
3022 return $ctags;
3025 # return hash, where keys are content tags ('ctags'),
3026 # and values are sum of weights of given tag in every project
3027 sub git_gather_all_ctags {
3028 my $projects = shift;
3029 my $ctags = {};
3031 foreach my $p (@$projects) {
3032 foreach my $ct (keys %{$p->{'ctags'}}) {
3033 $ctags->{$ct} += $p->{'ctags'}->{$ct};
3037 return $ctags;
3040 sub git_populate_project_tagcloud {
3041 my $ctags = shift;
3043 # First, merge different-cased tags; tags vote on casing
3044 my %ctags_lc;
3045 foreach (keys %$ctags) {
3046 $ctags_lc{lc $_}->{count} += $ctags->{$_};
3047 if (not $ctags_lc{lc $_}->{topcount}
3048 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
3049 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
3050 $ctags_lc{lc $_}->{topname} = $_;
3054 my $cloud;
3055 my $matched = $input_params{'ctag'};
3056 if (eval { require HTML::TagCloud; 1; }) {
3057 $cloud = HTML::TagCloud->new;
3058 foreach my $ctag (sort keys %ctags_lc) {
3059 # Pad the title with spaces so that the cloud looks
3060 # less crammed.
3061 my $title = esc_html($ctags_lc{$ctag}->{topname});
3062 $title =~ s/ /&nbsp;/g;
3063 $title =~ s/^/&nbsp;/g;
3064 $title =~ s/$/&nbsp;/g;
3065 if (defined $matched && $matched eq $ctag) {
3066 $title = qq(<span class="match">$title</span>);
3068 $cloud->add($title, href(project=>undef, ctag=>$ctag),
3069 $ctags_lc{$ctag}->{count});
3071 } else {
3072 $cloud = {};
3073 foreach my $ctag (keys %ctags_lc) {
3074 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3075 if (defined $matched && $matched eq $ctag) {
3076 $title = qq(<span class="match">$title</span>);
3078 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3079 $cloud->{$ctag}{ctag} =
3080 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3083 return $cloud;
3086 sub git_show_project_tagcloud {
3087 my ($cloud, $count) = @_;
3088 if (ref $cloud eq 'HTML::TagCloud') {
3089 return $cloud->html_and_css($count);
3090 } else {
3091 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3092 return
3093 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3094 join (', ', map {
3095 $cloud->{$_}->{'ctag'}
3096 } splice(@tags, 0, $count)) .
3097 '</div>';
3101 sub git_get_project_url_list {
3102 my $path = shift;
3104 $git_dir = "$projectroot/$path";
3105 open my $fd, '<', "$git_dir/cloneurl"
3106 or return wantarray ?
3107 @{ config_to_multi(git_get_project_config('url')) } :
3108 config_to_multi(git_get_project_config('url'));
3109 my @git_project_url_list = map { chomp; $_ } <$fd>;
3110 close $fd;
3112 return wantarray ? @git_project_url_list : \@git_project_url_list;
3115 sub git_get_projects_list {
3116 my $filter = shift || '';
3117 my $paranoid = shift;
3118 my @list;
3120 if (-d $projects_list) {
3121 # search in directory
3122 my $dir = $projects_list;
3123 # remove the trailing "/"
3124 $dir =~ s!/+$!!;
3125 my $pfxlen = length("$dir");
3126 my $pfxdepth = ($dir =~ tr!/!!);
3127 # when filtering, search only given subdirectory
3128 if ($filter && !$paranoid) {
3129 $dir .= "/$filter";
3130 $dir =~ s!/+$!!;
3133 File::Find::find({
3134 follow_fast => 1, # follow symbolic links
3135 follow_skip => 2, # ignore duplicates
3136 dangling_symlinks => 0, # ignore dangling symlinks, silently
3137 wanted => sub {
3138 # global variables
3139 our $project_maxdepth;
3140 our $projectroot;
3141 # skip project-list toplevel, if we get it.
3142 return if (m!^[/.]$!);
3143 # only directories can be git repositories
3144 return unless (-d $_);
3145 # don't traverse too deep (Find is super slow on os x)
3146 # $project_maxdepth excludes depth of $projectroot
3147 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3148 $File::Find::prune = 1;
3149 return;
3152 my $path = substr($File::Find::name, $pfxlen + 1);
3153 # paranoidly only filter here
3154 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3155 next;
3157 # we check related file in $projectroot
3158 if (check_export_ok("$projectroot/$path")) {
3159 push @list, { path => $path };
3160 $File::Find::prune = 1;
3163 }, "$dir");
3165 } elsif (-f $projects_list) {
3166 # read from file(url-encoded):
3167 # 'git%2Fgit.git Linus+Torvalds'
3168 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3169 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3170 open my $fd, '<', $projects_list or return;
3171 PROJECT:
3172 while (my $line = <$fd>) {
3173 chomp $line;
3174 my ($path, $owner) = split ' ', $line;
3175 $path = unescape($path);
3176 $owner = unescape($owner);
3177 if (!defined $path) {
3178 next;
3180 # if $filter is rpovided, check if $path begins with $filter
3181 if ($filter && $path !~ m!^\Q$filter\E/!) {
3182 next;
3184 if (check_export_ok("$projectroot/$path")) {
3185 my $pr = {
3186 path => $path
3188 if ($owner) {
3189 $pr->{'owner'} = to_utf8($owner);
3191 push @list, $pr;
3194 close $fd;
3196 return @list;
3199 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3200 # as side effects it sets 'forks' field to list of forks for forked projects
3201 sub filter_forks_from_projects_list {
3202 my $projects = shift;
3204 my %trie; # prefix tree of directories (path components)
3205 # generate trie out of those directories that might contain forks
3206 foreach my $pr (@$projects) {
3207 my $path = $pr->{'path'};
3208 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3209 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3210 next unless ($path); # skip '.git' repository: tests, git-instaweb
3211 next unless (-d "$projectroot/$path"); # containing directory exists
3212 $pr->{'forks'} = []; # there can be 0 or more forks of project
3214 # add to trie
3215 my @dirs = split('/', $path);
3216 # walk the trie, until either runs out of components or out of trie
3217 my $ref = \%trie;
3218 while (scalar @dirs &&
3219 exists($ref->{$dirs[0]})) {
3220 $ref = $ref->{shift @dirs};
3222 # create rest of trie structure from rest of components
3223 foreach my $dir (@dirs) {
3224 $ref = $ref->{$dir} = {};
3226 # create end marker, store $pr as a data
3227 $ref->{''} = $pr if (!exists $ref->{''});
3230 # filter out forks, by finding shortest prefix match for paths
3231 my @filtered;
3232 PROJECT:
3233 foreach my $pr (@$projects) {
3234 # trie lookup
3235 my $ref = \%trie;
3236 DIR:
3237 foreach my $dir (split('/', $pr->{'path'})) {
3238 if (exists $ref->{''}) {
3239 # found [shortest] prefix, is a fork - skip it
3240 push @{$ref->{''}{'forks'}}, $pr;
3241 next PROJECT;
3243 if (!exists $ref->{$dir}) {
3244 # not in trie, cannot have prefix, not a fork
3245 push @filtered, $pr;
3246 next PROJECT;
3248 # If the dir is there, we just walk one step down the trie.
3249 $ref = $ref->{$dir};
3251 # we ran out of trie
3252 # (shouldn't happen: it's either no match, or end marker)
3253 push @filtered, $pr;
3256 return @filtered;
3259 # note: fill_project_list_info must be run first,
3260 # for 'descr_long' and 'ctags' to be filled
3261 sub search_projects_list {
3262 my ($projlist, %opts) = @_;
3263 my $tagfilter = $opts{'tagfilter'};
3264 my $search_re = $opts{'search_regexp'};
3266 return @$projlist
3267 unless ($tagfilter || $search_re);
3269 # searching projects require filling to be run before it;
3270 fill_project_list_info($projlist,
3271 $tagfilter ? 'ctags' : (),
3272 $search_re ? ('path', 'descr') : ());
3273 my @projects;
3274 PROJECT:
3275 foreach my $pr (@$projlist) {
3277 if ($tagfilter) {
3278 next unless ref($pr->{'ctags'}) eq 'HASH';
3279 next unless
3280 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3283 if ($search_re) {
3284 next unless
3285 $pr->{'path'} =~ /$search_re/ ||
3286 $pr->{'descr_long'} =~ /$search_re/;
3289 push @projects, $pr;
3292 return @projects;
3295 our $gitweb_project_owner = undef;
3296 sub git_get_project_list_from_file {
3298 return if (defined $gitweb_project_owner);
3300 $gitweb_project_owner = {};
3301 # read from file (url-encoded):
3302 # 'git%2Fgit.git Linus+Torvalds'
3303 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3304 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3305 if (-f $projects_list) {
3306 open(my $fd, '<', $projects_list);
3307 while (my $line = <$fd>) {
3308 chomp $line;
3309 my ($pr, $ow) = split ' ', $line;
3310 $pr = unescape($pr);
3311 $ow = unescape($ow);
3312 $gitweb_project_owner->{$pr} = to_utf8($ow);
3314 close $fd;
3318 sub git_get_project_owner {
3319 my $project = shift;
3320 my $owner;
3322 return undef unless $project;
3323 $git_dir = "$projectroot/$project";
3325 if (!defined $gitweb_project_owner) {
3326 git_get_project_list_from_file();
3329 if (exists $gitweb_project_owner->{$project}) {
3330 $owner = $gitweb_project_owner->{$project};
3332 if (!defined $owner){
3333 $owner = git_get_project_config('owner');
3335 if (!defined $owner) {
3336 $owner = get_file_owner("$git_dir");
3339 return $owner;
3342 sub git_get_last_activity {
3343 my ($path) = @_;
3344 my $fd;
3346 $git_dir = "$projectroot/$path";
3347 open($fd, "-|", git_cmd(), 'for-each-ref',
3348 '--format=%(committer)',
3349 '--sort=-committerdate',
3350 '--count=1',
3351 map { "refs/$_" } get_branch_refs ()) or return;
3352 my $most_recent = <$fd>;
3353 close $fd or return;
3354 if (defined $most_recent &&
3355 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3356 my $timestamp = $1;
3357 my $age = time - $timestamp;
3358 return ($age, age_string($age));
3360 return (undef, undef);
3363 # Implementation note: when a single remote is wanted, we cannot use 'git
3364 # remote show -n' because that command always work (assuming it's a remote URL
3365 # if it's not defined), and we cannot use 'git remote show' because that would
3366 # try to make a network roundtrip. So the only way to find if that particular
3367 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3368 # and when we find what we want.
3369 sub git_get_remotes_list {
3370 my $wanted = shift;
3371 my %remotes = ();
3373 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3374 return unless $fd;
3375 while (my $remote = <$fd>) {
3376 chomp $remote;
3377 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3378 next if $wanted and not $remote eq $wanted;
3379 my ($url, $key) = ($1, $2);
3381 $remotes{$remote} ||= { 'heads' => () };
3382 $remotes{$remote}{$key} = $url;
3384 close $fd or return;
3385 return wantarray ? %remotes : \%remotes;
3388 # Takes a hash of remotes as first parameter and fills it by adding the
3389 # available remote heads for each of the indicated remotes.
3390 sub fill_remote_heads {
3391 my $remotes = shift;
3392 my @heads = map { "remotes/$_" } keys %$remotes;
3393 my @remoteheads = git_get_heads_list(undef, @heads);
3394 foreach my $remote (keys %$remotes) {
3395 $remotes->{$remote}{'heads'} = [ grep {
3396 $_->{'name'} =~ s!^$remote/!!
3397 } @remoteheads ];
3401 sub git_get_references {
3402 my $type = shift || "";
3403 my %refs;
3404 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3405 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3406 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3407 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3408 or return;
3410 while (my $line = <$fd>) {
3411 chomp $line;
3412 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3413 if (defined $refs{$1}) {
3414 push @{$refs{$1}}, $2;
3415 } else {
3416 $refs{$1} = [ $2 ];
3420 close $fd or return;
3421 return \%refs;
3424 sub git_get_rev_name_tags {
3425 my $hash = shift || return undef;
3427 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3428 or return;
3429 my $name_rev = <$fd>;
3430 close $fd;
3432 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3433 return $1;
3434 } else {
3435 # catches also '$hash undefined' output
3436 return undef;
3440 ## ----------------------------------------------------------------------
3441 ## parse to hash functions
3443 sub parse_date {
3444 my $epoch = shift;
3445 my $tz = shift || "-0000";
3447 my %date;
3448 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3449 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3450 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3451 $date{'hour'} = $hour;
3452 $date{'minute'} = $min;
3453 $date{'mday'} = $mday;
3454 $date{'day'} = $days[$wday];
3455 $date{'month'} = $months[$mon];
3456 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3457 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3458 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3459 $mday, $months[$mon], $hour ,$min;
3460 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3461 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3463 my ($tz_sign, $tz_hour, $tz_min) =
3464 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3465 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3466 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3467 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3468 $date{'hour_local'} = $hour;
3469 $date{'minute_local'} = $min;
3470 $date{'tz_local'} = $tz;
3471 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3472 1900+$year, $mon+1, $mday,
3473 $hour, $min, $sec, $tz);
3474 return %date;
3477 sub parse_tag {
3478 my $tag_id = shift;
3479 my %tag;
3480 my @comment;
3482 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3483 $tag{'id'} = $tag_id;
3484 while (my $line = <$fd>) {
3485 chomp $line;
3486 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3487 $tag{'object'} = $1;
3488 } elsif ($line =~ m/^type (.+)$/) {
3489 $tag{'type'} = $1;
3490 } elsif ($line =~ m/^tag (.+)$/) {
3491 $tag{'name'} = $1;
3492 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3493 $tag{'author'} = $1;
3494 $tag{'author_epoch'} = $2;
3495 $tag{'author_tz'} = $3;
3496 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3497 $tag{'author_name'} = $1;
3498 $tag{'author_email'} = $2;
3499 } else {
3500 $tag{'author_name'} = $tag{'author'};
3502 } elsif ($line =~ m/--BEGIN/) {
3503 push @comment, $line;
3504 last;
3505 } elsif ($line eq "") {
3506 last;
3509 push @comment, <$fd>;
3510 $tag{'comment'} = \@comment;
3511 close $fd or return;
3512 if (!defined $tag{'name'}) {
3513 return
3515 return %tag
3518 sub parse_commit_text {
3519 my ($commit_text, $withparents) = @_;
3520 my @commit_lines = split '\n', $commit_text;
3521 my %co;
3523 pop @commit_lines; # Remove '\0'
3525 if (! @commit_lines) {
3526 return;
3529 my $header = shift @commit_lines;
3530 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3531 return;
3533 ($co{'id'}, my @parents) = split ' ', $header;
3534 while (my $line = shift @commit_lines) {
3535 last if $line eq "\n";
3536 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3537 $co{'tree'} = $1;
3538 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3539 push @parents, $1;
3540 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3541 $co{'author'} = to_utf8($1);
3542 $co{'author_epoch'} = $2;
3543 $co{'author_tz'} = $3;
3544 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3545 $co{'author_name'} = $1;
3546 $co{'author_email'} = $2;
3547 } else {
3548 $co{'author_name'} = $co{'author'};
3550 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3551 $co{'committer'} = to_utf8($1);
3552 $co{'committer_epoch'} = $2;
3553 $co{'committer_tz'} = $3;
3554 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3555 $co{'committer_name'} = $1;
3556 $co{'committer_email'} = $2;
3557 } else {
3558 $co{'committer_name'} = $co{'committer'};
3562 if (!defined $co{'tree'}) {
3563 return;
3565 $co{'parents'} = \@parents;
3566 $co{'parent'} = $parents[0];
3568 foreach my $title (@commit_lines) {
3569 $title =~ s/^ //;
3570 if ($title ne "") {
3571 $co{'title'} = chop_str($title, 80, 5);
3572 # remove leading stuff of merges to make the interesting part visible
3573 if (length($title) > 50) {
3574 $title =~ s/^Automatic //;
3575 $title =~ s/^merge (of|with) /Merge ... /i;
3576 if (length($title) > 50) {
3577 $title =~ s/(http|rsync):\/\///;
3579 if (length($title) > 50) {
3580 $title =~ s/(master|www|rsync)\.//;
3582 if (length($title) > 50) {
3583 $title =~ s/kernel.org:?//;
3585 if (length($title) > 50) {
3586 $title =~ s/\/pub\/scm//;
3589 $co{'title_short'} = chop_str($title, 50, 5);
3590 last;
3593 if (! defined $co{'title'} || $co{'title'} eq "") {
3594 $co{'title'} = $co{'title_short'} = '(no commit message)';
3596 # remove added spaces
3597 foreach my $line (@commit_lines) {
3598 $line =~ s/^ //;
3600 $co{'comment'} = \@commit_lines;
3602 my $age = time - $co{'committer_epoch'};
3603 $co{'age'} = $age;
3604 $co{'age_string'} = age_string($age);
3605 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3606 if ($age > 60*60*24*7*2) {
3607 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3608 $co{'age_string_age'} = $co{'age_string'};
3609 } else {
3610 $co{'age_string_date'} = $co{'age_string'};
3611 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3613 return %co;
3616 sub parse_commit {
3617 my ($commit_id) = @_;
3618 my %co;
3620 local $/ = "\0";
3622 open my $fd, "-|", git_cmd(), "rev-list",
3623 "--parents",
3624 "--header",
3625 "--max-count=1",
3626 $commit_id,
3627 "--",
3628 or die_error(500, "Open git-rev-list failed");
3629 %co = parse_commit_text(<$fd>, 1);
3630 close $fd;
3632 return %co;
3635 sub parse_commits {
3636 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3637 my @cos;
3639 $maxcount ||= 1;
3640 $skip ||= 0;
3642 local $/ = "\0";
3644 open my $fd, "-|", git_cmd(), "rev-list",
3645 "--header",
3646 @args,
3647 ("--max-count=" . $maxcount),
3648 ("--skip=" . $skip),
3649 @extra_options,
3650 $commit_id,
3651 "--",
3652 ($filename ? ($filename) : ())
3653 or die_error(500, "Open git-rev-list failed");
3654 while (my $line = <$fd>) {
3655 my %co = parse_commit_text($line);
3656 push @cos, \%co;
3658 close $fd;
3660 return wantarray ? @cos : \@cos;
3663 # parse line of git-diff-tree "raw" output
3664 sub parse_difftree_raw_line {
3665 my $line = shift;
3666 my %res;
3668 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3669 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3670 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3671 $res{'from_mode'} = $1;
3672 $res{'to_mode'} = $2;
3673 $res{'from_id'} = $3;
3674 $res{'to_id'} = $4;
3675 $res{'status'} = $5;
3676 $res{'similarity'} = $6;
3677 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3678 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3679 } else {
3680 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3683 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3684 # combined diff (for merge commit)
3685 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3686 $res{'nparents'} = length($1);
3687 $res{'from_mode'} = [ split(' ', $2) ];
3688 $res{'to_mode'} = pop @{$res{'from_mode'}};
3689 $res{'from_id'} = [ split(' ', $3) ];
3690 $res{'to_id'} = pop @{$res{'from_id'}};
3691 $res{'status'} = [ split('', $4) ];
3692 $res{'to_file'} = unquote($5);
3694 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3695 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3696 $res{'commit'} = $1;
3699 return wantarray ? %res : \%res;
3702 # wrapper: return parsed line of git-diff-tree "raw" output
3703 # (the argument might be raw line, or parsed info)
3704 sub parsed_difftree_line {
3705 my $line_or_ref = shift;
3707 if (ref($line_or_ref) eq "HASH") {
3708 # pre-parsed (or generated by hand)
3709 return $line_or_ref;
3710 } else {
3711 return parse_difftree_raw_line($line_or_ref);
3715 # parse line of git-ls-tree output
3716 sub parse_ls_tree_line {
3717 my $line = shift;
3718 my %opts = @_;
3719 my %res;
3721 if ($opts{'-l'}) {
3722 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3723 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3725 $res{'mode'} = $1;
3726 $res{'type'} = $2;
3727 $res{'hash'} = $3;
3728 $res{'size'} = $4;
3729 if ($opts{'-z'}) {
3730 $res{'name'} = $5;
3731 } else {
3732 $res{'name'} = unquote($5);
3734 } else {
3735 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3736 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3738 $res{'mode'} = $1;
3739 $res{'type'} = $2;
3740 $res{'hash'} = $3;
3741 if ($opts{'-z'}) {
3742 $res{'name'} = $4;
3743 } else {
3744 $res{'name'} = unquote($4);
3748 return wantarray ? %res : \%res;
3751 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3752 sub parse_from_to_diffinfo {
3753 my ($diffinfo, $from, $to, @parents) = @_;
3755 if ($diffinfo->{'nparents'}) {
3756 # combined diff
3757 $from->{'file'} = [];
3758 $from->{'href'} = [];
3759 fill_from_file_info($diffinfo, @parents)
3760 unless exists $diffinfo->{'from_file'};
3761 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3762 $from->{'file'}[$i] =
3763 defined $diffinfo->{'from_file'}[$i] ?
3764 $diffinfo->{'from_file'}[$i] :
3765 $diffinfo->{'to_file'};
3766 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3767 $from->{'href'}[$i] = href(action=>"blob",
3768 hash_base=>$parents[$i],
3769 hash=>$diffinfo->{'from_id'}[$i],
3770 file_name=>$from->{'file'}[$i]);
3771 } else {
3772 $from->{'href'}[$i] = undef;
3775 } else {
3776 # ordinary (not combined) diff
3777 $from->{'file'} = $diffinfo->{'from_file'};
3778 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3779 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3780 hash=>$diffinfo->{'from_id'},
3781 file_name=>$from->{'file'});
3782 } else {
3783 delete $from->{'href'};
3787 $to->{'file'} = $diffinfo->{'to_file'};
3788 if (!is_deleted($diffinfo)) { # file exists in result
3789 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3790 hash=>$diffinfo->{'to_id'},
3791 file_name=>$to->{'file'});
3792 } else {
3793 delete $to->{'href'};
3797 ## ......................................................................
3798 ## parse to array of hashes functions
3800 sub git_get_heads_list {
3801 my ($limit, @classes) = @_;
3802 @classes = get_branch_refs() unless @classes;
3803 my @patterns = map { "refs/$_" } @classes;
3804 my @headslist;
3806 open my $fd, '-|', git_cmd(), 'for-each-ref',
3807 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3808 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3809 @patterns
3810 or return;
3811 while (my $line = <$fd>) {
3812 my %ref_item;
3814 chomp $line;
3815 my ($refinfo, $committerinfo) = split(/\0/, $line);
3816 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3817 my ($committer, $epoch, $tz) =
3818 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3819 $ref_item{'fullname'} = $name;
3820 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3821 $name =~ s!^refs/($strip_refs|remotes)/!!;
3822 $ref_item{'name'} = $name;
3823 # for refs neither in 'heads' nor 'remotes' we want to
3824 # show their ref dir
3825 my $ref_dir = (defined $1) ? $1 : '';
3826 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3827 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3830 $ref_item{'id'} = $hash;
3831 $ref_item{'title'} = $title || '(no commit message)';
3832 $ref_item{'epoch'} = $epoch;
3833 if ($epoch) {
3834 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3835 } else {
3836 $ref_item{'age'} = "unknown";
3839 push @headslist, \%ref_item;
3841 close $fd;
3843 return wantarray ? @headslist : \@headslist;
3846 sub git_get_tags_list {
3847 my $limit = shift;
3848 my @tagslist;
3850 open my $fd, '-|', git_cmd(), 'for-each-ref',
3851 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3852 '--format=%(objectname) %(objecttype) %(refname) '.
3853 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3854 'refs/tags'
3855 or return;
3856 while (my $line = <$fd>) {
3857 my %ref_item;
3859 chomp $line;
3860 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3861 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3862 my ($creator, $epoch, $tz) =
3863 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3864 $ref_item{'fullname'} = $name;
3865 $name =~ s!^refs/tags/!!;
3867 $ref_item{'type'} = $type;
3868 $ref_item{'id'} = $id;
3869 $ref_item{'name'} = $name;
3870 if ($type eq "tag") {
3871 $ref_item{'subject'} = $title;
3872 $ref_item{'reftype'} = $reftype;
3873 $ref_item{'refid'} = $refid;
3874 } else {
3875 $ref_item{'reftype'} = $type;
3876 $ref_item{'refid'} = $id;
3879 if ($type eq "tag" || $type eq "commit") {
3880 $ref_item{'epoch'} = $epoch;
3881 if ($epoch) {
3882 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3883 } else {
3884 $ref_item{'age'} = "unknown";
3888 push @tagslist, \%ref_item;
3890 close $fd;
3892 return wantarray ? @tagslist : \@tagslist;
3895 ## ----------------------------------------------------------------------
3896 ## filesystem-related functions
3898 sub get_file_owner {
3899 my $path = shift;
3901 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3902 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3903 if (!defined $gcos) {
3904 return undef;
3906 my $owner = $gcos;
3907 $owner =~ s/[,;].*$//;
3908 return to_utf8($owner);
3911 # assume that file exists
3912 sub insert_file {
3913 my $filename = shift;
3915 open my $fd, '<', $filename;
3916 print map { to_utf8($_) } <$fd>;
3917 close $fd;
3920 ## ......................................................................
3921 ## mimetype related functions
3923 sub mimetype_guess_file {
3924 my $filename = shift;
3925 my $mimemap = shift;
3926 -r $mimemap or return undef;
3928 my %mimemap;
3929 open(my $mh, '<', $mimemap) or return undef;
3930 while (<$mh>) {
3931 next if m/^#/; # skip comments
3932 my ($mimetype, @exts) = split(/\s+/);
3933 foreach my $ext (@exts) {
3934 $mimemap{$ext} = $mimetype;
3937 close($mh);
3939 $filename =~ /\.([^.]*)$/;
3940 return $mimemap{$1};
3943 sub mimetype_guess {
3944 my $filename = shift;
3945 my $mime;
3946 $filename =~ /\./ or return undef;
3948 if ($mimetypes_file) {
3949 my $file = $mimetypes_file;
3950 if ($file !~ m!^/!) { # if it is relative path
3951 # it is relative to project
3952 $file = "$projectroot/$project/$file";
3954 $mime = mimetype_guess_file($filename, $file);
3956 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3957 return $mime;
3960 sub blob_mimetype {
3961 my $fd = shift;
3962 my $filename = shift;
3964 if ($filename) {
3965 my $mime = mimetype_guess($filename);
3966 $mime and return $mime;
3969 # just in case
3970 return $default_blob_plain_mimetype unless $fd;
3972 if (-T $fd) {
3973 return 'text/plain';
3974 } elsif (! $filename) {
3975 return 'application/octet-stream';
3976 } elsif ($filename =~ m/\.png$/i) {
3977 return 'image/png';
3978 } elsif ($filename =~ m/\.gif$/i) {
3979 return 'image/gif';
3980 } elsif ($filename =~ m/\.jpe?g$/i) {
3981 return 'image/jpeg';
3982 } else {
3983 return 'application/octet-stream';
3987 sub blob_contenttype {
3988 my ($fd, $file_name, $type) = @_;
3990 $type ||= blob_mimetype($fd, $file_name);
3991 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3992 $type .= "; charset=$default_text_plain_charset";
3995 return $type;
3998 # guess file syntax for syntax highlighting; return undef if no highlighting
3999 # the name of syntax can (in the future) depend on syntax highlighter used
4000 sub guess_file_syntax {
4001 my ($highlight, $mimetype, $file_name) = @_;
4002 return undef unless ($highlight && defined $file_name);
4003 my $basename = basename($file_name, '.in');
4004 return $highlight_basename{$basename}
4005 if exists $highlight_basename{$basename};
4007 $basename =~ /\.([^.]*)$/;
4008 my $ext = $1 or return undef;
4009 return $highlight_ext{$ext}
4010 if exists $highlight_ext{$ext};
4012 return undef;
4015 # run highlighter and return FD of its output,
4016 # or return original FD if no highlighting
4017 sub run_highlighter {
4018 my ($fd, $highlight, $syntax) = @_;
4019 return $fd unless ($highlight && defined $syntax);
4021 close $fd;
4022 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
4023 quote_command($highlight_bin).
4024 " --replace-tabs=8 --fragment --syntax $syntax |"
4025 or die_error(500, "Couldn't open file or run syntax highlighter");
4026 return $fd;
4029 ## ======================================================================
4030 ## functions printing HTML: header, footer, error page
4032 sub get_page_title {
4033 my $title = to_utf8($site_name);
4035 unless (defined $project) {
4036 if (defined $project_filter) {
4037 $title .= " - projects in '" . esc_path($project_filter) . "'";
4039 return $title;
4041 $title .= " - " . to_utf8($project);
4043 return $title unless (defined $action);
4044 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
4046 return $title unless (defined $file_name);
4047 $title .= " - " . esc_path($file_name);
4048 if ($action eq "tree" && $file_name !~ m|/$|) {
4049 $title .= "/";
4052 return $title;
4055 sub get_content_type_html {
4056 # require explicit support from the UA if we are to send the page as
4057 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4058 # we have to do this because MSIE sometimes globs '*/*', pretending to
4059 # support xhtml+xml but choking when it gets what it asked for.
4060 if (defined $cgi->http('HTTP_ACCEPT') &&
4061 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4062 $cgi->Accept('application/xhtml+xml') != 0) {
4063 return 'application/xhtml+xml';
4064 } else {
4065 return 'text/html';
4069 sub print_feed_meta {
4070 if (defined $project) {
4071 my %href_params = get_feed_info();
4072 if (!exists $href_params{'-title'}) {
4073 $href_params{'-title'} = 'log';
4076 foreach my $format (qw(RSS Atom)) {
4077 my $type = lc($format);
4078 my %link_attr = (
4079 '-rel' => 'alternate',
4080 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4081 '-type' => "application/$type+xml"
4084 $href_params{'extra_options'} = undef;
4085 $href_params{'action'} = $type;
4086 $link_attr{'-href'} = href(%href_params);
4087 print "<link ".
4088 "rel=\"$link_attr{'-rel'}\" ".
4089 "title=\"$link_attr{'-title'}\" ".
4090 "href=\"$link_attr{'-href'}\" ".
4091 "type=\"$link_attr{'-type'}\" ".
4092 "/>\n";
4094 $href_params{'extra_options'} = '--no-merges';
4095 $link_attr{'-href'} = href(%href_params);
4096 $link_attr{'-title'} .= ' (no merges)';
4097 print "<link ".
4098 "rel=\"$link_attr{'-rel'}\" ".
4099 "title=\"$link_attr{'-title'}\" ".
4100 "href=\"$link_attr{'-href'}\" ".
4101 "type=\"$link_attr{'-type'}\" ".
4102 "/>\n";
4105 } else {
4106 printf('<link rel="alternate" title="%s projects list" '.
4107 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4108 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4109 printf('<link rel="alternate" title="%s projects feeds" '.
4110 'href="%s" type="text/x-opml" />'."\n",
4111 esc_attr($site_name), href(project=>undef, action=>"opml"));
4115 sub print_header_links {
4116 my $status = shift;
4118 # print out each stylesheet that exist, providing backwards capability
4119 # for those people who defined $stylesheet in a config file
4120 if (defined $stylesheet) {
4121 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4122 } else {
4123 foreach my $stylesheet (@stylesheets) {
4124 next unless $stylesheet;
4125 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4128 print_feed_meta()
4129 if ($status eq '200 OK');
4130 if (defined $favicon) {
4131 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4135 sub print_nav_breadcrumbs_path {
4136 my $dirprefix = undef;
4137 while (my $part = shift) {
4138 $dirprefix .= "/" if defined $dirprefix;
4139 $dirprefix .= $part;
4140 print $cgi->a({-href => href(project => undef,
4141 project_filter => $dirprefix,
4142 action => "project_list")},
4143 esc_html($part)) . " / ";
4147 sub print_nav_breadcrumbs {
4148 my %opts = @_;
4150 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4151 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4153 if (defined $project) {
4154 my @dirname = split '/', $project;
4155 my $projectbasename = pop @dirname;
4156 print_nav_breadcrumbs_path(@dirname);
4157 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4158 if (defined $action) {
4159 my $action_print = $action ;
4160 if (defined $opts{-action_extra}) {
4161 $action_print = $cgi->a({-href => href(action=>$action)},
4162 $action);
4164 print " / $action_print";
4166 if (defined $opts{-action_extra}) {
4167 print " / $opts{-action_extra}";
4169 print "\n";
4170 } elsif (defined $project_filter) {
4171 print_nav_breadcrumbs_path(split '/', $project_filter);
4175 sub print_search_form {
4176 if (!defined $searchtext) {
4177 $searchtext = "";
4179 my $search_hash;
4180 if (defined $hash_base) {
4181 $search_hash = $hash_base;
4182 } elsif (defined $hash) {
4183 $search_hash = $hash;
4184 } else {
4185 $search_hash = "HEAD";
4187 my $action = $my_uri;
4188 my $use_pathinfo = gitweb_check_feature('pathinfo');
4189 if ($use_pathinfo) {
4190 $action .= "/".esc_url($project);
4192 print $cgi->start_form(-method => "get", -action => $action) .
4193 "<div class=\"search\">\n" .
4194 (!$use_pathinfo &&
4195 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4196 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4197 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4198 $cgi->popup_menu(-name => 'st', -default => 'commit',
4199 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4200 " " . $cgi->a({-href => href(action=>"search_help"),
4201 -title => "search help" }, "?") . " search:\n",
4202 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4203 "<span title=\"Extended regular expression\">" .
4204 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4205 -checked => $search_use_regexp) .
4206 "</span>" .
4207 "</div>" .
4208 $cgi->end_form() . "\n";
4211 sub git_header_html {
4212 my $status = shift || "200 OK";
4213 my $expires = shift;
4214 my %opts = @_;
4216 my $title = get_page_title();
4217 my $content_type = get_content_type_html();
4218 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4219 -status=> $status, -expires => $expires)
4220 unless ($opts{'-no_http_header'});
4221 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4222 print <<EOF;
4223 <?xml version="1.0" encoding="utf-8"?>
4224 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4225 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4226 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4227 <!-- git core binaries version $git_version -->
4228 <head>
4229 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4230 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4231 <meta name="robots" content="index, nofollow"/>
4232 <title>$title</title>
4234 # the stylesheet, favicon etc urls won't work correctly with path_info
4235 # unless we set the appropriate base URL
4236 if ($ENV{'PATH_INFO'}) {
4237 print "<base href=\"".esc_url($base_url)."\" />\n";
4239 print_header_links($status);
4241 if (defined $site_html_head_string) {
4242 print to_utf8($site_html_head_string);
4245 print "</head>\n" .
4246 "<body>\n";
4248 if (defined $site_header && -f $site_header) {
4249 insert_file($site_header);
4252 print "<div class=\"page_header\">\n";
4253 if (defined $logo) {
4254 print $cgi->a({-href => esc_url($logo_url),
4255 -title => $logo_label},
4256 $cgi->img({-src => esc_url($logo),
4257 -width => 72, -height => 27,
4258 -alt => "git",
4259 -class => "logo"}));
4261 print_nav_breadcrumbs(%opts);
4262 print "</div>\n";
4264 my $have_search = gitweb_check_feature('search');
4265 if (defined $project && $have_search) {
4266 print_search_form();
4270 sub git_footer_html {
4271 my $feed_class = 'rss_logo';
4273 print "<div class=\"page_footer\">\n";
4274 if (defined $project) {
4275 my $descr = git_get_project_description($project);
4276 if (defined $descr) {
4277 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4280 my %href_params = get_feed_info();
4281 if (!%href_params) {
4282 $feed_class .= ' generic';
4284 $href_params{'-title'} ||= 'log';
4286 foreach my $format (qw(RSS Atom)) {
4287 $href_params{'action'} = lc($format);
4288 print $cgi->a({-href => href(%href_params),
4289 -title => "$href_params{'-title'} $format feed",
4290 -class => $feed_class}, $format)."\n";
4293 } else {
4294 print $cgi->a({-href => href(project=>undef, action=>"opml",
4295 project_filter => $project_filter),
4296 -class => $feed_class}, "OPML") . " ";
4297 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4298 project_filter => $project_filter),
4299 -class => $feed_class}, "TXT") . "\n";
4301 print "</div>\n"; # class="page_footer"
4303 if (defined $t0 && gitweb_check_feature('timed')) {
4304 print "<div id=\"generating_info\">\n";
4305 print 'This page took '.
4306 '<span id="generating_time" class="time_span">'.
4307 tv_interval($t0, [ gettimeofday() ]).
4308 ' seconds </span>'.
4309 ' and '.
4310 '<span id="generating_cmd">'.
4311 $number_of_git_cmds.
4312 '</span> git commands '.
4313 " to generate.\n";
4314 print "</div>\n"; # class="page_footer"
4317 if (defined $site_footer && -f $site_footer) {
4318 insert_file($site_footer);
4321 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4322 if (defined $action &&
4323 $action eq 'blame_incremental') {
4324 print qq!<script type="text/javascript">\n!.
4325 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4326 qq! "!. href() .qq!");\n!.
4327 qq!</script>\n!;
4328 } else {
4329 my ($jstimezone, $tz_cookie, $datetime_class) =
4330 gitweb_get_feature('javascript-timezone');
4332 print qq!<script type="text/javascript">\n!.
4333 qq!window.onload = function () {\n!;
4334 if (gitweb_check_feature('javascript-actions')) {
4335 print qq! fixLinks();\n!;
4337 if ($jstimezone && $tz_cookie && $datetime_class) {
4338 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4339 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4341 print qq!};\n!.
4342 qq!</script>\n!;
4345 print "</body>\n" .
4346 "</html>";
4349 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4350 # Example: die_error(404, 'Hash not found')
4351 # By convention, use the following status codes (as defined in RFC 2616):
4352 # 400: Invalid or missing CGI parameters, or
4353 # requested object exists but has wrong type.
4354 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4355 # this server or project.
4356 # 404: Requested object/revision/project doesn't exist.
4357 # 500: The server isn't configured properly, or
4358 # an internal error occurred (e.g. failed assertions caused by bugs), or
4359 # an unknown error occurred (e.g. the git binary died unexpectedly).
4360 # 503: The server is currently unavailable (because it is overloaded,
4361 # or down for maintenance). Generally, this is a temporary state.
4362 sub die_error {
4363 my $status = shift || 500;
4364 my $error = esc_html(shift) || "Internal Server Error";
4365 my $extra = shift;
4366 my %opts = @_;
4368 my %http_responses = (
4369 400 => '400 Bad Request',
4370 403 => '403 Forbidden',
4371 404 => '404 Not Found',
4372 500 => '500 Internal Server Error',
4373 503 => '503 Service Unavailable',
4375 git_header_html($http_responses{$status}, undef, %opts);
4376 print <<EOF;
4377 <div class="page_body">
4378 <br /><br />
4379 $status - $error
4380 <br />
4382 if (defined $extra) {
4383 print "<hr />\n" .
4384 "$extra\n";
4386 print "</div>\n";
4388 git_footer_html();
4389 goto DONE_GITWEB
4390 unless ($opts{'-error_handler'});
4393 ## ----------------------------------------------------------------------
4394 ## functions printing or outputting HTML: navigation
4396 sub git_print_page_nav {
4397 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4398 $extra = '' if !defined $extra; # pager or formats
4400 my @navs = qw(summary shortlog log commit commitdiff tree);
4401 if ($suppress) {
4402 @navs = grep { $_ ne $suppress } @navs;
4405 my %arg = map { $_ => {action=>$_} } @navs;
4406 if (defined $head) {
4407 for (qw(commit commitdiff)) {
4408 $arg{$_}{'hash'} = $head;
4410 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4411 for (qw(shortlog log)) {
4412 $arg{$_}{'hash'} = $head;
4417 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4418 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4420 my @actions = gitweb_get_feature('actions');
4421 my %repl = (
4422 '%' => '%',
4423 'n' => $project, # project name
4424 'f' => $git_dir, # project path within filesystem
4425 'h' => $treehead || '', # current hash ('h' parameter)
4426 'b' => $treebase || '', # hash base ('hb' parameter)
4428 while (@actions) {
4429 my ($label, $link, $pos) = splice(@actions,0,3);
4430 # insert
4431 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4432 # munch munch
4433 $link =~ s/%([%nfhb])/$repl{$1}/g;
4434 $arg{$label}{'_href'} = $link;
4437 print "<div class=\"page_nav\">\n" .
4438 (join " | ",
4439 map { $_ eq $current ?
4440 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4441 } @navs);
4442 print "<br/>\n$extra<br/>\n" .
4443 "</div>\n";
4446 # returns a submenu for the nagivation of the refs views (tags, heads,
4447 # remotes) with the current view disabled and the remotes view only
4448 # available if the feature is enabled
4449 sub format_ref_views {
4450 my ($current) = @_;
4451 my @ref_views = qw{tags heads};
4452 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4453 return join " | ", map {
4454 $_ eq $current ? $_ :
4455 $cgi->a({-href => href(action=>$_)}, $_)
4456 } @ref_views
4459 sub format_paging_nav {
4460 my ($action, $page, $has_next_link) = @_;
4461 my $paging_nav;
4464 if ($page > 0) {
4465 $paging_nav .=
4466 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4467 " &sdot; " .
4468 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4469 -accesskey => "p", -title => "Alt-p"}, "prev");
4470 } else {
4471 $paging_nav .= "first &sdot; prev";
4474 if ($has_next_link) {
4475 $paging_nav .= " &sdot; " .
4476 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4477 -accesskey => "n", -title => "Alt-n"}, "next");
4478 } else {
4479 $paging_nav .= " &sdot; next";
4482 return $paging_nav;
4485 ## ......................................................................
4486 ## functions printing or outputting HTML: div
4488 sub git_print_header_div {
4489 my ($action, $title, $hash, $hash_base) = @_;
4490 my %args = ();
4492 $args{'action'} = $action;
4493 $args{'hash'} = $hash if $hash;
4494 $args{'hash_base'} = $hash_base if $hash_base;
4496 print "<div class=\"header\">\n" .
4497 $cgi->a({-href => href(%args), -class => "title"},
4498 $title ? $title : $action) .
4499 "\n</div>\n";
4502 sub format_repo_url {
4503 my ($name, $url) = @_;
4504 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4507 # Group output by placing it in a DIV element and adding a header.
4508 # Options for start_div() can be provided by passing a hash reference as the
4509 # first parameter to the function.
4510 # Options to git_print_header_div() can be provided by passing an array
4511 # reference. This must follow the options to start_div if they are present.
4512 # The content can be a scalar, which is output as-is, a scalar reference, which
4513 # is output after html escaping, an IO handle passed either as *handle or
4514 # *handle{IO}, or a function reference. In the latter case all following
4515 # parameters will be taken as argument to the content function call.
4516 sub git_print_section {
4517 my ($div_args, $header_args, $content);
4518 my $arg = shift;
4519 if (ref($arg) eq 'HASH') {
4520 $div_args = $arg;
4521 $arg = shift;
4523 if (ref($arg) eq 'ARRAY') {
4524 $header_args = $arg;
4525 $arg = shift;
4527 $content = $arg;
4529 print $cgi->start_div($div_args);
4530 git_print_header_div(@$header_args);
4532 if (ref($content) eq 'CODE') {
4533 $content->(@_);
4534 } elsif (ref($content) eq 'SCALAR') {
4535 print esc_html($$content);
4536 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4537 print <$content>;
4538 } elsif (!ref($content) && defined($content)) {
4539 print $content;
4542 print $cgi->end_div;
4545 sub format_timestamp_html {
4546 my $date = shift;
4547 my $strtime = $date->{'rfc2822'};
4549 my (undef, undef, $datetime_class) =
4550 gitweb_get_feature('javascript-timezone');
4551 if ($datetime_class) {
4552 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4555 my $localtime_format = '(%02d:%02d %s)';
4556 if ($date->{'hour_local'} < 6) {
4557 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4559 $strtime .= ' ' .
4560 sprintf($localtime_format,
4561 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4563 return $strtime;
4566 # Outputs the author name and date in long form
4567 sub git_print_authorship {
4568 my $co = shift;
4569 my %opts = @_;
4570 my $tag = $opts{-tag} || 'div';
4571 my $author = $co->{'author_name'};
4573 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4574 print "<$tag class=\"author_date\">" .
4575 format_search_author($author, "author", esc_html($author)) .
4576 " [".format_timestamp_html(\%ad)."]".
4577 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4578 "</$tag>\n";
4581 # Outputs table rows containing the full author or committer information,
4582 # in the format expected for 'commit' view (& similar).
4583 # Parameters are a commit hash reference, followed by the list of people
4584 # to output information for. If the list is empty it defaults to both
4585 # author and committer.
4586 sub git_print_authorship_rows {
4587 my $co = shift;
4588 # too bad we can't use @people = @_ || ('author', 'committer')
4589 my @people = @_;
4590 @people = ('author', 'committer') unless @people;
4591 foreach my $who (@people) {
4592 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4593 print "<tr><td>$who</td><td>" .
4594 format_search_author($co->{"${who}_name"}, $who,
4595 esc_html($co->{"${who}_name"})) . " " .
4596 format_search_author($co->{"${who}_email"}, $who,
4597 esc_html("<" . $co->{"${who}_email"} . ">")) .
4598 "</td><td rowspan=\"2\">" .
4599 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4600 "</td></tr>\n" .
4601 "<tr>" .
4602 "<td></td><td>" .
4603 format_timestamp_html(\%wd) .
4604 "</td>" .
4605 "</tr>\n";
4609 sub git_print_page_path {
4610 my $name = shift;
4611 my $type = shift;
4612 my $hb = shift;
4615 print "<div class=\"page_path\">";
4616 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4617 -title => 'tree root'}, to_utf8("[$project]"));
4618 print " / ";
4619 if (defined $name) {
4620 my @dirname = split '/', $name;
4621 my $basename = pop @dirname;
4622 my $fullname = '';
4624 foreach my $dir (@dirname) {
4625 $fullname .= ($fullname ? '/' : '') . $dir;
4626 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4627 hash_base=>$hb),
4628 -title => $fullname}, esc_path($dir));
4629 print " / ";
4631 if (defined $type && $type eq 'blob') {
4632 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4633 hash_base=>$hb),
4634 -title => $name}, esc_path($basename));
4635 } elsif (defined $type && $type eq 'tree') {
4636 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4637 hash_base=>$hb),
4638 -title => $name}, esc_path($basename));
4639 print " / ";
4640 } else {
4641 print esc_path($basename);
4644 print "<br/></div>\n";
4647 sub git_print_log {
4648 my $log = shift;
4649 my %opts = @_;
4651 if ($opts{'-remove_title'}) {
4652 # remove title, i.e. first line of log
4653 shift @$log;
4655 # remove leading empty lines
4656 while (defined $log->[0] && $log->[0] eq "") {
4657 shift @$log;
4660 # print log
4661 my $skip_blank_line = 0;
4662 foreach my $line (@$log) {
4663 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4664 if (! $opts{'-remove_signoff'}) {
4665 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4666 $skip_blank_line = 1;
4668 next;
4671 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4672 if (! $opts{'-remove_signoff'}) {
4673 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4674 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4675 "</span><br/>\n";
4676 $skip_blank_line = 1;
4678 next;
4681 # print only one empty line
4682 # do not print empty line after signoff
4683 if ($line eq "") {
4684 next if ($skip_blank_line);
4685 $skip_blank_line = 1;
4686 } else {
4687 $skip_blank_line = 0;
4690 print format_log_line_html($line) . "<br/>\n";
4693 if ($opts{'-final_empty_line'}) {
4694 # end with single empty line
4695 print "<br/>\n" unless $skip_blank_line;
4699 # return link target (what link points to)
4700 sub git_get_link_target {
4701 my $hash = shift;
4702 my $link_target;
4704 # read link
4705 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4706 or return;
4708 local $/ = undef;
4709 $link_target = <$fd>;
4711 close $fd
4712 or return;
4714 return $link_target;
4717 # given link target, and the directory (basedir) the link is in,
4718 # return target of link relative to top directory (top tree);
4719 # return undef if it is not possible (including absolute links).
4720 sub normalize_link_target {
4721 my ($link_target, $basedir) = @_;
4723 # absolute symlinks (beginning with '/') cannot be normalized
4724 return if (substr($link_target, 0, 1) eq '/');
4726 # normalize link target to path from top (root) tree (dir)
4727 my $path;
4728 if ($basedir) {
4729 $path = $basedir . '/' . $link_target;
4730 } else {
4731 # we are in top (root) tree (dir)
4732 $path = $link_target;
4735 # remove //, /./, and /../
4736 my @path_parts;
4737 foreach my $part (split('/', $path)) {
4738 # discard '.' and ''
4739 next if (!$part || $part eq '.');
4740 # handle '..'
4741 if ($part eq '..') {
4742 if (@path_parts) {
4743 pop @path_parts;
4744 } else {
4745 # link leads outside repository (outside top dir)
4746 return;
4748 } else {
4749 push @path_parts, $part;
4752 $path = join('/', @path_parts);
4754 return $path;
4757 # print tree entry (row of git_tree), but without encompassing <tr> element
4758 sub git_print_tree_entry {
4759 my ($t, $basedir, $hash_base, $have_blame) = @_;
4761 my %base_key = ();
4762 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4764 # The format of a table row is: mode list link. Where mode is
4765 # the mode of the entry, list is the name of the entry, an href,
4766 # and link is the action links of the entry.
4768 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4769 if (exists $t->{'size'}) {
4770 print "<td class=\"size\">$t->{'size'}</td>\n";
4772 if ($t->{'type'} eq "blob") {
4773 print "<td class=\"list\">" .
4774 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4775 file_name=>"$basedir$t->{'name'}", %base_key),
4776 -class => "list"}, esc_path($t->{'name'}));
4777 if (S_ISLNK(oct $t->{'mode'})) {
4778 my $link_target = git_get_link_target($t->{'hash'});
4779 if ($link_target) {
4780 my $norm_target = normalize_link_target($link_target, $basedir);
4781 if (defined $norm_target) {
4782 print " -> " .
4783 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4784 file_name=>$norm_target),
4785 -title => $norm_target}, esc_path($link_target));
4786 } else {
4787 print " -> " . esc_path($link_target);
4791 print "</td>\n";
4792 print "<td class=\"link\">";
4793 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4794 file_name=>"$basedir$t->{'name'}", %base_key)},
4795 "blob");
4796 if ($have_blame) {
4797 print " | " .
4798 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4799 file_name=>"$basedir$t->{'name'}", %base_key)},
4800 "blame");
4802 if (defined $hash_base) {
4803 print " | " .
4804 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4805 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4806 "history");
4808 print " | " .
4809 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4810 file_name=>"$basedir$t->{'name'}")},
4811 "raw");
4812 print "</td>\n";
4814 } elsif ($t->{'type'} eq "tree") {
4815 print "<td class=\"list\">";
4816 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4817 file_name=>"$basedir$t->{'name'}",
4818 %base_key)},
4819 esc_path($t->{'name'}));
4820 print "</td>\n";
4821 print "<td class=\"link\">";
4822 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4823 file_name=>"$basedir$t->{'name'}",
4824 %base_key)},
4825 "tree");
4826 if (defined $hash_base) {
4827 print " | " .
4828 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4829 file_name=>"$basedir$t->{'name'}")},
4830 "history");
4832 print "</td>\n";
4833 } else {
4834 # unknown object: we can only present history for it
4835 # (this includes 'commit' object, i.e. submodule support)
4836 print "<td class=\"list\">" .
4837 esc_path($t->{'name'}) .
4838 "</td>\n";
4839 print "<td class=\"link\">";
4840 if (defined $hash_base) {
4841 print $cgi->a({-href => href(action=>"history",
4842 hash_base=>$hash_base,
4843 file_name=>"$basedir$t->{'name'}")},
4844 "history");
4846 print "</td>\n";
4850 ## ......................................................................
4851 ## functions printing large fragments of HTML
4853 # get pre-image filenames for merge (combined) diff
4854 sub fill_from_file_info {
4855 my ($diff, @parents) = @_;
4857 $diff->{'from_file'} = [ ];
4858 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4859 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4860 if ($diff->{'status'}[$i] eq 'R' ||
4861 $diff->{'status'}[$i] eq 'C') {
4862 $diff->{'from_file'}[$i] =
4863 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4867 return $diff;
4870 # is current raw difftree line of file deletion
4871 sub is_deleted {
4872 my $diffinfo = shift;
4874 return $diffinfo->{'to_id'} eq ('0' x 40);
4877 # does patch correspond to [previous] difftree raw line
4878 # $diffinfo - hashref of parsed raw diff format
4879 # $patchinfo - hashref of parsed patch diff format
4880 # (the same keys as in $diffinfo)
4881 sub is_patch_split {
4882 my ($diffinfo, $patchinfo) = @_;
4884 return defined $diffinfo && defined $patchinfo
4885 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4889 sub git_difftree_body {
4890 my ($difftree, $hash, @parents) = @_;
4891 my ($parent) = $parents[0];
4892 my $have_blame = gitweb_check_feature('blame');
4893 print "<div class=\"list_head\">\n";
4894 if ($#{$difftree} > 10) {
4895 print(($#{$difftree} + 1) . " files changed:\n");
4897 print "</div>\n";
4899 print "<table class=\"" .
4900 (@parents > 1 ? "combined " : "") .
4901 "diff_tree\">\n";
4903 # header only for combined diff in 'commitdiff' view
4904 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4905 if ($has_header) {
4906 # table header
4907 print "<thead><tr>\n" .
4908 "<th></th><th></th>\n"; # filename, patchN link
4909 for (my $i = 0; $i < @parents; $i++) {
4910 my $par = $parents[$i];
4911 print "<th>" .
4912 $cgi->a({-href => href(action=>"commitdiff",
4913 hash=>$hash, hash_parent=>$par),
4914 -title => 'commitdiff to parent number ' .
4915 ($i+1) . ': ' . substr($par,0,7)},
4916 $i+1) .
4917 "&nbsp;</th>\n";
4919 print "</tr></thead>\n<tbody>\n";
4922 my $alternate = 1;
4923 my $patchno = 0;
4924 foreach my $line (@{$difftree}) {
4925 my $diff = parsed_difftree_line($line);
4927 if ($alternate) {
4928 print "<tr class=\"dark\">\n";
4929 } else {
4930 print "<tr class=\"light\">\n";
4932 $alternate ^= 1;
4934 if (exists $diff->{'nparents'}) { # combined diff
4936 fill_from_file_info($diff, @parents)
4937 unless exists $diff->{'from_file'};
4939 if (!is_deleted($diff)) {
4940 # file exists in the result (child) commit
4941 print "<td>" .
4942 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4943 file_name=>$diff->{'to_file'},
4944 hash_base=>$hash),
4945 -class => "list"}, esc_path($diff->{'to_file'})) .
4946 "</td>\n";
4947 } else {
4948 print "<td>" .
4949 esc_path($diff->{'to_file'}) .
4950 "</td>\n";
4953 if ($action eq 'commitdiff') {
4954 # link to patch
4955 $patchno++;
4956 print "<td class=\"link\">" .
4957 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4958 "patch") .
4959 " | " .
4960 "</td>\n";
4963 my $has_history = 0;
4964 my $not_deleted = 0;
4965 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4966 my $hash_parent = $parents[$i];
4967 my $from_hash = $diff->{'from_id'}[$i];
4968 my $from_path = $diff->{'from_file'}[$i];
4969 my $status = $diff->{'status'}[$i];
4971 $has_history ||= ($status ne 'A');
4972 $not_deleted ||= ($status ne 'D');
4974 if ($status eq 'A') {
4975 print "<td class=\"link\" align=\"right\"> | </td>\n";
4976 } elsif ($status eq 'D') {
4977 print "<td class=\"link\">" .
4978 $cgi->a({-href => href(action=>"blob",
4979 hash_base=>$hash,
4980 hash=>$from_hash,
4981 file_name=>$from_path)},
4982 "blob" . ($i+1)) .
4983 " | </td>\n";
4984 } else {
4985 if ($diff->{'to_id'} eq $from_hash) {
4986 print "<td class=\"link nochange\">";
4987 } else {
4988 print "<td class=\"link\">";
4990 print $cgi->a({-href => href(action=>"blobdiff",
4991 hash=>$diff->{'to_id'},
4992 hash_parent=>$from_hash,
4993 hash_base=>$hash,
4994 hash_parent_base=>$hash_parent,
4995 file_name=>$diff->{'to_file'},
4996 file_parent=>$from_path)},
4997 "diff" . ($i+1)) .
4998 " | </td>\n";
5002 print "<td class=\"link\">";
5003 if ($not_deleted) {
5004 print $cgi->a({-href => href(action=>"blob",
5005 hash=>$diff->{'to_id'},
5006 file_name=>$diff->{'to_file'},
5007 hash_base=>$hash)},
5008 "blob");
5009 print " | " if ($has_history);
5011 if ($has_history) {
5012 print $cgi->a({-href => href(action=>"history",
5013 file_name=>$diff->{'to_file'},
5014 hash_base=>$hash)},
5015 "history");
5017 print "</td>\n";
5019 print "</tr>\n";
5020 next; # instead of 'else' clause, to avoid extra indent
5022 # else ordinary diff
5024 my ($to_mode_oct, $to_mode_str, $to_file_type);
5025 my ($from_mode_oct, $from_mode_str, $from_file_type);
5026 if ($diff->{'to_mode'} ne ('0' x 6)) {
5027 $to_mode_oct = oct $diff->{'to_mode'};
5028 if (S_ISREG($to_mode_oct)) { # only for regular file
5029 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
5031 $to_file_type = file_type($diff->{'to_mode'});
5033 if ($diff->{'from_mode'} ne ('0' x 6)) {
5034 $from_mode_oct = oct $diff->{'from_mode'};
5035 if (S_ISREG($from_mode_oct)) { # only for regular file
5036 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5038 $from_file_type = file_type($diff->{'from_mode'});
5041 if ($diff->{'status'} eq "A") { # created
5042 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5043 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5044 $mode_chng .= "]</span>";
5045 print "<td>";
5046 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5047 hash_base=>$hash, file_name=>$diff->{'file'}),
5048 -class => "list"}, esc_path($diff->{'file'}));
5049 print "</td>\n";
5050 print "<td>$mode_chng</td>\n";
5051 print "<td class=\"link\">";
5052 if ($action eq 'commitdiff') {
5053 # link to patch
5054 $patchno++;
5055 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5056 "patch") .
5057 " | ";
5059 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5060 hash_base=>$hash, file_name=>$diff->{'file'})},
5061 "blob");
5062 print "</td>\n";
5064 } elsif ($diff->{'status'} eq "D") { # deleted
5065 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5066 print "<td>";
5067 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5068 hash_base=>$parent, file_name=>$diff->{'file'}),
5069 -class => "list"}, esc_path($diff->{'file'}));
5070 print "</td>\n";
5071 print "<td>$mode_chng</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 " | ";
5080 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5081 hash_base=>$parent, file_name=>$diff->{'file'})},
5082 "blob") . " | ";
5083 if ($have_blame) {
5084 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5085 file_name=>$diff->{'file'})},
5086 "blame") . " | ";
5088 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5089 file_name=>$diff->{'file'})},
5090 "history");
5091 print "</td>\n";
5093 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5094 my $mode_chnge = "";
5095 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5096 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5097 if ($from_file_type ne $to_file_type) {
5098 $mode_chnge .= " from $from_file_type to $to_file_type";
5100 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5101 if ($from_mode_str && $to_mode_str) {
5102 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5103 } elsif ($to_mode_str) {
5104 $mode_chnge .= " mode: $to_mode_str";
5107 $mode_chnge .= "]</span>\n";
5109 print "<td>";
5110 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5111 hash_base=>$hash, file_name=>$diff->{'file'}),
5112 -class => "list"}, esc_path($diff->{'file'}));
5113 print "</td>\n";
5114 print "<td>$mode_chnge</td>\n";
5115 print "<td class=\"link\">";
5116 if ($action eq 'commitdiff') {
5117 # link to patch
5118 $patchno++;
5119 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5120 "patch") .
5121 " | ";
5122 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5123 # "commit" view and modified file (not onlu mode changed)
5124 print $cgi->a({-href => href(action=>"blobdiff",
5125 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5126 hash_base=>$hash, hash_parent_base=>$parent,
5127 file_name=>$diff->{'file'})},
5128 "diff") .
5129 " | ";
5131 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5132 hash_base=>$hash, file_name=>$diff->{'file'})},
5133 "blob") . " | ";
5134 if ($have_blame) {
5135 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5136 file_name=>$diff->{'file'})},
5137 "blame") . " | ";
5139 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5140 file_name=>$diff->{'file'})},
5141 "history");
5142 print "</td>\n";
5144 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5145 my %status_name = ('R' => 'moved', 'C' => 'copied');
5146 my $nstatus = $status_name{$diff->{'status'}};
5147 my $mode_chng = "";
5148 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5149 # mode also for directories, so we cannot use $to_mode_str
5150 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5152 print "<td>" .
5153 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5154 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5155 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5156 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5157 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5158 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5159 -class => "list"}, esc_path($diff->{'from_file'})) .
5160 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5161 "<td class=\"link\">";
5162 if ($action eq 'commitdiff') {
5163 # link to patch
5164 $patchno++;
5165 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5166 "patch") .
5167 " | ";
5168 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5169 # "commit" view and modified file (not only pure rename or copy)
5170 print $cgi->a({-href => href(action=>"blobdiff",
5171 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5172 hash_base=>$hash, hash_parent_base=>$parent,
5173 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5174 "diff") .
5175 " | ";
5177 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5178 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5179 "blob") . " | ";
5180 if ($have_blame) {
5181 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5182 file_name=>$diff->{'to_file'})},
5183 "blame") . " | ";
5185 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5186 file_name=>$diff->{'to_file'})},
5187 "history");
5188 print "</td>\n";
5190 } # we should not encounter Unmerged (U) or Unknown (X) status
5191 print "</tr>\n";
5193 print "</tbody>" if $has_header;
5194 print "</table>\n";
5197 # Print context lines and then rem/add lines in a side-by-side manner.
5198 sub print_sidebyside_diff_lines {
5199 my ($ctx, $rem, $add) = @_;
5201 # print context block before add/rem block
5202 if (@$ctx) {
5203 print join '',
5204 '<div class="chunk_block ctx">',
5205 '<div class="old">',
5206 @$ctx,
5207 '</div>',
5208 '<div class="new">',
5209 @$ctx,
5210 '</div>',
5211 '</div>';
5214 if (!@$add) {
5215 # pure removal
5216 print join '',
5217 '<div class="chunk_block rem">',
5218 '<div class="old">',
5219 @$rem,
5220 '</div>',
5221 '</div>';
5222 } elsif (!@$rem) {
5223 # pure addition
5224 print join '',
5225 '<div class="chunk_block add">',
5226 '<div class="new">',
5227 @$add,
5228 '</div>',
5229 '</div>';
5230 } else {
5231 print join '',
5232 '<div class="chunk_block chg">',
5233 '<div class="old">',
5234 @$rem,
5235 '</div>',
5236 '<div class="new">',
5237 @$add,
5238 '</div>',
5239 '</div>';
5243 # Print context lines and then rem/add lines in inline manner.
5244 sub print_inline_diff_lines {
5245 my ($ctx, $rem, $add) = @_;
5247 print @$ctx, @$rem, @$add;
5250 # Format removed and added line, mark changed part and HTML-format them.
5251 # Implementation is based on contrib/diff-highlight
5252 sub format_rem_add_lines_pair {
5253 my ($rem, $add, $num_parents) = @_;
5255 # We need to untabify lines before split()'ing them;
5256 # otherwise offsets would be invalid.
5257 chomp $rem;
5258 chomp $add;
5259 $rem = untabify($rem);
5260 $add = untabify($add);
5262 my @rem = split(//, $rem);
5263 my @add = split(//, $add);
5264 my ($esc_rem, $esc_add);
5265 # Ignore leading +/- characters for each parent.
5266 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5267 my ($prefix_has_nonspace, $suffix_has_nonspace);
5269 my $shorter = (@rem < @add) ? @rem : @add;
5270 while ($prefix_len < $shorter) {
5271 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5273 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5274 $prefix_len++;
5277 while ($prefix_len + $suffix_len < $shorter) {
5278 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5280 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5281 $suffix_len++;
5284 # Mark lines that are different from each other, but have some common
5285 # part that isn't whitespace. If lines are completely different, don't
5286 # mark them because that would make output unreadable, especially if
5287 # diff consists of multiple lines.
5288 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5289 $esc_rem = esc_html_hl_regions($rem, 'marked',
5290 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5291 $esc_add = esc_html_hl_regions($add, 'marked',
5292 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5293 } else {
5294 $esc_rem = esc_html($rem, -nbsp=>1);
5295 $esc_add = esc_html($add, -nbsp=>1);
5298 return format_diff_line(\$esc_rem, 'rem'),
5299 format_diff_line(\$esc_add, 'add');
5302 # HTML-format diff context, removed and added lines.
5303 sub format_ctx_rem_add_lines {
5304 my ($ctx, $rem, $add, $num_parents) = @_;
5305 my (@new_ctx, @new_rem, @new_add);
5306 my $can_highlight = 0;
5307 my $is_combined = ($num_parents > 1);
5309 # Highlight if every removed line has a corresponding added line.
5310 if (@$add > 0 && @$add == @$rem) {
5311 $can_highlight = 1;
5313 # Highlight lines in combined diff only if the chunk contains
5314 # diff between the same version, e.g.
5316 # - a
5317 # - b
5318 # + c
5319 # + d
5321 # Otherwise the highlightling would be confusing.
5322 if ($is_combined) {
5323 for (my $i = 0; $i < @$add; $i++) {
5324 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5325 my $prefix_add = substr($add->[$i], 0, $num_parents);
5327 $prefix_rem =~ s/-/+/g;
5329 if ($prefix_rem ne $prefix_add) {
5330 $can_highlight = 0;
5331 last;
5337 if ($can_highlight) {
5338 for (my $i = 0; $i < @$add; $i++) {
5339 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5340 $rem->[$i], $add->[$i], $num_parents);
5341 push @new_rem, $line_rem;
5342 push @new_add, $line_add;
5344 } else {
5345 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5346 @new_add = map { format_diff_line($_, 'add') } @$add;
5349 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5351 return (\@new_ctx, \@new_rem, \@new_add);
5354 # Print context lines and then rem/add lines.
5355 sub print_diff_lines {
5356 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5357 my $is_combined = $num_parents > 1;
5359 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5360 $num_parents);
5362 if ($diff_style eq 'sidebyside' && !$is_combined) {
5363 print_sidebyside_diff_lines($ctx, $rem, $add);
5364 } else {
5365 # default 'inline' style and unknown styles
5366 print_inline_diff_lines($ctx, $rem, $add);
5370 sub print_diff_chunk {
5371 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5372 my (@ctx, @rem, @add);
5374 # The class of the previous line.
5375 my $prev_class = '';
5377 return unless @chunk;
5379 # incomplete last line might be among removed or added lines,
5380 # or both, or among context lines: find which
5381 for (my $i = 1; $i < @chunk; $i++) {
5382 if ($chunk[$i][0] eq 'incomplete') {
5383 $chunk[$i][0] = $chunk[$i-1][0];
5387 # guardian
5388 push @chunk, ["", ""];
5390 foreach my $line_info (@chunk) {
5391 my ($class, $line) = @$line_info;
5393 # print chunk headers
5394 if ($class && $class eq 'chunk_header') {
5395 print format_diff_line($line, $class, $from, $to);
5396 next;
5399 ## print from accumulator when have some add/rem lines or end
5400 # of chunk (flush context lines), or when have add and rem
5401 # lines and new block is reached (otherwise add/rem lines could
5402 # be reordered)
5403 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5404 (@rem && @add && $class ne $prev_class)) {
5405 print_diff_lines(\@ctx, \@rem, \@add,
5406 $diff_style, $num_parents);
5407 @ctx = @rem = @add = ();
5410 ## adding lines to accumulator
5411 # guardian value
5412 last unless $line;
5413 # rem, add or change
5414 if ($class eq 'rem') {
5415 push @rem, $line;
5416 } elsif ($class eq 'add') {
5417 push @add, $line;
5419 # context line
5420 if ($class eq 'ctx') {
5421 push @ctx, $line;
5424 $prev_class = $class;
5428 sub git_patchset_body {
5429 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5430 my ($hash_parent) = $hash_parents[0];
5432 my $is_combined = (@hash_parents > 1);
5433 my $patch_idx = 0;
5434 my $patch_number = 0;
5435 my $patch_line;
5436 my $diffinfo;
5437 my $to_name;
5438 my (%from, %to);
5439 my @chunk; # for side-by-side diff
5441 print "<div class=\"patchset\">\n";
5443 # skip to first patch
5444 while ($patch_line = <$fd>) {
5445 chomp $patch_line;
5447 last if ($patch_line =~ m/^diff /);
5450 PATCH:
5451 while ($patch_line) {
5453 # parse "git diff" header line
5454 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5455 # $1 is from_name, which we do not use
5456 $to_name = unquote($2);
5457 $to_name =~ s!^b/!!;
5458 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5459 # $1 is 'cc' or 'combined', which we do not use
5460 $to_name = unquote($2);
5461 } else {
5462 $to_name = undef;
5465 # check if current patch belong to current raw line
5466 # and parse raw git-diff line if needed
5467 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5468 # this is continuation of a split patch
5469 print "<div class=\"patch cont\">\n";
5470 } else {
5471 # advance raw git-diff output if needed
5472 $patch_idx++ if defined $diffinfo;
5474 # read and prepare patch information
5475 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5477 # compact combined diff output can have some patches skipped
5478 # find which patch (using pathname of result) we are at now;
5479 if ($is_combined) {
5480 while ($to_name ne $diffinfo->{'to_file'}) {
5481 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5482 format_diff_cc_simplified($diffinfo, @hash_parents) .
5483 "</div>\n"; # class="patch"
5485 $patch_idx++;
5486 $patch_number++;
5488 last if $patch_idx > $#$difftree;
5489 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5493 # modifies %from, %to hashes
5494 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5496 # this is first patch for raw difftree line with $patch_idx index
5497 # we index @$difftree array from 0, but number patches from 1
5498 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5501 # git diff header
5502 #assert($patch_line =~ m/^diff /) if DEBUG;
5503 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5504 $patch_number++;
5505 # print "git diff" header
5506 print format_git_diff_header_line($patch_line, $diffinfo,
5507 \%from, \%to);
5509 # print extended diff header
5510 print "<div class=\"diff extended_header\">\n";
5511 EXTENDED_HEADER:
5512 while ($patch_line = <$fd>) {
5513 chomp $patch_line;
5515 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5517 print format_extended_diff_header_line($patch_line, $diffinfo,
5518 \%from, \%to);
5520 print "</div>\n"; # class="diff extended_header"
5522 # from-file/to-file diff header
5523 if (! $patch_line) {
5524 print "</div>\n"; # class="patch"
5525 last PATCH;
5527 next PATCH if ($patch_line =~ m/^diff /);
5528 #assert($patch_line =~ m/^---/) if DEBUG;
5530 my $last_patch_line = $patch_line;
5531 $patch_line = <$fd>;
5532 chomp $patch_line;
5533 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5535 print format_diff_from_to_header($last_patch_line, $patch_line,
5536 $diffinfo, \%from, \%to,
5537 @hash_parents);
5539 # the patch itself
5540 LINE:
5541 while ($patch_line = <$fd>) {
5542 chomp $patch_line;
5544 next PATCH if ($patch_line =~ m/^diff /);
5546 my $class = diff_line_class($patch_line, \%from, \%to);
5548 if ($class eq 'chunk_header') {
5549 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5550 @chunk = ();
5553 push @chunk, [ $class, $patch_line ];
5556 } continue {
5557 if (@chunk) {
5558 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5559 @chunk = ();
5561 print "</div>\n"; # class="patch"
5564 # for compact combined (--cc) format, with chunk and patch simplification
5565 # the patchset might be empty, but there might be unprocessed raw lines
5566 for (++$patch_idx if $patch_number > 0;
5567 $patch_idx < @$difftree;
5568 ++$patch_idx) {
5569 # read and prepare patch information
5570 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5572 # generate anchor for "patch" links in difftree / whatchanged part
5573 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5574 format_diff_cc_simplified($diffinfo, @hash_parents) .
5575 "</div>\n"; # class="patch"
5577 $patch_number++;
5580 if ($patch_number == 0) {
5581 if (@hash_parents > 1) {
5582 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5583 } else {
5584 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5588 print "</div>\n"; # class="patchset"
5591 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5593 sub git_project_search_form {
5594 my ($searchtext, $search_use_regexp) = @_;
5596 my $limit = '';
5597 if ($project_filter) {
5598 $limit = " in '$project_filter/'";
5601 print "<div class=\"projsearch\">\n";
5602 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5603 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5604 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5605 if (defined $project_filter);
5606 print $cgi->textfield(-name => 's', -value => $searchtext,
5607 -title => "Search project by name and description$limit",
5608 -size => 60) . "\n" .
5609 "<span title=\"Extended regular expression\">" .
5610 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5611 -checked => $search_use_regexp) .
5612 "</span>\n" .
5613 $cgi->submit(-name => 'btnS', -value => 'Search') .
5614 $cgi->end_form() . "\n" .
5615 $cgi->a({-href => href(project => undef, searchtext => undef,
5616 project_filter => $project_filter)},
5617 esc_html("List all projects$limit")) . "<br />\n";
5618 print "</div>\n";
5621 # entry for given @keys needs filling if at least one of keys in list
5622 # is not present in %$project_info
5623 sub project_info_needs_filling {
5624 my ($project_info, @keys) = @_;
5626 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5627 foreach my $key (@keys) {
5628 if (!exists $project_info->{$key}) {
5629 return 1;
5632 return;
5635 # fills project list info (age, description, owner, category, forks, etc.)
5636 # for each project in the list, removing invalid projects from
5637 # returned list, or fill only specified info.
5639 # Invalid projects are removed from the returned list if and only if you
5640 # ask 'age' or 'age_string' to be filled, because they are the only fields
5641 # that run unconditionally git command that requires repository, and
5642 # therefore do always check if project repository is invalid.
5644 # USAGE:
5645 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5646 # ensures that 'descr_long' and 'ctags' fields are filled
5647 # * @project_list = fill_project_list_info(\@project_list)
5648 # ensures that all fields are filled (and invalid projects removed)
5650 # NOTE: modifies $projlist, but does not remove entries from it
5651 sub fill_project_list_info {
5652 my ($projlist, @wanted_keys) = @_;
5653 my @projects;
5654 my $filter_set = sub { return @_; };
5655 if (@wanted_keys) {
5656 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5657 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5660 my $show_ctags = gitweb_check_feature('ctags');
5661 PROJECT:
5662 foreach my $pr (@$projlist) {
5663 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5664 my (@activity) = git_get_last_activity($pr->{'path'});
5665 unless (@activity) {
5666 next PROJECT;
5668 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5670 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5671 my $descr = git_get_project_description($pr->{'path'}) || "";
5672 $descr = to_utf8($descr);
5673 $pr->{'descr_long'} = $descr;
5674 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5676 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5677 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5679 if ($show_ctags &&
5680 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5681 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5683 if ($projects_list_group_categories &&
5684 project_info_needs_filling($pr, $filter_set->('category'))) {
5685 my $cat = git_get_project_category($pr->{'path'}) ||
5686 $project_list_default_category;
5687 $pr->{'category'} = to_utf8($cat);
5690 push @projects, $pr;
5693 return @projects;
5696 sub sort_projects_list {
5697 my ($projlist, $order) = @_;
5699 sub order_str {
5700 my $key = shift;
5701 return sub { $a->{$key} cmp $b->{$key} };
5704 sub order_num_then_undef {
5705 my $key = shift;
5706 return sub {
5707 defined $a->{$key} ?
5708 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5709 (defined $b->{$key} ? 1 : 0)
5713 my %orderings = (
5714 project => order_str('path'),
5715 descr => order_str('descr_long'),
5716 owner => order_str('owner'),
5717 age => order_num_then_undef('age'),
5720 my $ordering = $orderings{$order};
5721 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5724 # returns a hash of categories, containing the list of project
5725 # belonging to each category
5726 sub build_projlist_by_category {
5727 my ($projlist, $from, $to) = @_;
5728 my %categories;
5730 $from = 0 unless defined $from;
5731 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5733 for (my $i = $from; $i <= $to; $i++) {
5734 my $pr = $projlist->[$i];
5735 push @{$categories{ $pr->{'category'} }}, $pr;
5738 return wantarray ? %categories : \%categories;
5741 # print 'sort by' <th> element, generating 'sort by $name' replay link
5742 # if that order is not selected
5743 sub print_sort_th {
5744 print format_sort_th(@_);
5747 sub format_sort_th {
5748 my ($name, $order, $header) = @_;
5749 my $sort_th = "";
5750 $header ||= ucfirst($name);
5752 if ($order eq $name) {
5753 $sort_th .= "<th>$header</th>\n";
5754 } else {
5755 $sort_th .= "<th>" .
5756 $cgi->a({-href => href(-replay=>1, order=>$name),
5757 -class => "header"}, $header) .
5758 "</th>\n";
5761 return $sort_th;
5764 sub git_project_list_rows {
5765 my ($projlist, $from, $to, $check_forks) = @_;
5767 $from = 0 unless defined $from;
5768 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5770 my $alternate = 1;
5771 for (my $i = $from; $i <= $to; $i++) {
5772 my $pr = $projlist->[$i];
5774 if ($alternate) {
5775 print "<tr class=\"dark\">\n";
5776 } else {
5777 print "<tr class=\"light\">\n";
5779 $alternate ^= 1;
5781 if ($check_forks) {
5782 print "<td>";
5783 if ($pr->{'forks'}) {
5784 my $nforks = scalar @{$pr->{'forks'}};
5785 if ($nforks > 0) {
5786 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5787 -title => "$nforks forks"}, "+");
5788 } else {
5789 print $cgi->span({-title => "$nforks forks"}, "+");
5792 print "</td>\n";
5794 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5795 -class => "list"},
5796 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5797 "</td>\n" .
5798 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5799 -class => "list",
5800 -title => $pr->{'descr_long'}},
5801 $search_regexp
5802 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5803 $pr->{'descr'}, $search_regexp)
5804 : esc_html($pr->{'descr'})) .
5805 "</td>\n";
5806 unless ($omit_owner) {
5807 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5809 unless ($omit_age_column) {
5810 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5811 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5813 print"<td class=\"link\">" .
5814 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5815 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5816 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5817 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5818 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5819 "</td>\n" .
5820 "</tr>\n";
5824 sub git_project_list_body {
5825 # actually uses global variable $project
5826 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5827 my @projects = @$projlist;
5829 my $check_forks = gitweb_check_feature('forks');
5830 my $show_ctags = gitweb_check_feature('ctags');
5831 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5832 $check_forks = undef
5833 if ($tagfilter || $search_regexp);
5835 # filtering out forks before filling info allows to do less work
5836 @projects = filter_forks_from_projects_list(\@projects)
5837 if ($check_forks);
5838 # search_projects_list pre-fills required info
5839 @projects = search_projects_list(\@projects,
5840 'search_regexp' => $search_regexp,
5841 'tagfilter' => $tagfilter)
5842 if ($tagfilter || $search_regexp);
5843 # fill the rest
5844 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5845 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5846 push @all_fields, 'owner' unless($omit_owner);
5847 @projects = fill_project_list_info(\@projects, @all_fields);
5849 $order ||= $default_projects_order;
5850 $from = 0 unless defined $from;
5851 $to = $#projects if (!defined $to || $#projects < $to);
5853 # short circuit
5854 if ($from > $to) {
5855 print "<center>\n".
5856 "<b>No such projects found</b><br />\n".
5857 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5858 "</center>\n<br />\n";
5859 return;
5862 @projects = sort_projects_list(\@projects, $order);
5864 if ($show_ctags) {
5865 my $ctags = git_gather_all_ctags(\@projects);
5866 my $cloud = git_populate_project_tagcloud($ctags);
5867 print git_show_project_tagcloud($cloud, 64);
5870 print "<table class=\"project_list\">\n";
5871 unless ($no_header) {
5872 print "<tr>\n";
5873 if ($check_forks) {
5874 print "<th></th>\n";
5876 print_sort_th('project', $order, 'Project');
5877 print_sort_th('descr', $order, 'Description');
5878 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5879 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5880 print "<th></th>\n" . # for links
5881 "</tr>\n";
5884 if ($projects_list_group_categories) {
5885 # only display categories with projects in the $from-$to window
5886 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5887 my %categories = build_projlist_by_category(\@projects, $from, $to);
5888 foreach my $cat (sort keys %categories) {
5889 unless ($cat eq "") {
5890 print "<tr>\n";
5891 if ($check_forks) {
5892 print "<td></td>\n";
5894 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5895 print "</tr>\n";
5898 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5900 } else {
5901 git_project_list_rows(\@projects, $from, $to, $check_forks);
5904 if (defined $extra) {
5905 print "<tr>\n";
5906 if ($check_forks) {
5907 print "<td></td>\n";
5909 print "<td colspan=\"5\">$extra</td>\n" .
5910 "</tr>\n";
5912 print "</table>\n";
5915 sub git_log_body {
5916 # uses global variable $project
5917 my ($commitlist, $from, $to, $refs, $extra) = @_;
5919 $from = 0 unless defined $from;
5920 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5922 for (my $i = 0; $i <= $to; $i++) {
5923 my %co = %{$commitlist->[$i]};
5924 next if !%co;
5925 my $commit = $co{'id'};
5926 my $ref = format_ref_marker($refs, $commit);
5927 git_print_header_div('commit',
5928 "<span class=\"age\">$co{'age_string'}</span>" .
5929 esc_html($co{'title'}) . $ref,
5930 $commit);
5931 print "<div class=\"title_text\">\n" .
5932 "<div class=\"log_link\">\n" .
5933 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5934 " | " .
5935 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5936 " | " .
5937 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5938 "<br/>\n" .
5939 "</div>\n";
5940 git_print_authorship(\%co, -tag => 'span');
5941 print "<br/>\n</div>\n";
5943 print "<div class=\"log_body\">\n";
5944 git_print_log($co{'comment'}, -final_empty_line=> 1);
5945 print "</div>\n";
5947 if ($extra) {
5948 print "<div class=\"page_nav\">\n";
5949 print "$extra\n";
5950 print "</div>\n";
5954 sub git_shortlog_body {
5955 # uses global variable $project
5956 my ($commitlist, $from, $to, $refs, $extra) = @_;
5958 $from = 0 unless defined $from;
5959 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5961 print "<table class=\"shortlog\">\n";
5962 my $alternate = 1;
5963 for (my $i = $from; $i <= $to; $i++) {
5964 my %co = %{$commitlist->[$i]};
5965 my $commit = $co{'id'};
5966 my $ref = format_ref_marker($refs, $commit);
5967 if ($alternate) {
5968 print "<tr class=\"dark\">\n";
5969 } else {
5970 print "<tr class=\"light\">\n";
5972 $alternate ^= 1;
5973 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5974 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5975 format_author_html('td', \%co, 10) . "<td>";
5976 print format_subject_html($co{'title'}, $co{'title_short'},
5977 href(action=>"commit", hash=>$commit), $ref);
5978 print "</td>\n" .
5979 "<td class=\"link\">" .
5980 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5981 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5982 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5983 my $snapshot_links = format_snapshot_links($commit);
5984 if (defined $snapshot_links) {
5985 print " | " . $snapshot_links;
5987 print "</td>\n" .
5988 "</tr>\n";
5990 if (defined $extra) {
5991 print "<tr>\n" .
5992 "<td colspan=\"4\">$extra</td>\n" .
5993 "</tr>\n";
5995 print "</table>\n";
5998 sub git_history_body {
5999 # Warning: assumes constant type (blob or tree) during history
6000 my ($commitlist, $from, $to, $refs, $extra,
6001 $file_name, $file_hash, $ftype) = @_;
6003 $from = 0 unless defined $from;
6004 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
6006 print "<table class=\"history\">\n";
6007 my $alternate = 1;
6008 for (my $i = $from; $i <= $to; $i++) {
6009 my %co = %{$commitlist->[$i]};
6010 if (!%co) {
6011 next;
6013 my $commit = $co{'id'};
6015 my $ref = format_ref_marker($refs, $commit);
6017 if ($alternate) {
6018 print "<tr class=\"dark\">\n";
6019 } else {
6020 print "<tr class=\"light\">\n";
6022 $alternate ^= 1;
6023 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6024 # shortlog: format_author_html('td', \%co, 10)
6025 format_author_html('td', \%co, 15, 3) . "<td>";
6026 # originally git_history used chop_str($co{'title'}, 50)
6027 print format_subject_html($co{'title'}, $co{'title_short'},
6028 href(action=>"commit", hash=>$commit), $ref);
6029 print "</td>\n" .
6030 "<td class=\"link\">" .
6031 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
6032 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
6034 if ($ftype eq 'blob') {
6035 my $blob_current = $file_hash;
6036 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6037 if (defined $blob_current && defined $blob_parent &&
6038 $blob_current ne $blob_parent) {
6039 print " | " .
6040 $cgi->a({-href => href(action=>"blobdiff",
6041 hash=>$blob_current, hash_parent=>$blob_parent,
6042 hash_base=>$hash_base, hash_parent_base=>$commit,
6043 file_name=>$file_name)},
6044 "diff to current");
6047 print "</td>\n" .
6048 "</tr>\n";
6050 if (defined $extra) {
6051 print "<tr>\n" .
6052 "<td colspan=\"4\">$extra</td>\n" .
6053 "</tr>\n";
6055 print "</table>\n";
6058 sub git_tags_body {
6059 # uses global variable $project
6060 my ($taglist, $from, $to, $extra) = @_;
6061 $from = 0 unless defined $from;
6062 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6064 print "<table class=\"tags\">\n";
6065 my $alternate = 1;
6066 for (my $i = $from; $i <= $to; $i++) {
6067 my $entry = $taglist->[$i];
6068 my %tag = %$entry;
6069 my $comment = $tag{'subject'};
6070 my $comment_short;
6071 if (defined $comment) {
6072 $comment_short = chop_str($comment, 30, 5);
6074 if ($alternate) {
6075 print "<tr class=\"dark\">\n";
6076 } else {
6077 print "<tr class=\"light\">\n";
6079 $alternate ^= 1;
6080 if (defined $tag{'age'}) {
6081 print "<td><i>$tag{'age'}</i></td>\n";
6082 } else {
6083 print "<td></td>\n";
6085 print "<td>" .
6086 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6087 -class => "list name"}, esc_html($tag{'name'})) .
6088 "</td>\n" .
6089 "<td>";
6090 if (defined $comment) {
6091 print format_subject_html($comment, $comment_short,
6092 href(action=>"tag", hash=>$tag{'id'}));
6094 print "</td>\n" .
6095 "<td class=\"selflink\">";
6096 if ($tag{'type'} eq "tag") {
6097 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6098 } else {
6099 print "&nbsp;";
6101 print "</td>\n" .
6102 "<td class=\"link\">" . " | " .
6103 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6104 if ($tag{'reftype'} eq "commit") {
6105 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6106 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6107 } elsif ($tag{'reftype'} eq "blob") {
6108 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6110 print "</td>\n" .
6111 "</tr>";
6113 if (defined $extra) {
6114 print "<tr>\n" .
6115 "<td colspan=\"5\">$extra</td>\n" .
6116 "</tr>\n";
6118 print "</table>\n";
6121 sub git_heads_body {
6122 # uses global variable $project
6123 my ($headlist, $head_at, $from, $to, $extra) = @_;
6124 $from = 0 unless defined $from;
6125 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6127 print "<table class=\"heads\">\n";
6128 my $alternate = 1;
6129 for (my $i = $from; $i <= $to; $i++) {
6130 my $entry = $headlist->[$i];
6131 my %ref = %$entry;
6132 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6133 if ($alternate) {
6134 print "<tr class=\"dark\">\n";
6135 } else {
6136 print "<tr class=\"light\">\n";
6138 $alternate ^= 1;
6139 print "<td><i>$ref{'age'}</i></td>\n" .
6140 ($curr ? "<td class=\"current_head\">" : "<td>") .
6141 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6142 -class => "list name"},esc_html($ref{'name'})) .
6143 "</td>\n" .
6144 "<td class=\"link\">" .
6145 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6146 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6147 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6148 "</td>\n" .
6149 "</tr>";
6151 if (defined $extra) {
6152 print "<tr>\n" .
6153 "<td colspan=\"3\">$extra</td>\n" .
6154 "</tr>\n";
6156 print "</table>\n";
6159 # Display a single remote block
6160 sub git_remote_block {
6161 my ($remote, $rdata, $limit, $head) = @_;
6163 my $heads = $rdata->{'heads'};
6164 my $fetch = $rdata->{'fetch'};
6165 my $push = $rdata->{'push'};
6167 my $urls_table = "<table class=\"projects_list\">\n" ;
6169 if (defined $fetch) {
6170 if ($fetch eq $push) {
6171 $urls_table .= format_repo_url("URL", $fetch);
6172 } else {
6173 $urls_table .= format_repo_url("Fetch URL", $fetch);
6174 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6176 } elsif (defined $push) {
6177 $urls_table .= format_repo_url("Push URL", $push);
6178 } else {
6179 $urls_table .= format_repo_url("", "No remote URL");
6182 $urls_table .= "</table>\n";
6184 my $dots;
6185 if (defined $limit && $limit < @$heads) {
6186 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6189 print $urls_table;
6190 git_heads_body($heads, $head, 0, $limit, $dots);
6193 # Display a list of remote names with the respective fetch and push URLs
6194 sub git_remotes_list {
6195 my ($remotedata, $limit) = @_;
6196 print "<table class=\"heads\">\n";
6197 my $alternate = 1;
6198 my @remotes = sort keys %$remotedata;
6200 my $limited = $limit && $limit < @remotes;
6202 $#remotes = $limit - 1 if $limited;
6204 while (my $remote = shift @remotes) {
6205 my $rdata = $remotedata->{$remote};
6206 my $fetch = $rdata->{'fetch'};
6207 my $push = $rdata->{'push'};
6208 if ($alternate) {
6209 print "<tr class=\"dark\">\n";
6210 } else {
6211 print "<tr class=\"light\">\n";
6213 $alternate ^= 1;
6214 print "<td>" .
6215 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6216 -class=> "list name"},esc_html($remote)) .
6217 "</td>";
6218 print "<td class=\"link\">" .
6219 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6220 " | " .
6221 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6222 "</td>";
6224 print "</tr>\n";
6227 if ($limited) {
6228 print "<tr>\n" .
6229 "<td colspan=\"3\">" .
6230 $cgi->a({-href => href(action=>"remotes")}, "...") .
6231 "</td>\n" . "</tr>\n";
6234 print "</table>";
6237 # Display remote heads grouped by remote, unless there are too many
6238 # remotes, in which case we only display the remote names
6239 sub git_remotes_body {
6240 my ($remotedata, $limit, $head) = @_;
6241 if ($limit and $limit < keys %$remotedata) {
6242 git_remotes_list($remotedata, $limit);
6243 } else {
6244 fill_remote_heads($remotedata);
6245 while (my ($remote, $rdata) = each %$remotedata) {
6246 git_print_section({-class=>"remote", -id=>$remote},
6247 ["remotes", $remote, $remote], sub {
6248 git_remote_block($remote, $rdata, $limit, $head);
6254 sub git_search_message {
6255 my %co = @_;
6257 my $greptype;
6258 if ($searchtype eq 'commit') {
6259 $greptype = "--grep=";
6260 } elsif ($searchtype eq 'author') {
6261 $greptype = "--author=";
6262 } elsif ($searchtype eq 'committer') {
6263 $greptype = "--committer=";
6265 $greptype .= $searchtext;
6266 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6267 $greptype, '--regexp-ignore-case',
6268 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6270 my $paging_nav = '';
6271 if ($page > 0) {
6272 $paging_nav .=
6273 $cgi->a({-href => href(-replay=>1, page=>undef)},
6274 "first") .
6275 " &sdot; " .
6276 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6277 -accesskey => "p", -title => "Alt-p"}, "prev");
6278 } else {
6279 $paging_nav .= "first &sdot; prev";
6281 my $next_link = '';
6282 if ($#commitlist >= 100) {
6283 $next_link =
6284 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6285 -accesskey => "n", -title => "Alt-n"}, "next");
6286 $paging_nav .= " &sdot; $next_link";
6287 } else {
6288 $paging_nav .= " &sdot; next";
6291 git_header_html();
6293 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6294 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6295 if ($page == 0 && !@commitlist) {
6296 print "<p>No match.</p>\n";
6297 } else {
6298 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6301 git_footer_html();
6304 sub git_search_changes {
6305 my %co = @_;
6307 local $/ = "\n";
6308 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6309 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6310 ($search_use_regexp ? '--pickaxe-regex' : ())
6311 or die_error(500, "Open git-log failed");
6313 git_header_html();
6315 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6316 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6318 print "<table class=\"pickaxe search\">\n";
6319 my $alternate = 1;
6320 undef %co;
6321 my @files;
6322 while (my $line = <$fd>) {
6323 chomp $line;
6324 next unless $line;
6326 my %set = parse_difftree_raw_line($line);
6327 if (defined $set{'commit'}) {
6328 # finish previous commit
6329 if (%co) {
6330 print "</td>\n" .
6331 "<td class=\"link\">" .
6332 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6333 "commit") .
6334 " | " .
6335 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6336 hash_base=>$co{'id'})},
6337 "tree") .
6338 "</td>\n" .
6339 "</tr>\n";
6342 if ($alternate) {
6343 print "<tr class=\"dark\">\n";
6344 } else {
6345 print "<tr class=\"light\">\n";
6347 $alternate ^= 1;
6348 %co = parse_commit($set{'commit'});
6349 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6350 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6351 "<td><i>$author</i></td>\n" .
6352 "<td>" .
6353 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6354 -class => "list subject"},
6355 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6356 } elsif (defined $set{'to_id'}) {
6357 next if ($set{'to_id'} =~ m/^0{40}$/);
6359 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6360 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6361 -class => "list"},
6362 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6363 "<br/>\n";
6366 close $fd;
6368 # finish last commit (warning: repetition!)
6369 if (%co) {
6370 print "</td>\n" .
6371 "<td class=\"link\">" .
6372 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6373 "commit") .
6374 " | " .
6375 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6376 hash_base=>$co{'id'})},
6377 "tree") .
6378 "</td>\n" .
6379 "</tr>\n";
6382 print "</table>\n";
6384 git_footer_html();
6387 sub git_search_files {
6388 my %co = @_;
6390 local $/ = "\n";
6391 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6392 $search_use_regexp ? ('-E', '-i') : '-F',
6393 $searchtext, $co{'tree'}
6394 or die_error(500, "Open git-grep failed");
6396 git_header_html();
6398 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6399 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6401 print "<table class=\"grep_search\">\n";
6402 my $alternate = 1;
6403 my $matches = 0;
6404 my $lastfile = '';
6405 my $file_href;
6406 while (my $line = <$fd>) {
6407 chomp $line;
6408 my ($file, $lno, $ltext, $binary);
6409 last if ($matches++ > 1000);
6410 if ($line =~ /^Binary file (.+) matches$/) {
6411 $file = $1;
6412 $binary = 1;
6413 } else {
6414 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6415 $file =~ s/^$co{'tree'}://;
6417 if ($file ne $lastfile) {
6418 $lastfile and print "</td></tr>\n";
6419 if ($alternate++) {
6420 print "<tr class=\"dark\">\n";
6421 } else {
6422 print "<tr class=\"light\">\n";
6424 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6425 file_name=>$file);
6426 print "<td class=\"list\">".
6427 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6428 print "</td><td>\n";
6429 $lastfile = $file;
6431 if ($binary) {
6432 print "<div class=\"binary\">Binary file</div>\n";
6433 } else {
6434 $ltext = untabify($ltext);
6435 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6436 $ltext = esc_html($1, -nbsp=>1);
6437 $ltext .= '<span class="match">';
6438 $ltext .= esc_html($2, -nbsp=>1);
6439 $ltext .= '</span>';
6440 $ltext .= esc_html($3, -nbsp=>1);
6441 } else {
6442 $ltext = esc_html($ltext, -nbsp=>1);
6444 print "<div class=\"pre\">" .
6445 $cgi->a({-href => $file_href.'#l'.$lno,
6446 -class => "linenr"}, sprintf('%4i', $lno)) .
6447 ' ' . $ltext . "</div>\n";
6450 if ($lastfile) {
6451 print "</td></tr>\n";
6452 if ($matches > 1000) {
6453 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6455 } else {
6456 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6458 close $fd;
6460 print "</table>\n";
6462 git_footer_html();
6465 sub git_search_grep_body {
6466 my ($commitlist, $from, $to, $extra) = @_;
6467 $from = 0 unless defined $from;
6468 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6470 print "<table class=\"commit_search\">\n";
6471 my $alternate = 1;
6472 for (my $i = $from; $i <= $to; $i++) {
6473 my %co = %{$commitlist->[$i]};
6474 if (!%co) {
6475 next;
6477 my $commit = $co{'id'};
6478 if ($alternate) {
6479 print "<tr class=\"dark\">\n";
6480 } else {
6481 print "<tr class=\"light\">\n";
6483 $alternate ^= 1;
6484 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6485 format_author_html('td', \%co, 15, 5) .
6486 "<td>" .
6487 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6488 -class => "list subject"},
6489 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6490 my $comment = $co{'comment'};
6491 foreach my $line (@$comment) {
6492 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6493 my ($lead, $match, $trail) = ($1, $2, $3);
6494 $match = chop_str($match, 70, 5, 'center');
6495 my $contextlen = int((80 - length($match))/2);
6496 $contextlen = 30 if ($contextlen > 30);
6497 $lead = chop_str($lead, $contextlen, 10, 'left');
6498 $trail = chop_str($trail, $contextlen, 10, 'right');
6500 $lead = esc_html($lead);
6501 $match = esc_html($match);
6502 $trail = esc_html($trail);
6504 print "$lead<span class=\"match\">$match</span>$trail<br />";
6507 print "</td>\n" .
6508 "<td class=\"link\">" .
6509 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6510 " | " .
6511 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6512 " | " .
6513 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6514 print "</td>\n" .
6515 "</tr>\n";
6517 if (defined $extra) {
6518 print "<tr>\n" .
6519 "<td colspan=\"3\">$extra</td>\n" .
6520 "</tr>\n";
6522 print "</table>\n";
6525 ## ======================================================================
6526 ## ======================================================================
6527 ## actions
6529 sub git_project_list {
6530 my $order = $input_params{'order'};
6531 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6532 die_error(400, "Unknown order parameter");
6535 my @list = git_get_projects_list($project_filter, $strict_export);
6536 if (!@list) {
6537 die_error(404, "No projects found");
6540 git_header_html();
6541 if (defined $home_text && -f $home_text) {
6542 print "<div class=\"index_include\">\n";
6543 insert_file($home_text);
6544 print "</div>\n";
6547 git_project_search_form($searchtext, $search_use_regexp);
6548 git_project_list_body(\@list, $order);
6549 git_footer_html();
6552 sub git_forks {
6553 my $order = $input_params{'order'};
6554 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6555 die_error(400, "Unknown order parameter");
6558 my $filter = $project;
6559 $filter =~ s/\.git$//;
6560 my @list = git_get_projects_list($filter);
6561 if (!@list) {
6562 die_error(404, "No forks found");
6565 git_header_html();
6566 git_print_page_nav('','');
6567 git_print_header_div('summary', "$project forks");
6568 git_project_list_body(\@list, $order);
6569 git_footer_html();
6572 sub git_project_index {
6573 my @projects = git_get_projects_list($project_filter, $strict_export);
6574 if (!@projects) {
6575 die_error(404, "No projects found");
6578 print $cgi->header(
6579 -type => 'text/plain',
6580 -charset => 'utf-8',
6581 -content_disposition => 'inline; filename="index.aux"');
6583 foreach my $pr (@projects) {
6584 if (!exists $pr->{'owner'}) {
6585 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6588 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6589 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6590 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6591 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6592 $path =~ s/ /\+/g;
6593 $owner =~ s/ /\+/g;
6595 print "$path $owner\n";
6599 sub git_summary {
6600 my $descr = git_get_project_description($project) || "none";
6601 my %co = parse_commit("HEAD");
6602 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6603 my $head = $co{'id'};
6604 my $remote_heads = gitweb_check_feature('remote_heads');
6606 my $owner = git_get_project_owner($project);
6608 my $refs = git_get_references();
6609 # These get_*_list functions return one more to allow us to see if
6610 # there are more ...
6611 my @taglist = git_get_tags_list(16);
6612 my @headlist = git_get_heads_list(16);
6613 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6614 my @forklist;
6615 my $check_forks = gitweb_check_feature('forks');
6617 if ($check_forks) {
6618 # find forks of a project
6619 my $filter = $project;
6620 $filter =~ s/\.git$//;
6621 @forklist = git_get_projects_list($filter);
6622 # filter out forks of forks
6623 @forklist = filter_forks_from_projects_list(\@forklist)
6624 if (@forklist);
6627 git_header_html();
6628 git_print_page_nav('summary','', $head);
6630 print "<div class=\"title\">&nbsp;</div>\n";
6631 print "<table class=\"projects_list\">\n" .
6632 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6633 if ($owner and not $omit_owner) {
6634 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . email_obfuscate($owner) . "</td></tr>\n";
6636 if (defined $cd{'rfc2822'}) {
6637 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6638 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6641 # use per project git URL list in $projectroot/$project/cloneurl
6642 # or make project git URL from git base URL and project name
6643 my $url_tag = "URL";
6644 my @url_list = git_get_project_url_list($project);
6645 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6646 foreach my $git_url (@url_list) {
6647 next unless $git_url;
6648 print format_repo_url($url_tag, $git_url);
6649 $url_tag = "";
6652 # Tag cloud
6653 my $show_ctags = gitweb_check_feature('ctags');
6654 if ($show_ctags) {
6655 my $ctags = git_get_project_ctags($project);
6656 if (%$ctags) {
6657 # without ability to add tags, don't show if there are none
6658 my $cloud = git_populate_project_tagcloud($ctags);
6659 print "<tr id=\"metadata_ctags\">" .
6660 "<td>content tags</td>" .
6661 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6662 "</tr>\n";
6666 print "</table>\n";
6668 # If XSS prevention is on, we don't include README.html.
6669 # TODO: Allow a readme in some safe format.
6670 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6671 print "<div class=\"title\">readme</div>\n" .
6672 "<div class=\"readme\">\n";
6673 insert_file("$projectroot/$project/README.html");
6674 print "\n</div>\n"; # class="readme"
6677 # we need to request one more than 16 (0..15) to check if
6678 # those 16 are all
6679 my @commitlist = $head ? parse_commits($head, 17) : ();
6680 if (@commitlist) {
6681 git_print_header_div('shortlog');
6682 git_shortlog_body(\@commitlist, 0, 15, $refs,
6683 $#commitlist <= 15 ? undef :
6684 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6687 if (@taglist) {
6688 git_print_header_div('tags');
6689 git_tags_body(\@taglist, 0, 15,
6690 $#taglist <= 15 ? undef :
6691 $cgi->a({-href => href(action=>"tags")}, "..."));
6694 if (@headlist) {
6695 git_print_header_div('heads');
6696 git_heads_body(\@headlist, $head, 0, 15,
6697 $#headlist <= 15 ? undef :
6698 $cgi->a({-href => href(action=>"heads")}, "..."));
6701 if (%remotedata) {
6702 git_print_header_div('remotes');
6703 git_remotes_body(\%remotedata, 15, $head);
6706 if (@forklist) {
6707 git_print_header_div('forks');
6708 git_project_list_body(\@forklist, 'age', 0, 15,
6709 $#forklist <= 15 ? undef :
6710 $cgi->a({-href => href(action=>"forks")}, "..."),
6711 'no_header');
6714 git_footer_html();
6717 sub git_tag {
6718 my %tag = parse_tag($hash);
6720 if (! %tag) {
6721 die_error(404, "Unknown tag object");
6724 my $head = git_get_head_hash($project);
6725 git_header_html();
6726 git_print_page_nav('','', $head,undef,$head);
6727 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6728 print "<div class=\"title_text\">\n" .
6729 "<table class=\"object_header\">\n" .
6730 "<tr>\n" .
6731 "<td>object</td>\n" .
6732 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6733 $tag{'object'}) . "</td>\n" .
6734 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6735 $tag{'type'}) . "</td>\n" .
6736 "</tr>\n";
6737 if (defined($tag{'author'})) {
6738 git_print_authorship_rows(\%tag, 'author');
6740 print "</table>\n\n" .
6741 "</div>\n";
6742 print "<div class=\"page_body\">";
6743 my $comment = $tag{'comment'};
6744 foreach my $line (@$comment) {
6745 chomp $line;
6746 print esc_html($line, -nbsp=>1) . "<br/>\n";
6748 print "</div>\n";
6749 git_footer_html();
6752 sub git_blame_common {
6753 my $format = shift || 'porcelain';
6754 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6755 $format = 'incremental';
6756 $action = 'blame_incremental'; # for page title etc
6759 # permissions
6760 gitweb_check_feature('blame')
6761 or die_error(403, "Blame view not allowed");
6763 # error checking
6764 die_error(400, "No file name given") unless $file_name;
6765 $hash_base ||= git_get_head_hash($project);
6766 die_error(404, "Couldn't find base commit") unless $hash_base;
6767 my %co = parse_commit($hash_base)
6768 or die_error(404, "Commit not found");
6769 my $ftype = "blob";
6770 if (!defined $hash) {
6771 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6772 or die_error(404, "Error looking up file");
6773 } else {
6774 $ftype = git_get_type($hash);
6775 if ($ftype !~ "blob") {
6776 die_error(400, "Object is not a blob");
6780 my $fd;
6781 if ($format eq 'incremental') {
6782 # get file contents (as base)
6783 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6784 or die_error(500, "Open git-cat-file failed");
6785 } elsif ($format eq 'data') {
6786 # run git-blame --incremental
6787 open $fd, "-|", git_cmd(), "blame", "--incremental",
6788 $hash_base, "--", $file_name
6789 or die_error(500, "Open git-blame --incremental failed");
6790 } else {
6791 # run git-blame --porcelain
6792 open $fd, "-|", git_cmd(), "blame", '-p',
6793 $hash_base, '--', $file_name
6794 or die_error(500, "Open git-blame --porcelain failed");
6796 binmode $fd, ':utf8';
6798 # incremental blame data returns early
6799 if ($format eq 'data') {
6800 print $cgi->header(
6801 -type=>"text/plain", -charset => "utf-8",
6802 -status=> "200 OK");
6803 local $| = 1; # output autoflush
6804 while (my $line = <$fd>) {
6805 print to_utf8($line);
6807 close $fd
6808 or print "ERROR $!\n";
6810 print 'END';
6811 if (defined $t0 && gitweb_check_feature('timed')) {
6812 print ' '.
6813 tv_interval($t0, [ gettimeofday() ]).
6814 ' '.$number_of_git_cmds;
6816 print "\n";
6818 return;
6821 # page header
6822 git_header_html();
6823 my $formats_nav =
6824 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6825 "blob") .
6826 " | ";
6827 if ($format eq 'incremental') {
6828 $formats_nav .=
6829 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6830 "blame") . " (non-incremental)";
6831 } else {
6832 $formats_nav .=
6833 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6834 "blame") . " (incremental)";
6836 $formats_nav .=
6837 " | " .
6838 $cgi->a({-href => href(action=>"history", -replay=>1)},
6839 "history") .
6840 " | " .
6841 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6842 "HEAD");
6843 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6844 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6845 git_print_page_path($file_name, $ftype, $hash_base);
6847 # page body
6848 if ($format eq 'incremental') {
6849 print "<noscript>\n<div class=\"error\"><center><b>\n".
6850 "This page requires JavaScript to run.\n Use ".
6851 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6852 'this page').
6853 " instead.\n".
6854 "</b></center></div>\n</noscript>\n";
6856 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6859 print qq!<div class="page_body">\n!;
6860 print qq!<div id="progress_info">... / ...</div>\n!
6861 if ($format eq 'incremental');
6862 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6863 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6864 qq!<thead>\n!.
6865 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6866 qq!</thead>\n!.
6867 qq!<tbody>\n!;
6869 my @rev_color = qw(light dark);
6870 my $num_colors = scalar(@rev_color);
6871 my $current_color = 0;
6873 if ($format eq 'incremental') {
6874 my $color_class = $rev_color[$current_color];
6876 #contents of a file
6877 my $linenr = 0;
6878 LINE:
6879 while (my $line = <$fd>) {
6880 chomp $line;
6881 $linenr++;
6883 print qq!<tr id="l$linenr" class="$color_class">!.
6884 qq!<td class="sha1"><a href=""> </a></td>!.
6885 qq!<td class="linenr">!.
6886 qq!<a class="linenr" href="">$linenr</a></td>!;
6887 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6888 print qq!</tr>\n!;
6891 } else { # porcelain, i.e. ordinary blame
6892 my %metainfo = (); # saves information about commits
6894 # blame data
6895 LINE:
6896 while (my $line = <$fd>) {
6897 chomp $line;
6898 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6899 # no <lines in group> for subsequent lines in group of lines
6900 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6901 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6902 if (!exists $metainfo{$full_rev}) {
6903 $metainfo{$full_rev} = { 'nprevious' => 0 };
6905 my $meta = $metainfo{$full_rev};
6906 my $data;
6907 while ($data = <$fd>) {
6908 chomp $data;
6909 last if ($data =~ s/^\t//); # contents of line
6910 if ($data =~ /^(\S+)(?: (.*))?$/) {
6911 $meta->{$1} = $2 unless exists $meta->{$1};
6913 if ($data =~ /^previous /) {
6914 $meta->{'nprevious'}++;
6917 my $short_rev = substr($full_rev, 0, 8);
6918 my $author = $meta->{'author'};
6919 my %date =
6920 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6921 my $date = $date{'iso-tz'};
6922 if ($group_size) {
6923 $current_color = ($current_color + 1) % $num_colors;
6925 my $tr_class = $rev_color[$current_color];
6926 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6927 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6928 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6929 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6930 if ($group_size) {
6931 print "<td class=\"sha1\"";
6932 print " title=\"". esc_html($author) . ", $date\"";
6933 print " rowspan=\"$group_size\"" if ($group_size > 1);
6934 print ">";
6935 print $cgi->a({-href => href(action=>"commit",
6936 hash=>$full_rev,
6937 file_name=>$file_name)},
6938 esc_html($short_rev));
6939 if ($group_size >= 2) {
6940 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6941 if (@author_initials) {
6942 print "<br />" .
6943 esc_html(join('', @author_initials));
6944 # or join('.', ...)
6947 print "</td>\n";
6949 # 'previous' <sha1 of parent commit> <filename at commit>
6950 if (exists $meta->{'previous'} &&
6951 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6952 $meta->{'parent'} = $1;
6953 $meta->{'file_parent'} = unquote($2);
6955 my $linenr_commit =
6956 exists($meta->{'parent'}) ?
6957 $meta->{'parent'} : $full_rev;
6958 my $linenr_filename =
6959 exists($meta->{'file_parent'}) ?
6960 $meta->{'file_parent'} : unquote($meta->{'filename'});
6961 my $blamed = href(action => 'blame',
6962 file_name => $linenr_filename,
6963 hash_base => $linenr_commit);
6964 print "<td class=\"linenr\">";
6965 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6966 -class => "linenr" },
6967 esc_html($lineno));
6968 print "</td>";
6969 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6970 print "</tr>\n";
6971 } # end while
6975 # footer
6976 print "</tbody>\n".
6977 "</table>\n"; # class="blame"
6978 print "</div>\n"; # class="blame_body"
6979 close $fd
6980 or print "Reading blob failed\n";
6982 git_footer_html();
6985 sub git_blame {
6986 git_blame_common();
6989 sub git_blame_incremental {
6990 git_blame_common('incremental');
6993 sub git_blame_data {
6994 git_blame_common('data');
6997 sub git_tags {
6998 my $head = git_get_head_hash($project);
6999 git_header_html();
7000 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
7001 git_print_header_div('summary', $project);
7003 my @tagslist = git_get_tags_list();
7004 if (@tagslist) {
7005 git_tags_body(\@tagslist);
7007 git_footer_html();
7010 sub git_heads {
7011 my $head = git_get_head_hash($project);
7012 git_header_html();
7013 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
7014 git_print_header_div('summary', $project);
7016 my @headslist = git_get_heads_list();
7017 if (@headslist) {
7018 git_heads_body(\@headslist, $head);
7020 git_footer_html();
7023 # used both for single remote view and for list of all the remotes
7024 sub git_remotes {
7025 gitweb_check_feature('remote_heads')
7026 or die_error(403, "Remote heads view is disabled");
7028 my $head = git_get_head_hash($project);
7029 my $remote = $input_params{'hash'};
7031 my $remotedata = git_get_remotes_list($remote);
7032 die_error(500, "Unable to get remote information") unless defined $remotedata;
7034 unless (%$remotedata) {
7035 die_error(404, defined $remote ?
7036 "Remote $remote not found" :
7037 "No remotes found");
7040 git_header_html(undef, undef, -action_extra => $remote);
7041 git_print_page_nav('', '', $head, undef, $head,
7042 format_ref_views($remote ? '' : 'remotes'));
7044 fill_remote_heads($remotedata);
7045 if (defined $remote) {
7046 git_print_header_div('remotes', "$remote remote for $project");
7047 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7048 } else {
7049 git_print_header_div('summary', "$project remotes");
7050 git_remotes_body($remotedata, undef, $head);
7053 git_footer_html();
7056 sub git_blob_plain {
7057 my $type = shift;
7058 my $expires;
7060 if (!defined $hash) {
7061 if (defined $file_name) {
7062 my $base = $hash_base || git_get_head_hash($project);
7063 $hash = git_get_hash_by_path($base, $file_name, "blob")
7064 or die_error(404, "Cannot find file");
7065 } else {
7066 die_error(400, "No file name defined");
7068 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7069 # blobs defined by non-textual hash id's can be cached
7070 $expires = "+1d";
7073 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7074 or die_error(500, "Open git-cat-file blob '$hash' failed");
7076 # content-type (can include charset)
7077 $type = blob_contenttype($fd, $file_name, $type);
7079 # "save as" filename, even when no $file_name is given
7080 my $save_as = "$hash";
7081 if (defined $file_name) {
7082 $save_as = $file_name;
7083 } elsif ($type =~ m/^text\//) {
7084 $save_as .= '.txt';
7087 # With XSS prevention on, blobs of all types except a few known safe
7088 # ones are served with "Content-Disposition: attachment" to make sure
7089 # they don't run in our security domain. For certain image types,
7090 # blob view writes an <img> tag referring to blob_plain view, and we
7091 # want to be sure not to break that by serving the image as an
7092 # attachment (though Firefox 3 doesn't seem to care).
7093 my $sandbox = $prevent_xss &&
7094 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7096 # serve text/* as text/plain
7097 if ($prevent_xss &&
7098 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7099 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7100 my $rest = $1;
7101 $rest = defined $rest ? $rest : '';
7102 $type = "text/plain$rest";
7105 print $cgi->header(
7106 -type => $type,
7107 -expires => $expires,
7108 -content_disposition =>
7109 ($sandbox ? 'attachment' : 'inline')
7110 . '; filename="' . $save_as . '"');
7111 local $/ = undef;
7112 binmode STDOUT, ':raw';
7113 print <$fd>;
7114 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7115 close $fd;
7118 sub git_blob {
7119 my $expires;
7121 if (!defined $hash) {
7122 if (defined $file_name) {
7123 my $base = $hash_base || git_get_head_hash($project);
7124 $hash = git_get_hash_by_path($base, $file_name, "blob")
7125 or die_error(404, "Cannot find file");
7126 } else {
7127 die_error(400, "No file name defined");
7129 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7130 # blobs defined by non-textual hash id's can be cached
7131 $expires = "+1d";
7134 my $have_blame = gitweb_check_feature('blame');
7135 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7136 or die_error(500, "Couldn't cat $file_name, $hash");
7137 my $mimetype = blob_mimetype($fd, $file_name);
7138 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7139 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7140 close $fd;
7141 return git_blob_plain($mimetype);
7143 # we can have blame only for text/* mimetype
7144 $have_blame &&= ($mimetype =~ m!^text/!);
7146 my $highlight = gitweb_check_feature('highlight');
7147 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7148 $fd = run_highlighter($fd, $highlight, $syntax)
7149 if $syntax;
7151 git_header_html(undef, $expires);
7152 my $formats_nav = '';
7153 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7154 if (defined $file_name) {
7155 if ($have_blame) {
7156 $formats_nav .=
7157 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7158 "blame") .
7159 " | ";
7161 $formats_nav .=
7162 $cgi->a({-href => href(action=>"history", -replay=>1)},
7163 "history") .
7164 " | " .
7165 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7166 "raw") .
7167 " | " .
7168 $cgi->a({-href => href(action=>"blob",
7169 hash_base=>"HEAD", file_name=>$file_name)},
7170 "HEAD");
7171 } else {
7172 $formats_nav .=
7173 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7174 "raw");
7176 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7177 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7178 } else {
7179 print "<div class=\"page_nav\">\n" .
7180 "<br/><br/></div>\n" .
7181 "<div class=\"title\">".esc_html($hash)."</div>\n";
7183 git_print_page_path($file_name, "blob", $hash_base);
7184 print "<div class=\"page_body\">\n";
7185 if ($mimetype =~ m!^image/!) {
7186 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7187 if ($file_name) {
7188 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7190 print qq! src="! .
7191 href(action=>"blob_plain", hash=>$hash,
7192 hash_base=>$hash_base, file_name=>$file_name) .
7193 qq!" />\n!;
7194 } else {
7195 my $nr;
7196 while (my $line = <$fd>) {
7197 chomp $line;
7198 $nr++;
7199 $line = untabify($line);
7200 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7201 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7202 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7205 close $fd
7206 or print "Reading blob failed.\n";
7207 print "</div>";
7208 git_footer_html();
7211 sub git_tree {
7212 if (!defined $hash_base) {
7213 $hash_base = "HEAD";
7215 if (!defined $hash) {
7216 if (defined $file_name) {
7217 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7218 } else {
7219 $hash = $hash_base;
7222 die_error(404, "No such tree") unless defined($hash);
7224 my $show_sizes = gitweb_check_feature('show-sizes');
7225 my $have_blame = gitweb_check_feature('blame');
7227 my @entries = ();
7229 local $/ = "\0";
7230 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7231 ($show_sizes ? '-l' : ()), @extra_options, $hash
7232 or die_error(500, "Open git-ls-tree failed");
7233 @entries = map { chomp; $_ } <$fd>;
7234 close $fd
7235 or die_error(404, "Reading tree failed");
7238 my $refs = git_get_references();
7239 my $ref = format_ref_marker($refs, $hash_base);
7240 git_header_html();
7241 my $basedir = '';
7242 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7243 my @views_nav = ();
7244 if (defined $file_name) {
7245 push @views_nav,
7246 $cgi->a({-href => href(action=>"history", -replay=>1)},
7247 "history"),
7248 $cgi->a({-href => href(action=>"tree",
7249 hash_base=>"HEAD", file_name=>$file_name)},
7250 "HEAD"),
7252 my $snapshot_links = format_snapshot_links($hash);
7253 if (defined $snapshot_links) {
7254 # FIXME: Should be available when we have no hash base as well.
7255 push @views_nav, $snapshot_links;
7257 git_print_page_nav('tree','', $hash_base, undef, undef,
7258 join(' | ', @views_nav));
7259 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7260 } else {
7261 undef $hash_base;
7262 print "<div class=\"page_nav\">\n";
7263 print "<br/><br/></div>\n";
7264 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7266 if (defined $file_name) {
7267 $basedir = $file_name;
7268 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7269 $basedir .= '/';
7271 git_print_page_path($file_name, 'tree', $hash_base);
7273 print "<div class=\"page_body\">\n";
7274 print "<table class=\"tree\">\n";
7275 my $alternate = 1;
7276 # '..' (top directory) link if possible
7277 if (defined $hash_base &&
7278 defined $file_name && $file_name =~ m![^/]+$!) {
7279 if ($alternate) {
7280 print "<tr class=\"dark\">\n";
7281 } else {
7282 print "<tr class=\"light\">\n";
7284 $alternate ^= 1;
7286 my $up = $file_name;
7287 $up =~ s!/?[^/]+$!!;
7288 undef $up unless $up;
7289 # based on git_print_tree_entry
7290 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7291 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7292 print '<td class="list">';
7293 print $cgi->a({-href => href(action=>"tree",
7294 hash_base=>$hash_base,
7295 file_name=>$up)},
7296 "..");
7297 print "</td>\n";
7298 print "<td class=\"link\"></td>\n";
7300 print "</tr>\n";
7302 foreach my $line (@entries) {
7303 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7305 if ($alternate) {
7306 print "<tr class=\"dark\">\n";
7307 } else {
7308 print "<tr class=\"light\">\n";
7310 $alternate ^= 1;
7312 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7314 print "</tr>\n";
7316 print "</table>\n" .
7317 "</div>";
7318 git_footer_html();
7321 sub sanitize_for_filename {
7322 my $name = shift;
7324 $name =~ s!/!-!g;
7325 $name =~ s/[^[:alnum:]_.-]//g;
7327 return $name;
7330 sub snapshot_name {
7331 my ($project, $hash) = @_;
7333 # path/to/project.git -> project
7334 # path/to/project/.git -> project
7335 my $name = to_utf8($project);
7336 $name =~ s,([^/])/*\.git$,$1,;
7337 $name = sanitize_for_filename(basename($name));
7339 my $ver = $hash;
7340 if ($hash =~ /^[0-9a-fA-F]+$/) {
7341 # shorten SHA-1 hash
7342 my $full_hash = git_get_full_hash($project, $hash);
7343 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7344 $ver = git_get_short_hash($project, $hash);
7346 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7347 # tags don't need shortened SHA-1 hash
7348 $ver = $1;
7349 } else {
7350 # branches and other need shortened SHA-1 hash
7351 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7352 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7353 my $ref_dir = (defined $1) ? $1 : '';
7354 $ver = $2;
7356 $ref_dir = sanitize_for_filename($ref_dir);
7357 # for refs neither in heads nor remotes we want to
7358 # add a ref dir to archive name
7359 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7360 $ver = $ref_dir . '-' . $ver;
7363 $ver .= '-' . git_get_short_hash($project, $hash);
7365 # special case of sanitization for filename - we change
7366 # slashes to dots instead of dashes
7367 # in case of hierarchical branch names
7368 $ver =~ s!/!.!g;
7369 $ver =~ s/[^[:alnum:]_.-]//g;
7371 # name = project-version_string
7372 $name = "$name-$ver";
7374 return wantarray ? ($name, $name) : $name;
7377 sub exit_if_unmodified_since {
7378 my ($latest_epoch) = @_;
7379 our $cgi;
7381 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7382 if (defined $if_modified) {
7383 my $since;
7384 if (eval { require HTTP::Date; 1; }) {
7385 $since = HTTP::Date::str2time($if_modified);
7386 } elsif (eval { require Time::ParseDate; 1; }) {
7387 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7389 if (defined $since && $latest_epoch <= $since) {
7390 my %latest_date = parse_date($latest_epoch);
7391 print $cgi->header(
7392 -last_modified => $latest_date{'rfc2822'},
7393 -status => '304 Not Modified');
7394 goto DONE_GITWEB;
7399 sub git_snapshot {
7400 my $format = $input_params{'snapshot_format'};
7401 if (!@snapshot_fmts) {
7402 die_error(403, "Snapshots not allowed");
7404 # default to first supported snapshot format
7405 $format ||= $snapshot_fmts[0];
7406 if ($format !~ m/^[a-z0-9]+$/) {
7407 die_error(400, "Invalid snapshot format parameter");
7408 } elsif (!exists($known_snapshot_formats{$format})) {
7409 die_error(400, "Unknown snapshot format");
7410 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7411 die_error(403, "Snapshot format not allowed");
7412 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7413 die_error(403, "Unsupported snapshot format");
7416 my $type = git_get_type("$hash^{}");
7417 if (!$type) {
7418 die_error(404, 'Object does not exist');
7419 } elsif ($type eq 'blob') {
7420 die_error(400, 'Object is not a tree-ish');
7423 my ($name, $prefix) = snapshot_name($project, $hash);
7424 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7426 my %co = parse_commit($hash);
7427 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7429 my $cmd = quote_command(
7430 git_cmd(), 'archive',
7431 "--format=$known_snapshot_formats{$format}{'format'}",
7432 "--prefix=$prefix/", $hash);
7433 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7434 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7437 $filename =~ s/(["\\])/\\$1/g;
7438 my %latest_date;
7439 if (%co) {
7440 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7443 print $cgi->header(
7444 -type => $known_snapshot_formats{$format}{'type'},
7445 -content_disposition => 'inline; filename="' . $filename . '"',
7446 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7447 -status => '200 OK');
7449 open my $fd, "-|", $cmd
7450 or die_error(500, "Execute git-archive failed");
7451 binmode STDOUT, ':raw';
7452 print <$fd>;
7453 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7454 close $fd;
7457 sub git_log_generic {
7458 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7460 my $head = git_get_head_hash($project);
7461 if (!defined $base) {
7462 $base = $head;
7464 if (!defined $page) {
7465 $page = 0;
7467 my $refs = git_get_references();
7469 my $commit_hash = $base;
7470 if (defined $parent) {
7471 $commit_hash = "$parent..$base";
7473 my @commitlist =
7474 parse_commits($commit_hash, 101, (100 * $page),
7475 defined $file_name ? ($file_name, "--full-history") : ());
7477 my $ftype;
7478 if (!defined $file_hash && defined $file_name) {
7479 # some commits could have deleted file in question,
7480 # and not have it in tree, but one of them has to have it
7481 for (my $i = 0; $i < @commitlist; $i++) {
7482 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7483 last if defined $file_hash;
7486 if (defined $file_hash) {
7487 $ftype = git_get_type($file_hash);
7489 if (defined $file_name && !defined $ftype) {
7490 die_error(500, "Unknown type of object");
7492 my %co;
7493 if (defined $file_name) {
7494 %co = parse_commit($base)
7495 or die_error(404, "Unknown commit object");
7499 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7500 my $next_link = '';
7501 if ($#commitlist >= 100) {
7502 $next_link =
7503 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7504 -accesskey => "n", -title => "Alt-n"}, "next");
7506 my $patch_max = gitweb_get_feature('patches');
7507 if ($patch_max && !defined $file_name) {
7508 if ($patch_max < 0 || @commitlist <= $patch_max) {
7509 $paging_nav .= " &sdot; " .
7510 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7511 "patches");
7515 git_header_html();
7516 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7517 if (defined $file_name) {
7518 git_print_header_div('commit', esc_html($co{'title'}), $base);
7519 } else {
7520 git_print_header_div('summary', $project)
7522 git_print_page_path($file_name, $ftype, $hash_base)
7523 if (defined $file_name);
7525 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7526 $file_name, $file_hash, $ftype);
7528 git_footer_html();
7531 sub git_log {
7532 git_log_generic('log', \&git_log_body,
7533 $hash, $hash_parent);
7536 sub git_commit {
7537 $hash ||= $hash_base || "HEAD";
7538 my %co = parse_commit($hash)
7539 or die_error(404, "Unknown commit object");
7541 my $parent = $co{'parent'};
7542 my $parents = $co{'parents'}; # listref
7544 # we need to prepare $formats_nav before any parameter munging
7545 my $formats_nav;
7546 if (!defined $parent) {
7547 # --root commitdiff
7548 $formats_nav .= '(initial)';
7549 } elsif (@$parents == 1) {
7550 # single parent commit
7551 $formats_nav .=
7552 '(parent: ' .
7553 $cgi->a({-href => href(action=>"commit",
7554 hash=>$parent)},
7555 esc_html(substr($parent, 0, 7))) .
7556 ')';
7557 } else {
7558 # merge commit
7559 $formats_nav .=
7560 '(merge: ' .
7561 join(' ', map {
7562 $cgi->a({-href => href(action=>"commit",
7563 hash=>$_)},
7564 esc_html(substr($_, 0, 7)));
7565 } @$parents ) .
7566 ')';
7568 if (gitweb_check_feature('patches') && @$parents <= 1) {
7569 $formats_nav .= " | " .
7570 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7571 "patch");
7574 if (!defined $parent) {
7575 $parent = "--root";
7577 my @difftree;
7578 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7579 @diff_opts,
7580 (@$parents <= 1 ? $parent : '-c'),
7581 $hash, "--"
7582 or die_error(500, "Open git-diff-tree failed");
7583 @difftree = map { chomp; $_ } <$fd>;
7584 close $fd or die_error(404, "Reading git-diff-tree failed");
7586 # non-textual hash id's can be cached
7587 my $expires;
7588 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7589 $expires = "+1d";
7591 my $refs = git_get_references();
7592 my $ref = format_ref_marker($refs, $co{'id'});
7594 git_header_html(undef, $expires);
7595 git_print_page_nav('commit', '',
7596 $hash, $co{'tree'}, $hash,
7597 $formats_nav);
7599 if (defined $co{'parent'}) {
7600 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7601 } else {
7602 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7604 print "<div class=\"title_text\">\n" .
7605 "<table class=\"object_header\">\n";
7606 git_print_authorship_rows(\%co);
7607 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7608 print "<tr>" .
7609 "<td>tree</td>" .
7610 "<td class=\"sha1\">" .
7611 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7612 class => "list"}, $co{'tree'}) .
7613 "</td>" .
7614 "<td class=\"link\">" .
7615 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7616 "tree");
7617 my $snapshot_links = format_snapshot_links($hash);
7618 if (defined $snapshot_links) {
7619 print " | " . $snapshot_links;
7621 print "</td>" .
7622 "</tr>\n";
7624 foreach my $par (@$parents) {
7625 print "<tr>" .
7626 "<td>parent</td>" .
7627 "<td class=\"sha1\">" .
7628 $cgi->a({-href => href(action=>"commit", hash=>$par),
7629 class => "list"}, $par) .
7630 "</td>" .
7631 "<td class=\"link\">" .
7632 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7633 " | " .
7634 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7635 "</td>" .
7636 "</tr>\n";
7638 print "</table>".
7639 "</div>\n";
7641 print "<div class=\"page_body\">\n";
7642 git_print_log($co{'comment'});
7643 print "</div>\n";
7645 git_difftree_body(\@difftree, $hash, @$parents);
7647 git_footer_html();
7650 sub git_object {
7651 # object is defined by:
7652 # - hash or hash_base alone
7653 # - hash_base and file_name
7654 my $type;
7656 # - hash or hash_base alone
7657 if ($hash || ($hash_base && !defined $file_name)) {
7658 my $object_id = $hash || $hash_base;
7660 open my $fd, "-|", quote_command(
7661 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7662 or die_error(404, "Object does not exist");
7663 $type = <$fd>;
7664 chomp $type;
7665 close $fd
7666 or die_error(404, "Object does not exist");
7668 # - hash_base and file_name
7669 } elsif ($hash_base && defined $file_name) {
7670 $file_name =~ s,/+$,,;
7672 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7673 or die_error(404, "Base object does not exist");
7675 # here errors should not happen
7676 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7677 or die_error(500, "Open git-ls-tree failed");
7678 my $line = <$fd>;
7679 close $fd;
7681 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7682 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7683 die_error(404, "File or directory for given base does not exist");
7685 $type = $2;
7686 $hash = $3;
7687 } else {
7688 die_error(400, "Not enough information to find object");
7691 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7692 hash=>$hash, hash_base=>$hash_base,
7693 file_name=>$file_name),
7694 -status => '302 Found');
7697 sub git_blobdiff {
7698 my $format = shift || 'html';
7699 my $diff_style = $input_params{'diff_style'} || 'inline';
7701 my $fd;
7702 my @difftree;
7703 my %diffinfo;
7704 my $expires;
7706 # preparing $fd and %diffinfo for git_patchset_body
7707 # new style URI
7708 if (defined $hash_base && defined $hash_parent_base) {
7709 if (defined $file_name) {
7710 # read raw output
7711 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7712 $hash_parent_base, $hash_base,
7713 "--", (defined $file_parent ? $file_parent : ()), $file_name
7714 or die_error(500, "Open git-diff-tree failed");
7715 @difftree = map { chomp; $_ } <$fd>;
7716 close $fd
7717 or die_error(404, "Reading git-diff-tree failed");
7718 @difftree
7719 or die_error(404, "Blob diff not found");
7721 } elsif (defined $hash &&
7722 $hash =~ /[0-9a-fA-F]{40}/) {
7723 # try to find filename from $hash
7725 # read filtered raw output
7726 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7727 $hash_parent_base, $hash_base, "--"
7728 or die_error(500, "Open git-diff-tree failed");
7729 @difftree =
7730 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7731 # $hash == to_id
7732 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7733 map { chomp; $_ } <$fd>;
7734 close $fd
7735 or die_error(404, "Reading git-diff-tree failed");
7736 @difftree
7737 or die_error(404, "Blob diff not found");
7739 } else {
7740 die_error(400, "Missing one of the blob diff parameters");
7743 if (@difftree > 1) {
7744 die_error(400, "Ambiguous blob diff specification");
7747 %diffinfo = parse_difftree_raw_line($difftree[0]);
7748 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7749 $file_name ||= $diffinfo{'to_file'};
7751 $hash_parent ||= $diffinfo{'from_id'};
7752 $hash ||= $diffinfo{'to_id'};
7754 # non-textual hash id's can be cached
7755 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7756 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7757 $expires = '+1d';
7760 # open patch output
7761 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7762 '-p', ($format eq 'html' ? "--full-index" : ()),
7763 $hash_parent_base, $hash_base,
7764 "--", (defined $file_parent ? $file_parent : ()), $file_name
7765 or die_error(500, "Open git-diff-tree failed");
7768 # old/legacy style URI -- not generated anymore since 1.4.3.
7769 if (!%diffinfo) {
7770 die_error('404 Not Found', "Missing one of the blob diff parameters")
7773 # header
7774 if ($format eq 'html') {
7775 my $formats_nav =
7776 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7777 "raw");
7778 $formats_nav .= diff_style_nav($diff_style);
7779 git_header_html(undef, $expires);
7780 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7781 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7782 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7783 } else {
7784 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7785 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7787 if (defined $file_name) {
7788 git_print_page_path($file_name, "blob", $hash_base);
7789 } else {
7790 print "<div class=\"page_path\"></div>\n";
7793 } elsif ($format eq 'plain') {
7794 print $cgi->header(
7795 -type => 'text/plain',
7796 -charset => 'utf-8',
7797 -expires => $expires,
7798 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7800 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7802 } else {
7803 die_error(400, "Unknown blobdiff format");
7806 # patch
7807 if ($format eq 'html') {
7808 print "<div class=\"page_body\">\n";
7810 git_patchset_body($fd, $diff_style,
7811 [ \%diffinfo ], $hash_base, $hash_parent_base);
7812 close $fd;
7814 print "</div>\n"; # class="page_body"
7815 git_footer_html();
7817 } else {
7818 while (my $line = <$fd>) {
7819 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7820 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7822 print $line;
7824 last if $line =~ m!^\+\+\+!;
7826 local $/ = undef;
7827 print <$fd>;
7828 close $fd;
7832 sub git_blobdiff_plain {
7833 git_blobdiff('plain');
7836 # assumes that it is added as later part of already existing navigation,
7837 # so it returns "| foo | bar" rather than just "foo | bar"
7838 sub diff_style_nav {
7839 my ($diff_style, $is_combined) = @_;
7840 $diff_style ||= 'inline';
7842 return "" if ($is_combined);
7844 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7845 my %styles = @styles;
7846 @styles =
7847 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7849 return join '',
7850 map { " | ".$_ }
7851 map {
7852 $_ eq $diff_style ? $styles{$_} :
7853 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7854 } @styles;
7857 sub git_commitdiff {
7858 my %params = @_;
7859 my $format = $params{-format} || 'html';
7860 my $diff_style = $input_params{'diff_style'} || 'inline';
7862 my ($patch_max) = gitweb_get_feature('patches');
7863 if ($format eq 'patch') {
7864 die_error(403, "Patch view not allowed") unless $patch_max;
7867 $hash ||= $hash_base || "HEAD";
7868 my %co = parse_commit($hash)
7869 or die_error(404, "Unknown commit object");
7871 # choose format for commitdiff for merge
7872 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7873 $hash_parent = '--cc';
7875 # we need to prepare $formats_nav before almost any parameter munging
7876 my $formats_nav;
7877 if ($format eq 'html') {
7878 $formats_nav =
7879 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7880 "raw");
7881 if ($patch_max && @{$co{'parents'}} <= 1) {
7882 $formats_nav .= " | " .
7883 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7884 "patch");
7886 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7888 if (defined $hash_parent &&
7889 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7890 # commitdiff with two commits given
7891 my $hash_parent_short = $hash_parent;
7892 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7893 $hash_parent_short = substr($hash_parent, 0, 7);
7895 $formats_nav .=
7896 ' (from';
7897 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7898 if ($co{'parents'}[$i] eq $hash_parent) {
7899 $formats_nav .= ' parent ' . ($i+1);
7900 last;
7903 $formats_nav .= ': ' .
7904 $cgi->a({-href => href(-replay=>1,
7905 hash=>$hash_parent, hash_base=>undef)},
7906 esc_html($hash_parent_short)) .
7907 ')';
7908 } elsif (!$co{'parent'}) {
7909 # --root commitdiff
7910 $formats_nav .= ' (initial)';
7911 } elsif (scalar @{$co{'parents'}} == 1) {
7912 # single parent commit
7913 $formats_nav .=
7914 ' (parent: ' .
7915 $cgi->a({-href => href(-replay=>1,
7916 hash=>$co{'parent'}, hash_base=>undef)},
7917 esc_html(substr($co{'parent'}, 0, 7))) .
7918 ')';
7919 } else {
7920 # merge commit
7921 if ($hash_parent eq '--cc') {
7922 $formats_nav .= ' | ' .
7923 $cgi->a({-href => href(-replay=>1,
7924 hash=>$hash, hash_parent=>'-c')},
7925 'combined');
7926 } else { # $hash_parent eq '-c'
7927 $formats_nav .= ' | ' .
7928 $cgi->a({-href => href(-replay=>1,
7929 hash=>$hash, hash_parent=>'--cc')},
7930 'compact');
7932 $formats_nav .=
7933 ' (merge: ' .
7934 join(' ', map {
7935 $cgi->a({-href => href(-replay=>1,
7936 hash=>$_, hash_base=>undef)},
7937 esc_html(substr($_, 0, 7)));
7938 } @{$co{'parents'}} ) .
7939 ')';
7943 my $hash_parent_param = $hash_parent;
7944 if (!defined $hash_parent_param) {
7945 # --cc for multiple parents, --root for parentless
7946 $hash_parent_param =
7947 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7950 # read commitdiff
7951 my $fd;
7952 my @difftree;
7953 if ($format eq 'html') {
7954 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7955 "--no-commit-id", "--patch-with-raw", "--full-index",
7956 $hash_parent_param, $hash, "--"
7957 or die_error(500, "Open git-diff-tree failed");
7959 while (my $line = <$fd>) {
7960 chomp $line;
7961 # empty line ends raw part of diff-tree output
7962 last unless $line;
7963 push @difftree, scalar parse_difftree_raw_line($line);
7966 } elsif ($format eq 'plain') {
7967 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7968 '-p', $hash_parent_param, $hash, "--"
7969 or die_error(500, "Open git-diff-tree failed");
7970 } elsif ($format eq 'patch') {
7971 # For commit ranges, we limit the output to the number of
7972 # patches specified in the 'patches' feature.
7973 # For single commits, we limit the output to a single patch,
7974 # diverging from the git-format-patch default.
7975 my @commit_spec = ();
7976 if ($hash_parent) {
7977 if ($patch_max > 0) {
7978 push @commit_spec, "-$patch_max";
7980 push @commit_spec, '-n', "$hash_parent..$hash";
7981 } else {
7982 if ($params{-single}) {
7983 push @commit_spec, '-1';
7984 } else {
7985 if ($patch_max > 0) {
7986 push @commit_spec, "-$patch_max";
7988 push @commit_spec, "-n";
7990 push @commit_spec, '--root', $hash;
7992 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7993 '--encoding=utf8', '--stdout', @commit_spec
7994 or die_error(500, "Open git-format-patch failed");
7995 } else {
7996 die_error(400, "Unknown commitdiff format");
7999 # non-textual hash id's can be cached
8000 my $expires;
8001 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8002 $expires = "+1d";
8005 # write commit message
8006 if ($format eq 'html') {
8007 my $refs = git_get_references();
8008 my $ref = format_ref_marker($refs, $co{'id'});
8010 git_header_html(undef, $expires);
8011 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
8012 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
8013 print "<div class=\"title_text\">\n" .
8014 "<table class=\"object_header\">\n";
8015 git_print_authorship_rows(\%co);
8016 print "</table>".
8017 "</div>\n";
8018 print "<div class=\"page_body\">\n";
8019 if (@{$co{'comment'}} > 1) {
8020 print "<div class=\"log\">\n";
8021 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
8022 print "</div>\n"; # class="log"
8025 } elsif ($format eq 'plain') {
8026 my $refs = git_get_references("tags");
8027 my $tagname = git_get_rev_name_tags($hash);
8028 my $filename = basename($project) . "-$hash.patch";
8030 print $cgi->header(
8031 -type => 'text/plain',
8032 -charset => 'utf-8',
8033 -expires => $expires,
8034 -content_disposition => 'inline; filename="' . "$filename" . '"');
8035 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8036 print "From: " . to_utf8($co{'author'}) . "\n";
8037 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8038 print "Subject: " . to_utf8($co{'title'}) . "\n";
8040 print "X-Git-Tag: $tagname\n" if $tagname;
8041 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8043 foreach my $line (@{$co{'comment'}}) {
8044 print to_utf8($line) . "\n";
8046 print "---\n\n";
8047 } elsif ($format eq 'patch') {
8048 my $filename = basename($project) . "-$hash.patch";
8050 print $cgi->header(
8051 -type => 'text/plain',
8052 -charset => 'utf-8',
8053 -expires => $expires,
8054 -content_disposition => 'inline; filename="' . "$filename" . '"');
8057 # write patch
8058 if ($format eq 'html') {
8059 my $use_parents = !defined $hash_parent ||
8060 $hash_parent eq '-c' || $hash_parent eq '--cc';
8061 git_difftree_body(\@difftree, $hash,
8062 $use_parents ? @{$co{'parents'}} : $hash_parent);
8063 print "<br/>\n";
8065 git_patchset_body($fd, $diff_style,
8066 \@difftree, $hash,
8067 $use_parents ? @{$co{'parents'}} : $hash_parent);
8068 close $fd;
8069 print "</div>\n"; # class="page_body"
8070 git_footer_html();
8072 } elsif ($format eq 'plain') {
8073 local $/ = undef;
8074 print <$fd>;
8075 close $fd
8076 or print "Reading git-diff-tree failed\n";
8077 } elsif ($format eq 'patch') {
8078 local $/ = undef;
8079 print <$fd>;
8080 close $fd
8081 or print "Reading git-format-patch failed\n";
8085 sub git_commitdiff_plain {
8086 git_commitdiff(-format => 'plain');
8089 # format-patch-style patches
8090 sub git_patch {
8091 git_commitdiff(-format => 'patch', -single => 1);
8094 sub git_patches {
8095 git_commitdiff(-format => 'patch');
8098 sub git_history {
8099 git_log_generic('history', \&git_history_body,
8100 $hash_base, $hash_parent_base,
8101 $file_name, $hash);
8104 sub git_search {
8105 $searchtype ||= 'commit';
8107 # check if appropriate features are enabled
8108 gitweb_check_feature('search')
8109 or die_error(403, "Search is disabled");
8110 if ($searchtype eq 'pickaxe') {
8111 # pickaxe may take all resources of your box and run for several minutes
8112 # with every query - so decide by yourself how public you make this feature
8113 gitweb_check_feature('pickaxe')
8114 or die_error(403, "Pickaxe search is disabled");
8116 if ($searchtype eq 'grep') {
8117 # grep search might be potentially CPU-intensive, too
8118 gitweb_check_feature('grep')
8119 or die_error(403, "Grep search is disabled");
8122 if (!defined $searchtext) {
8123 die_error(400, "Text field is empty");
8125 if (!defined $hash) {
8126 $hash = git_get_head_hash($project);
8128 my %co = parse_commit($hash);
8129 if (!%co) {
8130 die_error(404, "Unknown commit object");
8132 if (!defined $page) {
8133 $page = 0;
8136 if ($searchtype eq 'commit' ||
8137 $searchtype eq 'author' ||
8138 $searchtype eq 'committer') {
8139 git_search_message(%co);
8140 } elsif ($searchtype eq 'pickaxe') {
8141 git_search_changes(%co);
8142 } elsif ($searchtype eq 'grep') {
8143 git_search_files(%co);
8144 } else {
8145 die_error(400, "Unknown search type");
8149 sub git_search_help {
8150 git_header_html();
8151 git_print_page_nav('','', $hash,$hash,$hash);
8152 print <<EOT;
8153 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8154 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8155 the pattern entered is recognized as the POSIX extended
8156 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8157 insensitive).</p>
8158 <dl>
8159 <dt><b>commit</b></dt>
8160 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8162 my $have_grep = gitweb_check_feature('grep');
8163 if ($have_grep) {
8164 print <<EOT;
8165 <dt><b>grep</b></dt>
8166 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8167 a different one) are searched for the given pattern. On large trees, this search can take
8168 a while and put some strain on the server, so please use it with some consideration. Note that
8169 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8170 case-sensitive.</dd>
8173 print <<EOT;
8174 <dt><b>author</b></dt>
8175 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8176 <dt><b>committer</b></dt>
8177 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8179 my $have_pickaxe = gitweb_check_feature('pickaxe');
8180 if ($have_pickaxe) {
8181 print <<EOT;
8182 <dt><b>pickaxe</b></dt>
8183 <dd>All commits that caused the string to appear or disappear from any file (changes that
8184 added, removed or "modified" the string) will be listed. This search can take a while and
8185 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8186 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8189 print "</dl>\n";
8190 git_footer_html();
8193 sub git_shortlog {
8194 git_log_generic('shortlog', \&git_shortlog_body,
8195 $hash, $hash_parent);
8198 ## ......................................................................
8199 ## feeds (RSS, Atom; OPML)
8201 sub git_feed {
8202 my $format = shift || 'atom';
8203 my $have_blame = gitweb_check_feature('blame');
8205 # Atom: http://www.atomenabled.org/developers/syndication/
8206 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8207 if ($format ne 'rss' && $format ne 'atom') {
8208 die_error(400, "Unknown web feed format");
8211 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8212 my $head = $hash || 'HEAD';
8213 my @commitlist = parse_commits($head, 150, 0, $file_name);
8215 my %latest_commit;
8216 my %latest_date;
8217 my $content_type = "application/$format+xml";
8218 if (defined $cgi->http('HTTP_ACCEPT') &&
8219 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8220 # browser (feed reader) prefers text/xml
8221 $content_type = 'text/xml';
8223 if (defined($commitlist[0])) {
8224 %latest_commit = %{$commitlist[0]};
8225 my $latest_epoch = $latest_commit{'committer_epoch'};
8226 exit_if_unmodified_since($latest_epoch);
8227 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8229 print $cgi->header(
8230 -type => $content_type,
8231 -charset => 'utf-8',
8232 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8233 -status => '200 OK');
8235 # Optimization: skip generating the body if client asks only
8236 # for Last-Modified date.
8237 return if ($cgi->request_method() eq 'HEAD');
8239 # header variables
8240 my $title = "$site_name - $project/$action";
8241 my $feed_type = 'log';
8242 if (defined $hash) {
8243 $title .= " - '$hash'";
8244 $feed_type = 'branch log';
8245 if (defined $file_name) {
8246 $title .= " :: $file_name";
8247 $feed_type = 'history';
8249 } elsif (defined $file_name) {
8250 $title .= " - $file_name";
8251 $feed_type = 'history';
8253 $title .= " $feed_type";
8254 $title = esc_html($title);
8255 my $descr = git_get_project_description($project);
8256 if (defined $descr) {
8257 $descr = esc_html($descr);
8258 } else {
8259 $descr = "$project " .
8260 ($format eq 'rss' ? 'RSS' : 'Atom') .
8261 " feed";
8263 my $owner = git_get_project_owner($project);
8264 $owner = esc_html($owner);
8266 #header
8267 my $alt_url;
8268 if (defined $file_name) {
8269 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8270 } elsif (defined $hash) {
8271 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8272 } else {
8273 $alt_url = href(-full=>1, action=>"summary");
8275 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8276 if ($format eq 'rss') {
8277 print <<XML;
8278 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8279 <channel>
8281 print "<title>$title</title>\n" .
8282 "<link>$alt_url</link>\n" .
8283 "<description>$descr</description>\n" .
8284 "<language>en</language>\n" .
8285 # project owner is responsible for 'editorial' content
8286 "<managingEditor>$owner</managingEditor>\n";
8287 if (defined $logo || defined $favicon) {
8288 # prefer the logo to the favicon, since RSS
8289 # doesn't allow both
8290 my $img = esc_url($logo || $favicon);
8291 print "<image>\n" .
8292 "<url>$img</url>\n" .
8293 "<title>$title</title>\n" .
8294 "<link>$alt_url</link>\n" .
8295 "</image>\n";
8297 if (%latest_date) {
8298 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8299 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8301 print "<generator>gitweb v.$version/$git_version</generator>\n";
8302 } elsif ($format eq 'atom') {
8303 print <<XML;
8304 <feed xmlns="http://www.w3.org/2005/Atom">
8306 print "<title>$title</title>\n" .
8307 "<subtitle>$descr</subtitle>\n" .
8308 '<link rel="alternate" type="text/html" href="' .
8309 $alt_url . '" />' . "\n" .
8310 '<link rel="self" type="' . $content_type . '" href="' .
8311 $cgi->self_url() . '" />' . "\n" .
8312 "<id>" . href(-full=>1) . "</id>\n" .
8313 # use project owner for feed author
8314 '<author><name>'. email_obfuscate($owner) . '</name></author>\n';
8315 if (defined $favicon) {
8316 print "<icon>" . esc_url($favicon) . "</icon>\n";
8318 if (defined $logo) {
8319 # not twice as wide as tall: 72 x 27 pixels
8320 print "<logo>" . esc_url($logo) . "</logo>\n";
8322 if (! %latest_date) {
8323 # dummy date to keep the feed valid until commits trickle in:
8324 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8325 } else {
8326 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8328 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8331 # contents
8332 for (my $i = 0; $i <= $#commitlist; $i++) {
8333 my %co = %{$commitlist[$i]};
8334 my $commit = $co{'id'};
8335 # we read 150, we always show 30 and the ones more recent than 48 hours
8336 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8337 last;
8339 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8341 # get list of changed files
8342 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8343 $co{'parent'} || "--root",
8344 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8345 or next;
8346 my @difftree = map { chomp; $_ } <$fd>;
8347 close $fd
8348 or next;
8350 # print element (entry, item)
8351 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8352 if ($format eq 'rss') {
8353 print "<item>\n" .
8354 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8355 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8356 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8357 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8358 "<link>$co_url</link>\n" .
8359 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8360 "<content:encoded>" .
8361 "<![CDATA[\n";
8362 } elsif ($format eq 'atom') {
8363 print "<entry>\n" .
8364 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8365 "<updated>$cd{'iso-8601'}</updated>\n" .
8366 "<author>\n" .
8367 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8368 if ($co{'author_email'}) {
8369 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8371 print "</author>\n" .
8372 # use committer for contributor
8373 "<contributor>\n" .
8374 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8375 if ($co{'committer_email'}) {
8376 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8378 print "</contributor>\n" .
8379 "<published>$cd{'iso-8601'}</published>\n" .
8380 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8381 "<id>$co_url</id>\n" .
8382 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8383 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8385 my $comment = $co{'comment'};
8386 print "<pre>\n";
8387 foreach my $line (@$comment) {
8388 $line = esc_html($line);
8389 print "$line\n";
8391 print "</pre><ul>\n";
8392 foreach my $difftree_line (@difftree) {
8393 my %difftree = parse_difftree_raw_line($difftree_line);
8394 next if !$difftree{'from_id'};
8396 my $file = $difftree{'file'} || $difftree{'to_file'};
8398 print "<li>" .
8399 "[" .
8400 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8401 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8402 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8403 file_name=>$file, file_parent=>$difftree{'from_file'}),
8404 -title => "diff"}, 'D');
8405 if ($have_blame) {
8406 print $cgi->a({-href => href(-full=>1, action=>"blame",
8407 file_name=>$file, hash_base=>$commit),
8408 -title => "blame"}, 'B');
8410 # if this is not a feed of a file history
8411 if (!defined $file_name || $file_name ne $file) {
8412 print $cgi->a({-href => href(-full=>1, action=>"history",
8413 file_name=>$file, hash=>$commit),
8414 -title => "history"}, 'H');
8416 $file = esc_path($file);
8417 print "] ".
8418 "$file</li>\n";
8420 if ($format eq 'rss') {
8421 print "</ul>]]>\n" .
8422 "</content:encoded>\n" .
8423 "</item>\n";
8424 } elsif ($format eq 'atom') {
8425 print "</ul>\n</div>\n" .
8426 "</content>\n" .
8427 "</entry>\n";
8431 # end of feed
8432 if ($format eq 'rss') {
8433 print "</channel>\n</rss>\n";
8434 } elsif ($format eq 'atom') {
8435 print "</feed>\n";
8439 sub git_rss {
8440 git_feed('rss');
8443 sub git_atom {
8444 git_feed('atom');
8447 sub git_opml {
8448 my @list = git_get_projects_list($project_filter, $strict_export);
8449 if (!@list) {
8450 die_error(404, "No projects found");
8453 print $cgi->header(
8454 -type => 'text/xml',
8455 -charset => 'utf-8',
8456 -content_disposition => 'inline; filename="opml.xml"');
8458 my $title = esc_html($site_name);
8459 my $filter = " within subdirectory ";
8460 if (defined $project_filter) {
8461 $filter .= esc_html($project_filter);
8462 } else {
8463 $filter = "";
8465 print <<XML;
8466 <?xml version="1.0" encoding="utf-8"?>
8467 <opml version="1.0">
8468 <head>
8469 <title>$title OPML Export$filter</title>
8470 </head>
8471 <body>
8472 <outline text="git RSS feeds">
8475 foreach my $pr (@list) {
8476 my %proj = %$pr;
8477 my $head = git_get_head_hash($proj{'path'});
8478 if (!defined $head) {
8479 next;
8481 $git_dir = "$projectroot/$proj{'path'}";
8482 my %co = parse_commit($head);
8483 if (!%co) {
8484 next;
8487 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8488 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8489 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8490 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8492 print <<XML;
8493 </outline>
8494 </body>
8495 </opml>