tgupdate: merge t/email/obfuscate base into t/email/obfuscate
[git/gitweb.git] / gitweb / gitweb.perl
blobea794eed85911a32b0e824113bacce9cac7e9e3d
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;
757 our $to_utf8_pipe_command = '';
759 sub evaluate_encoding {
760 my $requested = $fallback_encoding || 'ISO-8859-1';
761 my $obj = Encode::find_encoding($requested) or
762 die_error(400, "Requested fallback encoding not found");
763 if ($obj->name eq 'iso-8859-1') {
764 # Use Windows-1252 instead as required by the HTML 5 standard
765 my $altobj = Encode::find_encoding('Windows-1252');
766 $obj = $altobj if $altobj;
768 $encode_object = $obj;
769 my $nm = lc($encode_object->name);
770 unless ($nm eq 'cp1252' || $nm eq 'ascii' || $nm eq 'utf8' ||
771 $nm =~ /^utf-8/ || $nm =~ /^iso-8859-/) {
772 $to_utf8_pipe_command =
773 quote_command($^X, '-CO', '-MEncode=decode,FB_DEFAULT', '-pse',
774 '$_ = decode($fe, $_, FB_DEFAULT) if !utf8::decode($_);',
775 '--', "-fe=$fallback_encoding")." | ";
779 sub evaluate_email_obfuscate {
780 # email obfuscation
781 our $email;
782 if (!$email && eval { require HTML::Email::Obfuscate; 1 }) {
783 $email = HTML::Email::Obfuscate->new(lite => 1);
787 # Get loadavg of system, to compare against $maxload.
788 # Currently it requires '/proc/loadavg' present to get loadavg;
789 # if it is not present it returns 0, which means no load checking.
790 sub get_loadavg {
791 if( -e '/proc/loadavg' ){
792 open my $fd, '<', '/proc/loadavg'
793 or return 0;
794 my @load = split(/\s+/, scalar <$fd>);
795 close $fd;
797 # The first three columns measure CPU and IO utilization of the last one,
798 # five, and 10 minute periods. The fourth column shows the number of
799 # currently running processes and the total number of processes in the m/n
800 # format. The last column displays the last process ID used.
801 return $load[0] || 0;
803 # additional checks for load average should go here for things that don't export
804 # /proc/loadavg
806 return 0;
809 # version of the core git binary
810 our $git_version;
811 sub evaluate_git_version {
812 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
813 $number_of_git_cmds++;
816 sub check_loadavg {
817 if (defined $maxload && get_loadavg() > $maxload) {
818 die_error(503, "The load average on the server is too high");
822 # ======================================================================
823 # input validation and dispatch
825 # input parameters can be collected from a variety of sources (presently, CGI
826 # and PATH_INFO), so we define an %input_params hash that collects them all
827 # together during validation: this allows subsequent uses (e.g. href()) to be
828 # agnostic of the parameter origin
830 our %input_params = ();
832 # input parameters are stored with the long parameter name as key. This will
833 # also be used in the href subroutine to convert parameters to their CGI
834 # equivalent, and since the href() usage is the most frequent one, we store
835 # the name -> CGI key mapping here, instead of the reverse.
837 # XXX: Warning: If you touch this, check the search form for updating,
838 # too.
840 our @cgi_param_mapping = (
841 project => "p",
842 action => "a",
843 file_name => "f",
844 file_parent => "fp",
845 hash => "h",
846 hash_parent => "hp",
847 hash_base => "hb",
848 hash_parent_base => "hpb",
849 page => "pg",
850 order => "o",
851 searchtext => "s",
852 searchtype => "st",
853 snapshot_format => "sf",
854 extra_options => "opt",
855 search_use_regexp => "sr",
856 ctag => "by_tag",
857 diff_style => "ds",
858 project_filter => "pf",
859 # this must be last entry (for manipulation from JavaScript)
860 javascript => "js"
862 our %cgi_param_mapping = @cgi_param_mapping;
864 # we will also need to know the possible actions, for validation
865 our %actions = (
866 "blame" => \&git_blame,
867 "blame_incremental" => \&git_blame_incremental,
868 "blame_data" => \&git_blame_data,
869 "blobdiff" => \&git_blobdiff,
870 "blobdiff_plain" => \&git_blobdiff_plain,
871 "blob" => \&git_blob,
872 "blob_plain" => \&git_blob_plain,
873 "commitdiff" => \&git_commitdiff,
874 "commitdiff_plain" => \&git_commitdiff_plain,
875 "commit" => \&git_commit,
876 "forks" => \&git_forks,
877 "heads" => \&git_heads,
878 "history" => \&git_history,
879 "log" => \&git_log,
880 "patch" => \&git_patch,
881 "patches" => \&git_patches,
882 "remotes" => \&git_remotes,
883 "rss" => \&git_rss,
884 "atom" => \&git_atom,
885 "search" => \&git_search,
886 "search_help" => \&git_search_help,
887 "shortlog" => \&git_shortlog,
888 "summary" => \&git_summary,
889 "tag" => \&git_tag,
890 "tags" => \&git_tags,
891 "tree" => \&git_tree,
892 "snapshot" => \&git_snapshot,
893 "object" => \&git_object,
894 # those below don't need $project
895 "opml" => \&git_opml,
896 "project_list" => \&git_project_list,
897 "project_index" => \&git_project_index,
900 # finally, we have the hash of allowed extra_options for the commands that
901 # allow them
902 our %allowed_options = (
903 "--no-merges" => [ qw(rss atom log shortlog history) ],
906 # fill %input_params with the CGI parameters. All values except for 'opt'
907 # should be single values, but opt can be an array. We should probably
908 # build an array of parameters that can be multi-valued, but since for the time
909 # being it's only this one, we just single it out
910 sub evaluate_query_params {
911 our $cgi;
913 while (my ($name, $symbol) = each %cgi_param_mapping) {
914 if ($symbol eq 'opt') {
915 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
916 } else {
917 $input_params{$name} = decode_utf8($cgi->param($symbol));
922 # now read PATH_INFO and update the parameter list for missing parameters
923 sub evaluate_path_info {
924 return if defined $input_params{'project'};
925 return if !$path_info;
926 $path_info =~ s,^/+,,;
927 return if !$path_info;
929 # find which part of PATH_INFO is project
930 my $project = $path_info;
931 $project =~ s,/+$,,;
932 while ($project && !check_head_link("$projectroot/$project")) {
933 $project =~ s,/*[^/]*$,,;
935 return unless $project;
936 $input_params{'project'} = $project;
938 # do not change any parameters if an action is given using the query string
939 return if $input_params{'action'};
940 $path_info =~ s,^\Q$project\E/*,,;
942 # next, check if we have an action
943 my $action = $path_info;
944 $action =~ s,/.*$,,;
945 if (exists $actions{$action}) {
946 $path_info =~ s,^$action/*,,;
947 $input_params{'action'} = $action;
950 # list of actions that want hash_base instead of hash, but can have no
951 # pathname (f) parameter
952 my @wants_base = (
953 'tree',
954 'history',
957 # we want to catch, among others
958 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
959 my ($parentrefname, $parentpathname, $refname, $pathname) =
960 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
962 # first, analyze the 'current' part
963 if (defined $pathname) {
964 # we got "branch:filename" or "branch:dir/"
965 # we could use git_get_type(branch:pathname), but:
966 # - it needs $git_dir
967 # - it does a git() call
968 # - the convention of terminating directories with a slash
969 # makes it superfluous
970 # - embedding the action in the PATH_INFO would make it even
971 # more superfluous
972 $pathname =~ s,^/+,,;
973 if (!$pathname || substr($pathname, -1) eq "/") {
974 $input_params{'action'} ||= "tree";
975 $pathname =~ s,/$,,;
976 } else {
977 # the default action depends on whether we had parent info
978 # or not
979 if ($parentrefname) {
980 $input_params{'action'} ||= "blobdiff_plain";
981 } else {
982 $input_params{'action'} ||= "blob_plain";
985 $input_params{'hash_base'} ||= $refname;
986 $input_params{'file_name'} ||= $pathname;
987 } elsif (defined $refname) {
988 # we got "branch". In this case we have to choose if we have to
989 # set hash or hash_base.
991 # Most of the actions without a pathname only want hash to be
992 # set, except for the ones specified in @wants_base that want
993 # hash_base instead. It should also be noted that hand-crafted
994 # links having 'history' as an action and no pathname or hash
995 # set will fail, but that happens regardless of PATH_INFO.
996 if (defined $parentrefname) {
997 # if there is parent let the default be 'shortlog' action
998 # (for http://git.example.com/repo.git/A..B links); if there
999 # is no parent, dispatch will detect type of object and set
1000 # action appropriately if required (if action is not set)
1001 $input_params{'action'} ||= "shortlog";
1003 if ($input_params{'action'} &&
1004 grep { $_ eq $input_params{'action'} } @wants_base) {
1005 $input_params{'hash_base'} ||= $refname;
1006 } else {
1007 $input_params{'hash'} ||= $refname;
1011 # next, handle the 'parent' part, if present
1012 if (defined $parentrefname) {
1013 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1014 # someproject/blobdiff/oldrev..newrev:/filename
1015 if ($parentpathname) {
1016 $parentpathname =~ s,^/+,,;
1017 $parentpathname =~ s,/$,,;
1018 $input_params{'file_parent'} ||= $parentpathname;
1019 } else {
1020 $input_params{'file_parent'} ||= $input_params{'file_name'};
1022 # we assume that hash_parent_base is wanted if a path was specified,
1023 # or if the action wants hash_base instead of hash
1024 if (defined $input_params{'file_parent'} ||
1025 grep { $_ eq $input_params{'action'} } @wants_base) {
1026 $input_params{'hash_parent_base'} ||= $parentrefname;
1027 } else {
1028 $input_params{'hash_parent'} ||= $parentrefname;
1032 # for the snapshot action, we allow URLs in the form
1033 # $project/snapshot/$hash.ext
1034 # where .ext determines the snapshot and gets removed from the
1035 # passed $refname to provide the $hash.
1037 # To be able to tell that $refname includes the format extension, we
1038 # require the following two conditions to be satisfied:
1039 # - the hash input parameter MUST have been set from the $refname part
1040 # of the URL (i.e. they must be equal)
1041 # - the snapshot format MUST NOT have been defined already (e.g. from
1042 # CGI parameter sf)
1043 # It's also useless to try any matching unless $refname has a dot,
1044 # so we check for that too
1045 if (defined $input_params{'action'} &&
1046 $input_params{'action'} eq 'snapshot' &&
1047 defined $refname && index($refname, '.') != -1 &&
1048 $refname eq $input_params{'hash'} &&
1049 !defined $input_params{'snapshot_format'}) {
1050 # We loop over the known snapshot formats, checking for
1051 # extensions. Allowed extensions are both the defined suffix
1052 # (which includes the initial dot already) and the snapshot
1053 # format key itself, with a prepended dot
1054 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1055 my $hash = $refname;
1056 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1057 next;
1059 my $sfx = $1;
1060 # a valid suffix was found, so set the snapshot format
1061 # and reset the hash parameter
1062 $input_params{'snapshot_format'} = $fmt;
1063 $input_params{'hash'} = $hash;
1064 # we also set the format suffix to the one requested
1065 # in the URL: this way a request for e.g. .tgz returns
1066 # a .tgz instead of a .tar.gz
1067 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1068 last;
1073 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1074 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1075 $searchtext, $search_regexp, $project_filter);
1076 sub evaluate_and_validate_params {
1077 our $action = $input_params{'action'};
1078 if (defined $action) {
1079 if (!is_valid_action($action)) {
1080 die_error(400, "Invalid action parameter");
1084 # parameters which are pathnames
1085 our $project = $input_params{'project'};
1086 if (defined $project) {
1087 if (!is_valid_project($project)) {
1088 undef $project;
1089 die_error(404, "No such project");
1093 our $project_filter = $input_params{'project_filter'};
1094 if (defined $project_filter) {
1095 if (!is_valid_pathname($project_filter)) {
1096 die_error(404, "Invalid project_filter parameter");
1100 our $file_name = $input_params{'file_name'};
1101 if (defined $file_name) {
1102 if (!is_valid_pathname($file_name)) {
1103 die_error(400, "Invalid file parameter");
1107 our $file_parent = $input_params{'file_parent'};
1108 if (defined $file_parent) {
1109 if (!is_valid_pathname($file_parent)) {
1110 die_error(400, "Invalid file parent parameter");
1114 # parameters which are refnames
1115 our $hash = $input_params{'hash'};
1116 if (defined $hash) {
1117 if (!is_valid_refname($hash)) {
1118 die_error(400, "Invalid hash parameter");
1122 our $hash_parent = $input_params{'hash_parent'};
1123 if (defined $hash_parent) {
1124 if (!is_valid_refname($hash_parent)) {
1125 die_error(400, "Invalid hash parent parameter");
1129 our $hash_base = $input_params{'hash_base'};
1130 if (defined $hash_base) {
1131 if (!is_valid_refname($hash_base)) {
1132 die_error(400, "Invalid hash base parameter");
1136 our @extra_options = @{$input_params{'extra_options'}};
1137 # @extra_options is always defined, since it can only be (currently) set from
1138 # CGI, and $cgi->param() returns the empty array in array context if the param
1139 # is not set
1140 foreach my $opt (@extra_options) {
1141 if (not exists $allowed_options{$opt}) {
1142 die_error(400, "Invalid option parameter");
1144 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1145 die_error(400, "Invalid option parameter for this action");
1149 our $hash_parent_base = $input_params{'hash_parent_base'};
1150 if (defined $hash_parent_base) {
1151 if (!is_valid_refname($hash_parent_base)) {
1152 die_error(400, "Invalid hash parent base parameter");
1156 # other parameters
1157 our $page = $input_params{'page'};
1158 if (defined $page) {
1159 if ($page =~ m/[^0-9]/) {
1160 die_error(400, "Invalid page parameter");
1164 our $searchtype = $input_params{'searchtype'};
1165 if (defined $searchtype) {
1166 if ($searchtype =~ m/[^a-z]/) {
1167 die_error(400, "Invalid searchtype parameter");
1171 our $search_use_regexp = $input_params{'search_use_regexp'};
1173 our $searchtext = $input_params{'searchtext'};
1174 our $search_regexp = undef;
1175 if (defined $searchtext) {
1176 if (length($searchtext) < 2) {
1177 die_error(403, "At least two characters are required for search parameter");
1179 if ($search_use_regexp) {
1180 $search_regexp = $searchtext;
1181 if (!eval { qr/$search_regexp/; 1; }) {
1182 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1183 die_error(400, "Invalid search regexp '$search_regexp'",
1184 esc_html($error));
1186 } else {
1187 $search_regexp = quotemeta $searchtext;
1192 # path to the current git repository
1193 our $git_dir;
1194 sub evaluate_git_dir {
1195 our $git_dir = "$projectroot/$project" if $project;
1198 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1199 sub configure_gitweb_features {
1200 # list of supported snapshot formats
1201 our @snapshot_fmts = gitweb_get_feature('snapshot');
1202 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1204 # check that the avatar feature is set to a known provider name,
1205 # and for each provider check if the dependencies are satisfied.
1206 # if the provider name is invalid or the dependencies are not met,
1207 # reset $git_avatar to the empty string.
1208 our ($git_avatar) = gitweb_get_feature('avatar');
1209 if ($git_avatar eq 'gravatar') {
1210 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1211 } elsif ($git_avatar eq 'picon') {
1212 # no dependencies
1213 } else {
1214 $git_avatar = '';
1217 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1218 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1221 sub get_branch_refs {
1222 return ('heads', @extra_branch_refs);
1225 # custom error handler: 'die <message>' is Internal Server Error
1226 sub handle_errors_html {
1227 my $msg = shift; # it is already HTML escaped
1229 # to avoid infinite loop where error occurs in die_error,
1230 # change handler to default handler, disabling handle_errors_html
1231 set_message("Error occurred when inside die_error:\n$msg");
1233 # you cannot jump out of die_error when called as error handler;
1234 # the subroutine set via CGI::Carp::set_message is called _after_
1235 # HTTP headers are already written, so it cannot write them itself
1236 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1238 set_message(\&handle_errors_html);
1240 # dispatch
1241 sub dispatch {
1242 if (!defined $action) {
1243 if (defined $hash) {
1244 $action = git_get_type($hash);
1245 $action or die_error(404, "Object does not exist");
1246 } elsif (defined $hash_base && defined $file_name) {
1247 $action = git_get_type("$hash_base:$file_name");
1248 $action or die_error(404, "File or directory does not exist");
1249 } elsif (defined $project) {
1250 $action = 'summary';
1251 } else {
1252 $action = 'project_list';
1255 if (!defined($actions{$action})) {
1256 die_error(400, "Unknown action");
1258 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1259 !$project) {
1260 die_error(400, "Project needed");
1262 $actions{$action}->();
1265 sub reset_timer {
1266 our $t0 = [ gettimeofday() ]
1267 if defined $t0;
1268 our $number_of_git_cmds = 0;
1271 our $first_request = 1;
1272 our $evaluate_uri_force = undef;
1273 sub run_request {
1274 reset_timer();
1276 # Only allow GET and HEAD methods
1277 if (!$ENV{'REQUEST_METHOD'} || ($ENV{'REQUEST_METHOD'} ne 'GET' && $ENV{'REQUEST_METHOD'} ne 'HEAD')) {
1278 print <<EOT;
1279 Status: 405 Method Not Allowed
1280 Content-Type: text/plain
1281 Allow: GET,HEAD
1283 405 Method Not Allowed
1285 return;
1288 evaluate_uri();
1289 &$evaluate_uri_force() if $evaluate_uri_force;
1290 if ($per_request_config) {
1291 if (ref($per_request_config) eq 'CODE') {
1292 $per_request_config->();
1293 } elsif (!$first_request) {
1294 evaluate_gitweb_config();
1295 evaluate_email_obfuscate();
1298 check_loadavg();
1300 # $projectroot and $projects_list might be set in gitweb config file
1301 $projects_list ||= $projectroot;
1303 evaluate_query_params();
1304 evaluate_path_info();
1305 evaluate_and_validate_params();
1306 evaluate_git_dir();
1308 configure_gitweb_features();
1310 dispatch();
1313 our $is_last_request = sub { 1 };
1314 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1315 our $CGI = 'CGI';
1316 our $cgi;
1317 our $fcgi_mode = 0;
1318 our $fcgi_nproc_active = 0;
1319 sub is_fcgi {
1320 use Errno;
1321 my $stdinfno = fileno STDIN;
1322 return 0 unless defined $stdinfno && $stdinfno == 0;
1323 return 0 unless getsockname STDIN;
1324 return 0 if getpeername STDIN;
1325 return $!{ENOTCONN}?1:0;
1327 sub configure_as_fcgi {
1328 return if $fcgi_mode;
1330 require CGI::Fast;
1331 our $CGI = 'CGI::Fast';
1333 $fcgi_mode = 1;
1334 $first_request = 0;
1335 my $request_number = 0;
1336 # let each child service 100 requests
1337 our $is_last_request = sub { ++$request_number > 100 };
1339 sub evaluate_argv {
1340 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1341 configure_as_fcgi()
1342 if $script_name =~ /\.fcgi$/ || ($auto_fcgi && is_fcgi());
1344 my $nproc_sub = sub {
1345 my ($arg, $val) = @_;
1346 return unless eval { require FCGI::ProcManager; 1; };
1347 $fcgi_nproc_active = 1;
1348 my $proc_manager = FCGI::ProcManager->new({
1349 n_processes => $val,
1351 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1352 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1353 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1355 if (@ARGV) {
1356 require Getopt::Long;
1357 Getopt::Long::GetOptions(
1358 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1359 'nproc|n=i' => $nproc_sub,
1362 if (!$fcgi_nproc_active && defined $ENV{'GITWEB_FCGI_NPROC'} && $ENV{'GITWEB_FCGI_NPROC'} =~ /^\d+$/) {
1363 &$nproc_sub('nproc', $ENV{'GITWEB_FCGI_NPROC'});
1367 sub run {
1368 evaluate_gitweb_config();
1369 evaluate_encoding();
1370 evaluate_email_obfuscate();
1371 evaluate_git_version();
1372 my ($ml, $mi, $bu, $hl, $subroutine) = ($my_url, $my_uri, $base_url, $home_link, '');
1373 $subroutine .= '$my_url = $ml;' if defined $my_url && $my_url ne '';
1374 $subroutine .= '$my_uri = $mi;' if defined $my_uri; # this one can be ""
1375 $subroutine .= '$base_url = $bu;' if defined $base_url && $base_url ne '';
1376 $subroutine .= '$home_link = $hl;' if defined $home_link && $home_link ne '';
1377 $evaluate_uri_force = eval "sub {$subroutine}" if $subroutine;
1378 $first_request = 1;
1379 evaluate_argv();
1381 $pre_listen_hook->()
1382 if $pre_listen_hook;
1384 REQUEST:
1385 while ($cgi = $CGI->new()) {
1386 $pre_dispatch_hook->()
1387 if $pre_dispatch_hook;
1389 run_request();
1391 $post_dispatch_hook->()
1392 if $post_dispatch_hook;
1393 $first_request = 0;
1395 last REQUEST if ($is_last_request->());
1398 DONE_GITWEB:
1402 run();
1404 if (defined caller) {
1405 # wrapped in a subroutine processing requests,
1406 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1407 return;
1408 } else {
1409 # pure CGI script, serving single request
1410 exit;
1413 ## ======================================================================
1414 ## action links
1416 # possible values of extra options
1417 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1418 # -replay => 1 - start from a current view (replay with modifications)
1419 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1420 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1421 sub href {
1422 my %params = @_;
1423 # default is to use -absolute url() i.e. $my_uri
1424 my $href = $params{-full} ? $my_url : $my_uri;
1426 # implicit -replay, must be first of implicit params
1427 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1429 $params{'project'} = $project unless exists $params{'project'};
1431 if ($params{-replay}) {
1432 while (my ($name, $symbol) = each %cgi_param_mapping) {
1433 if (!exists $params{$name}) {
1434 $params{$name} = $input_params{$name};
1439 my $use_pathinfo = gitweb_check_feature('pathinfo');
1440 if (defined $params{'project'} &&
1441 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1442 # try to put as many parameters as possible in PATH_INFO:
1443 # - project name
1444 # - action
1445 # - hash_parent or hash_parent_base:/file_parent
1446 # - hash or hash_base:/filename
1447 # - the snapshot_format as an appropriate suffix
1449 # When the script is the root DirectoryIndex for the domain,
1450 # $href here would be something like http://gitweb.example.com/
1451 # Thus, we strip any trailing / from $href, to spare us double
1452 # slashes in the final URL
1453 $href =~ s,/$,,;
1455 # Then add the project name, if present
1456 $href .= "/".esc_path_info($params{'project'});
1457 delete $params{'project'};
1459 # since we destructively absorb parameters, we keep this
1460 # boolean that remembers if we're handling a snapshot
1461 my $is_snapshot = $params{'action'} eq 'snapshot';
1463 # Summary just uses the project path URL, any other action is
1464 # added to the URL
1465 if (defined $params{'action'}) {
1466 $href .= "/".esc_path_info($params{'action'})
1467 unless $params{'action'} eq 'summary';
1468 delete $params{'action'};
1471 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1472 # stripping nonexistent or useless pieces
1473 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1474 || $params{'hash_parent'} || $params{'hash'});
1475 if (defined $params{'hash_base'}) {
1476 if (defined $params{'hash_parent_base'}) {
1477 $href .= esc_path_info($params{'hash_parent_base'});
1478 # skip the file_parent if it's the same as the file_name
1479 if (defined $params{'file_parent'}) {
1480 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1481 delete $params{'file_parent'};
1482 } elsif ($params{'file_parent'} !~ /\.\./) {
1483 $href .= ":/".esc_path_info($params{'file_parent'});
1484 delete $params{'file_parent'};
1487 $href .= "..";
1488 delete $params{'hash_parent'};
1489 delete $params{'hash_parent_base'};
1490 } elsif (defined $params{'hash_parent'}) {
1491 $href .= esc_path_info($params{'hash_parent'}). "..";
1492 delete $params{'hash_parent'};
1495 $href .= esc_path_info($params{'hash_base'});
1496 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1497 $href .= ":/".esc_path_info($params{'file_name'});
1498 delete $params{'file_name'};
1500 delete $params{'hash'};
1501 delete $params{'hash_base'};
1502 } elsif (defined $params{'hash'}) {
1503 $href .= esc_path_info($params{'hash'});
1504 delete $params{'hash'};
1507 # If the action was a snapshot, we can absorb the
1508 # snapshot_format parameter too
1509 if ($is_snapshot) {
1510 my $fmt = $params{'snapshot_format'};
1511 # snapshot_format should always be defined when href()
1512 # is called, but just in case some code forgets, we
1513 # fall back to the default
1514 $fmt ||= $snapshot_fmts[0];
1515 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1516 delete $params{'snapshot_format'};
1520 # now encode the parameters explicitly
1521 my @result = ();
1522 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1523 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1524 if (defined $params{$name}) {
1525 if (ref($params{$name}) eq "ARRAY") {
1526 foreach my $par (@{$params{$name}}) {
1527 push @result, $symbol . "=" . esc_param($par);
1529 } else {
1530 push @result, $symbol . "=" . esc_param($params{$name});
1534 $href .= "?" . join(';', @result) if scalar @result;
1536 # final transformation: trailing spaces must be escaped (URI-encoded)
1537 $href =~ s/(\s+)$/CGI::escape($1)/e;
1539 if ($params{-anchor}) {
1540 $href .= "#".esc_param($params{-anchor});
1543 return $href;
1547 ## ======================================================================
1548 ## validation, quoting/unquoting and escaping
1550 sub is_valid_action {
1551 my $input = shift;
1552 return undef unless exists $actions{$input};
1553 return 1;
1556 sub is_valid_project {
1557 my $input = shift;
1559 return unless defined $input;
1560 if (!is_valid_pathname($input) ||
1561 !(-d "$projectroot/$input") ||
1562 !check_export_ok("$projectroot/$input") ||
1563 ($strict_export && !project_in_list($input))) {
1564 return undef;
1565 } else {
1566 return 1;
1570 sub is_valid_pathname {
1571 my $input = shift;
1573 return undef unless defined $input;
1574 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1575 # at the beginning, at the end, and between slashes.
1576 # also this catches doubled slashes
1577 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1578 return undef;
1580 # no null characters
1581 if ($input =~ m!\0!) {
1582 return undef;
1584 return 1;
1587 sub is_valid_ref_format {
1588 my $input = shift;
1590 return undef unless defined $input;
1591 # restrictions on ref name according to git-check-ref-format
1592 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1593 return undef;
1595 return 1;
1598 sub is_valid_refname {
1599 my $input = shift;
1601 return undef unless defined $input;
1602 # textual hashes are O.K.
1603 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1604 return 1;
1606 # it must be correct pathname
1607 is_valid_pathname($input) or return undef;
1608 # check git-check-ref-format restrictions
1609 is_valid_ref_format($input) or return undef;
1610 return 1;
1613 # decode sequences of octets in utf8 into Perl's internal form,
1614 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1615 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1616 sub to_utf8 {
1617 my $str = shift;
1618 return undef unless defined $str;
1620 if (utf8::is_utf8($str) || utf8::decode($str)) {
1621 return $str;
1622 } else {
1623 return $encode_object->decode($str, Encode::FB_DEFAULT);
1627 # quote unsafe chars, but keep the slash, even when it's not
1628 # correct, but quoted slashes look too horrible in bookmarks
1629 sub esc_param {
1630 my $str = shift;
1631 return undef unless defined $str;
1632 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1633 $str =~ s/ /\+/g;
1634 return $str;
1637 # the quoting rules for path_info fragment are slightly different
1638 sub esc_path_info {
1639 my $str = shift;
1640 return undef unless defined $str;
1642 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1643 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1645 return $str;
1648 # quote unsafe chars in whole URL, so some characters cannot be quoted
1649 sub esc_url {
1650 my $str = shift;
1651 return undef unless defined $str;
1652 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1653 $str =~ s/ /\+/g;
1654 return $str;
1657 # quote unsafe characters in HTML attributes
1658 sub esc_attr {
1660 # for XHTML conformance escaping '"' to '&quot;' is not enough
1661 return esc_html(@_);
1664 # replace invalid utf8 character with SUBSTITUTION sequence
1665 sub esc_html {
1666 my $str = shift;
1667 my %opts = @_;
1669 return undef unless defined $str;
1671 $str = to_utf8($str);
1672 $str = $cgi->escapeHTML($str);
1673 if ($opts{'-nbsp'}) {
1674 $str =~ s/ /&nbsp;/g;
1676 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1677 return $str;
1680 # quote control characters and escape filename to HTML
1681 sub esc_path {
1682 my $str = shift;
1683 my %opts = @_;
1685 return undef unless defined $str;
1687 $str = to_utf8($str);
1688 $str = $cgi->escapeHTML($str);
1689 if ($opts{'-nbsp'}) {
1690 $str =~ s/ /&nbsp;/g;
1692 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1693 return $str;
1696 # Sanitize for use in XHTML + application/xml+xhtml (valid XML 1.0)
1697 sub sanitize {
1698 my $str = shift;
1700 return undef unless defined $str;
1702 $str = to_utf8($str);
1703 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1704 return $str;
1707 # Make control characters "printable", using character escape codes (CEC)
1708 sub quot_cec {
1709 my $cntrl = shift;
1710 my %opts = @_;
1711 my %es = ( # character escape codes, aka escape sequences
1712 "\t" => '\t', # tab (HT)
1713 "\n" => '\n', # line feed (LF)
1714 "\r" => '\r', # carrige return (CR)
1715 "\f" => '\f', # form feed (FF)
1716 "\b" => '\b', # backspace (BS)
1717 "\a" => '\a', # alarm (bell) (BEL)
1718 "\e" => '\e', # escape (ESC)
1719 "\013" => '\v', # vertical tab (VT)
1720 "\000" => '\0', # nul character (NUL)
1722 my $chr = ( (exists $es{$cntrl})
1723 ? $es{$cntrl}
1724 : sprintf('\%2x', ord($cntrl)) );
1725 if ($opts{-nohtml}) {
1726 return $chr;
1727 } else {
1728 return "<span class=\"cntrl\">$chr</span>";
1732 # Alternatively use unicode control pictures codepoints,
1733 # Unicode "printable representation" (PR)
1734 sub quot_upr {
1735 my $cntrl = shift;
1736 my %opts = @_;
1738 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1739 if ($opts{-nohtml}) {
1740 return $chr;
1741 } else {
1742 return "<span class=\"cntrl\">$chr</span>";
1746 # git may return quoted and escaped filenames
1747 sub unquote {
1748 my $str = shift;
1750 sub unq {
1751 my $seq = shift;
1752 my %es = ( # character escape codes, aka escape sequences
1753 't' => "\t", # tab (HT, TAB)
1754 'n' => "\n", # newline (NL)
1755 'r' => "\r", # return (CR)
1756 'f' => "\f", # form feed (FF)
1757 'b' => "\b", # backspace (BS)
1758 'a' => "\a", # alarm (bell) (BEL)
1759 'e' => "\e", # escape (ESC)
1760 'v' => "\013", # vertical tab (VT)
1763 if ($seq =~ m/^[0-7]{1,3}$/) {
1764 # octal char sequence
1765 return chr(oct($seq));
1766 } elsif (exists $es{$seq}) {
1767 # C escape sequence, aka character escape code
1768 return $es{$seq};
1770 # quoted ordinary character
1771 return $seq;
1774 if ($str =~ m/^"(.*)"$/) {
1775 # needs unquoting
1776 $str = $1;
1777 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1779 return $str;
1782 # escape tabs (convert tabs to spaces)
1783 sub untabify {
1784 my $line = shift;
1786 while ((my $pos = index($line, "\t")) != -1) {
1787 if (my $count = (8 - ($pos % 8))) {
1788 my $spaces = ' ' x $count;
1789 $line =~ s/\t/$spaces/;
1793 return $line;
1796 sub project_in_list {
1797 my $project = shift;
1798 my @list = git_get_projects_list();
1799 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1802 ## ----------------------------------------------------------------------
1803 ## HTML aware string manipulation
1805 # Try to chop given string on a word boundary between position
1806 # $len and $len+$add_len. If there is no word boundary there,
1807 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1808 # (marking chopped part) would be longer than given string.
1809 sub chop_str {
1810 my $str = shift;
1811 my $len = shift;
1812 my $add_len = shift || 10;
1813 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1815 # Make sure perl knows it is utf8 encoded so we don't
1816 # cut in the middle of a utf8 multibyte char.
1817 $str = to_utf8($str);
1819 # allow only $len chars, but don't cut a word if it would fit in $add_len
1820 # if it doesn't fit, cut it if it's still longer than the dots we would add
1821 # remove chopped character entities entirely
1823 # when chopping in the middle, distribute $len into left and right part
1824 # return early if chopping wouldn't make string shorter
1825 if ($where eq 'center') {
1826 return $str if ($len + 5 >= length($str)); # filler is length 5
1827 $len = int($len/2);
1828 } else {
1829 return $str if ($len + 4 >= length($str)); # filler is length 4
1832 # regexps: ending and beginning with word part up to $add_len
1833 my $endre = qr/.{$len}\w{0,$add_len}/;
1834 my $begre = qr/\w{0,$add_len}.{$len}/;
1836 if ($where eq 'left') {
1837 $str =~ m/^(.*?)($begre)$/;
1838 my ($lead, $body) = ($1, $2);
1839 if (length($lead) > 4) {
1840 $lead = " ...";
1842 return "$lead$body";
1844 } elsif ($where eq 'center') {
1845 $str =~ m/^($endre)(.*)$/;
1846 my ($left, $str) = ($1, $2);
1847 $str =~ m/^(.*?)($begre)$/;
1848 my ($mid, $right) = ($1, $2);
1849 if (length($mid) > 5) {
1850 $mid = " ... ";
1852 return "$left$mid$right";
1854 } else {
1855 $str =~ m/^($endre)(.*)$/;
1856 my $body = $1;
1857 my $tail = $2;
1858 if (length($tail) > 4) {
1859 $tail = "... ";
1861 return "$body$tail";
1865 # pass-through email filter, obfuscating it when possible
1866 sub email_obfuscate {
1867 our $email;
1868 my ($str) = @_;
1869 if ($email) {
1870 $str = $email->escape_html($str);
1871 # Stock HTML::Email::Obfuscate version likes to produce
1872 # invalid XHTML...
1873 $str =~ s#<(/?)B>#<$1b>#g;
1874 return $str;
1875 } else {
1876 $str = esc_html($str);
1877 $str =~ s/@/&#x40;/;
1878 return $str;
1882 # takes the same arguments as chop_str, but also wraps a <span> around the
1883 # result with a title attribute if it does get chopped. Additionally, the
1884 # string is HTML-escaped.
1885 sub chop_and_escape_str {
1886 my ($str) = @_;
1888 my $chopped = chop_str(@_);
1889 $str = to_utf8($str);
1890 if ($chopped eq $str) {
1891 return email_obfuscate($chopped);
1892 } else {
1893 $str =~ s/[[:cntrl:]]/?/g;
1894 return $cgi->span({-title=>$str}, email_obfuscate($chopped));
1898 # Highlight selected fragments of string, using given CSS class,
1899 # and escape HTML. It is assumed that fragments do not overlap.
1900 # Regions are passed as list of pairs (array references).
1902 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1903 # '<span class="mark">foo</span>bar'
1904 sub esc_html_hl_regions {
1905 my ($str, $css_class, @sel) = @_;
1906 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1907 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1908 return esc_html($str, %opts) unless @sel;
1910 my $out = '';
1911 my $pos = 0;
1913 for my $s (@sel) {
1914 my ($begin, $end) = @$s;
1916 # Don't create empty <span> elements.
1917 next if $end <= $begin;
1919 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1920 %opts);
1922 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1923 if ($begin - $pos > 0);
1924 $out .= $cgi->span({-class => $css_class}, $escaped);
1926 $pos = $end;
1928 $out .= esc_html(substr($str, $pos), %opts)
1929 if ($pos < length($str));
1931 return $out;
1934 # return positions of beginning and end of each match
1935 sub matchpos_list {
1936 my ($str, $regexp) = @_;
1937 return unless (defined $str && defined $regexp);
1939 my @matches;
1940 while ($str =~ /$regexp/g) {
1941 push @matches, [$-[0], $+[0]];
1943 return @matches;
1946 # highlight match (if any), and escape HTML
1947 sub esc_html_match_hl {
1948 my ($str, $regexp) = @_;
1949 return esc_html($str) unless defined $regexp;
1951 my @matches = matchpos_list($str, $regexp);
1952 return esc_html($str) unless @matches;
1954 return esc_html_hl_regions($str, 'match', @matches);
1958 # highlight match (if any) of shortened string, and escape HTML
1959 sub esc_html_match_hl_chopped {
1960 my ($str, $chopped, $regexp) = @_;
1961 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1963 my @matches = matchpos_list($str, $regexp);
1964 return esc_html($chopped) unless @matches;
1966 # filter matches so that we mark chopped string
1967 my $tail = "... "; # see chop_str
1968 unless ($chopped =~ s/\Q$tail\E$//) {
1969 $tail = '';
1971 my $chop_len = length($chopped);
1972 my $tail_len = length($tail);
1973 my @filtered;
1975 for my $m (@matches) {
1976 if ($m->[0] > $chop_len) {
1977 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1978 last;
1979 } elsif ($m->[1] > $chop_len) {
1980 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1981 last;
1983 push @filtered, $m;
1986 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1989 ## ----------------------------------------------------------------------
1990 ## functions returning short strings
1992 # CSS class for given age value (in seconds)
1993 sub age_class {
1994 my $age = shift;
1996 if (!defined $age) {
1997 return "noage";
1998 } elsif ($age < 60*60*2) {
1999 return "age0";
2000 } elsif ($age < 60*60*24*2) {
2001 return "age1";
2002 } else {
2003 return "age2";
2007 # convert age in seconds to "nn units ago" string
2008 sub age_string {
2009 my $age = shift;
2010 my $age_str;
2012 if ($age > 60*60*24*365*2) {
2013 $age_str = (int $age/60/60/24/365);
2014 $age_str .= " years ago";
2015 } elsif ($age > 60*60*24*(365/12)*2) {
2016 $age_str = int $age/60/60/24/(365/12);
2017 $age_str .= " months ago";
2018 } elsif ($age > 60*60*24*7*2) {
2019 $age_str = int $age/60/60/24/7;
2020 $age_str .= " weeks ago";
2021 } elsif ($age > 60*60*24*2) {
2022 $age_str = int $age/60/60/24;
2023 $age_str .= " days ago";
2024 } elsif ($age > 60*60*2) {
2025 $age_str = int $age/60/60;
2026 $age_str .= " hours ago";
2027 } elsif ($age > 60*2) {
2028 $age_str = int $age/60;
2029 $age_str .= " min ago";
2030 } elsif ($age > 2) {
2031 $age_str = int $age;
2032 $age_str .= " sec ago";
2033 } else {
2034 $age_str .= " right now";
2036 return $age_str;
2039 use constant {
2040 S_IFINVALID => 0030000,
2041 S_IFGITLINK => 0160000,
2044 # submodule/subproject, a commit object reference
2045 sub S_ISGITLINK {
2046 my $mode = shift;
2048 return (($mode & S_IFMT) == S_IFGITLINK)
2051 # convert file mode in octal to symbolic file mode string
2052 sub mode_str {
2053 my $mode = oct shift;
2055 if (S_ISGITLINK($mode)) {
2056 return 'm---------';
2057 } elsif (S_ISDIR($mode & S_IFMT)) {
2058 return 'drwxr-xr-x';
2059 } elsif (S_ISLNK($mode)) {
2060 return 'lrwxrwxrwx';
2061 } elsif (S_ISREG($mode)) {
2062 # git cares only about the executable bit
2063 if ($mode & S_IXUSR) {
2064 return '-rwxr-xr-x';
2065 } else {
2066 return '-rw-r--r--';
2068 } else {
2069 return '----------';
2073 # convert file mode in octal to file type string
2074 sub file_type {
2075 my $mode = shift;
2077 if ($mode !~ m/^[0-7]+$/) {
2078 return $mode;
2079 } else {
2080 $mode = oct $mode;
2083 if (S_ISGITLINK($mode)) {
2084 return "submodule";
2085 } elsif (S_ISDIR($mode & S_IFMT)) {
2086 return "directory";
2087 } elsif (S_ISLNK($mode)) {
2088 return "symlink";
2089 } elsif (S_ISREG($mode)) {
2090 return "file";
2091 } else {
2092 return "unknown";
2096 # convert file mode in octal to file type description string
2097 sub file_type_long {
2098 my $mode = shift;
2100 if ($mode !~ m/^[0-7]+$/) {
2101 return $mode;
2102 } else {
2103 $mode = oct $mode;
2106 if (S_ISGITLINK($mode)) {
2107 return "submodule";
2108 } elsif (S_ISDIR($mode & S_IFMT)) {
2109 return "directory";
2110 } elsif (S_ISLNK($mode)) {
2111 return "symlink";
2112 } elsif (S_ISREG($mode)) {
2113 if ($mode & S_IXUSR) {
2114 return "executable";
2115 } else {
2116 return "file";
2118 } else {
2119 return "unknown";
2124 ## ----------------------------------------------------------------------
2125 ## functions returning short HTML fragments, or transforming HTML fragments
2126 ## which don't belong to other sections
2128 # format line of commit message.
2129 sub format_log_line_html {
2130 my $line = shift;
2132 $line = esc_html($line, -nbsp=>1);
2133 $line =~ s{
2136 # The output of "git describe", e.g. v2.10.0-297-gf6727b0
2137 # or hadoop-20160921-113441-20-g094fb7d
2138 (?<!-) # see strbuf_check_tag_ref(). Tags can't start with -
2139 [A-Za-z0-9.-]+
2140 (?!\.) # refs can't end with ".", see check_refname_format()
2141 -g[0-9a-fA-F]{7,40}
2143 # Just a normal looking Git SHA1
2144 [0-9a-fA-F]{7,40}
2148 $cgi->a({-href => href(action=>"object", hash=>$1),
2149 -class => "text"}, $1);
2150 }egx;
2152 return $line;
2155 # format marker of refs pointing to given object
2157 # the destination action is chosen based on object type and current context:
2158 # - for annotated tags, we choose the tag view unless it's the current view
2159 # already, in which case we go to shortlog view
2160 # - for other refs, we keep the current view if we're in history, shortlog or
2161 # log view, and select shortlog otherwise
2162 sub format_ref_marker {
2163 my ($refs, $id) = @_;
2164 my $markers = '';
2166 if (defined $refs->{$id}) {
2167 foreach my $ref (@{$refs->{$id}}) {
2168 # this code exploits the fact that non-lightweight tags are the
2169 # only indirect objects, and that they are the only objects for which
2170 # we want to use tag instead of shortlog as action
2171 my ($type, $name) = qw();
2172 my $indirect = ($ref =~ s/\^\{\}$//);
2173 # e.g. tags/v2.6.11 or heads/next
2174 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2175 $type = $1;
2176 $name = $2;
2177 } else {
2178 $type = "ref";
2179 $name = $ref;
2182 my $class = $type;
2183 $class .= " indirect" if $indirect;
2185 my $dest_action = "shortlog";
2187 if ($indirect) {
2188 $dest_action = "tag" unless $action eq "tag";
2189 } elsif ($action =~ /^(history|(short)?log)$/) {
2190 $dest_action = $action;
2193 my $dest = "";
2194 $dest .= "refs/" unless $ref =~ m!^refs/!;
2195 $dest .= $ref;
2197 my $link = $cgi->a({
2198 -href => href(
2199 action=>$dest_action,
2200 hash=>$dest
2201 )}, esc_html($name));
2203 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2204 $link . "</span>";
2208 if ($markers) {
2209 return ' <span class="refs">'. $markers . '</span>';
2210 } else {
2211 return "";
2215 # format, perhaps shortened and with markers, title line
2216 sub format_subject_html {
2217 my ($long, $short, $href, $extra) = @_;
2218 $extra = '' unless defined($extra);
2220 if (length($short) < length($long)) {
2221 $long =~ s/[[:cntrl:]]/?/g;
2222 return $cgi->a({-href => $href, -class => "list subject",
2223 -title => to_utf8($long)},
2224 esc_html($short)) . $extra;
2225 } else {
2226 return $cgi->a({-href => $href, -class => "list subject"},
2227 esc_html($long)) . $extra;
2231 # Rather than recomputing the url for an email multiple times, we cache it
2232 # after the first hit. This gives a visible benefit in views where the avatar
2233 # for the same email is used repeatedly (e.g. shortlog).
2234 # The cache is shared by all avatar engines (currently gravatar only), which
2235 # are free to use it as preferred. Since only one avatar engine is used for any
2236 # given page, there's no risk for cache conflicts.
2237 our %avatar_cache = ();
2239 # Compute the picon url for a given email, by using the picon search service over at
2240 # http://www.cs.indiana.edu/picons/search.html
2241 sub picon_url {
2242 my $email = lc shift;
2243 if (!$avatar_cache{$email}) {
2244 my ($user, $domain) = split('@', $email);
2245 $avatar_cache{$email} =
2246 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2247 "$domain/$user/" .
2248 "users+domains+unknown/up/single";
2250 return $avatar_cache{$email};
2253 # Compute the gravatar url for a given email, if it's not in the cache already.
2254 # Gravatar stores only the part of the URL before the size, since that's the
2255 # one computationally more expensive. This also allows reuse of the cache for
2256 # different sizes (for this particular engine).
2257 sub gravatar_url {
2258 my $email = lc shift;
2259 my $size = shift;
2260 $avatar_cache{$email} ||=
2261 "//www.gravatar.com/avatar/" .
2262 Digest::MD5::md5_hex($email) . "?s=";
2263 return $avatar_cache{$email} . $size;
2266 # Insert an avatar for the given $email at the given $size if the feature
2267 # is enabled.
2268 sub git_get_avatar {
2269 my ($email, %opts) = @_;
2270 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2271 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2272 $opts{-size} ||= 'default';
2273 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2274 my $url = "";
2275 if ($git_avatar eq 'gravatar') {
2276 $url = gravatar_url($email, $size);
2277 } elsif ($git_avatar eq 'picon') {
2278 $url = picon_url($email);
2280 # Other providers can be added by extending the if chain, defining $url
2281 # as needed. If no variant puts something in $url, we assume avatars
2282 # are completely disabled/unavailable.
2283 if ($url) {
2284 return $pre_white .
2285 "<img width=\"$size\" " .
2286 "class=\"avatar\" " .
2287 "src=\"".esc_url($url)."\" " .
2288 "alt=\"\" " .
2289 "/>" . $post_white;
2290 } else {
2291 return "";
2295 sub format_search_author {
2296 my ($author, $searchtype, $displaytext) = @_;
2297 my $have_search = gitweb_check_feature('search');
2299 if ($have_search) {
2300 my $performed = "";
2301 if ($searchtype eq 'author') {
2302 $performed = "authored";
2303 } elsif ($searchtype eq 'committer') {
2304 $performed = "committed";
2307 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2308 searchtext=>$author,
2309 searchtype=>$searchtype), class=>"list",
2310 title=>"Search for commits $performed by $author"},
2311 $displaytext);
2313 } else {
2314 return $displaytext;
2318 # format the author name of the given commit with the given tag
2319 # the author name is chopped and escaped according to the other
2320 # optional parameters (see chop_str).
2321 sub format_author_html {
2322 my $tag = shift;
2323 my $co = shift;
2324 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2325 return "<$tag class=\"author\">" .
2326 format_search_author($co->{'author_name'}, "author",
2327 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2328 $author) .
2329 "</$tag>";
2332 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2333 sub format_git_diff_header_line {
2334 my $line = shift;
2335 my $diffinfo = shift;
2336 my ($from, $to) = @_;
2338 if ($diffinfo->{'nparents'}) {
2339 # combined diff
2340 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2341 if ($to->{'href'}) {
2342 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2343 esc_path($to->{'file'}));
2344 } else { # file was deleted (no href)
2345 $line .= esc_path($to->{'file'});
2347 } else {
2348 # "ordinary" diff
2349 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2350 if ($from->{'href'}) {
2351 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2352 'a/' . esc_path($from->{'file'}));
2353 } else { # file was added (no href)
2354 $line .= 'a/' . esc_path($from->{'file'});
2356 $line .= ' ';
2357 if ($to->{'href'}) {
2358 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2359 'b/' . esc_path($to->{'file'}));
2360 } else { # file was deleted
2361 $line .= 'b/' . esc_path($to->{'file'});
2365 return "<div class=\"diff header\">$line</div>\n";
2368 # format extended diff header line, before patch itself
2369 sub format_extended_diff_header_line {
2370 my $line = shift;
2371 my $diffinfo = shift;
2372 my ($from, $to) = @_;
2374 # match <path>
2375 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2376 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2377 esc_path($from->{'file'}));
2379 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2380 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2381 esc_path($to->{'file'}));
2383 # match single <mode>
2384 if ($line =~ m/\s(\d{6})$/) {
2385 $line .= '<span class="info"> (' .
2386 file_type_long($1) .
2387 ')</span>';
2389 # match <hash>
2390 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2391 # can match only for combined diff
2392 $line = 'index ';
2393 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2394 if ($from->{'href'}[$i]) {
2395 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2396 -class=>"hash"},
2397 substr($diffinfo->{'from_id'}[$i],0,7));
2398 } else {
2399 $line .= '0' x 7;
2401 # separator
2402 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2404 $line .= '..';
2405 if ($to->{'href'}) {
2406 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2407 substr($diffinfo->{'to_id'},0,7));
2408 } else {
2409 $line .= '0' x 7;
2412 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2413 # can match only for ordinary diff
2414 my ($from_link, $to_link);
2415 if ($from->{'href'}) {
2416 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2417 substr($diffinfo->{'from_id'},0,7));
2418 } else {
2419 $from_link = '0' x 7;
2421 if ($to->{'href'}) {
2422 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2423 substr($diffinfo->{'to_id'},0,7));
2424 } else {
2425 $to_link = '0' x 7;
2427 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2428 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2431 return $line . "<br/>\n";
2434 # format from-file/to-file diff header
2435 sub format_diff_from_to_header {
2436 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2437 my $line;
2438 my $result = '';
2440 $line = $from_line;
2441 #assert($line =~ m/^---/) if DEBUG;
2442 # no extra formatting for "^--- /dev/null"
2443 if (! $diffinfo->{'nparents'}) {
2444 # ordinary (single parent) diff
2445 if ($line =~ m!^--- "?a/!) {
2446 if ($from->{'href'}) {
2447 $line = '--- a/' .
2448 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2449 esc_path($from->{'file'}));
2450 } else {
2451 $line = '--- a/' .
2452 esc_path($from->{'file'});
2455 $result .= qq!<div class="diff from_file">$line</div>\n!;
2457 } else {
2458 # combined diff (merge commit)
2459 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2460 if ($from->{'href'}[$i]) {
2461 $line = '--- ' .
2462 $cgi->a({-href=>href(action=>"blobdiff",
2463 hash_parent=>$diffinfo->{'from_id'}[$i],
2464 hash_parent_base=>$parents[$i],
2465 file_parent=>$from->{'file'}[$i],
2466 hash=>$diffinfo->{'to_id'},
2467 hash_base=>$hash,
2468 file_name=>$to->{'file'}),
2469 -class=>"path",
2470 -title=>"diff" . ($i+1)},
2471 $i+1) .
2472 '/' .
2473 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2474 esc_path($from->{'file'}[$i]));
2475 } else {
2476 $line = '--- /dev/null';
2478 $result .= qq!<div class="diff from_file">$line</div>\n!;
2482 $line = $to_line;
2483 #assert($line =~ m/^\+\+\+/) if DEBUG;
2484 # no extra formatting for "^+++ /dev/null"
2485 if ($line =~ m!^\+\+\+ "?b/!) {
2486 if ($to->{'href'}) {
2487 $line = '+++ b/' .
2488 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2489 esc_path($to->{'file'}));
2490 } else {
2491 $line = '+++ b/' .
2492 esc_path($to->{'file'});
2495 $result .= qq!<div class="diff to_file">$line</div>\n!;
2497 return $result;
2500 # create note for patch simplified by combined diff
2501 sub format_diff_cc_simplified {
2502 my ($diffinfo, @parents) = @_;
2503 my $result = '';
2505 $result .= "<div class=\"diff header\">" .
2506 "diff --cc ";
2507 if (!is_deleted($diffinfo)) {
2508 $result .= $cgi->a({-href => href(action=>"blob",
2509 hash_base=>$hash,
2510 hash=>$diffinfo->{'to_id'},
2511 file_name=>$diffinfo->{'to_file'}),
2512 -class => "path"},
2513 esc_path($diffinfo->{'to_file'}));
2514 } else {
2515 $result .= esc_path($diffinfo->{'to_file'});
2517 $result .= "</div>\n" . # class="diff header"
2518 "<div class=\"diff nodifferences\">" .
2519 "Simple merge" .
2520 "</div>\n"; # class="diff nodifferences"
2522 return $result;
2525 sub diff_line_class {
2526 my ($line, $from, $to) = @_;
2528 # ordinary diff
2529 my $num_sign = 1;
2530 # combined diff
2531 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2532 $num_sign = scalar @{$from->{'href'}};
2535 my @diff_line_classifier = (
2536 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2537 { regexp => qr/^\\/, class => "incomplete" },
2538 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2539 # classifier for context must come before classifier add/rem,
2540 # or we would have to use more complicated regexp, for example
2541 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2542 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2543 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2545 for my $clsfy (@diff_line_classifier) {
2546 return $clsfy->{'class'}
2547 if ($line =~ $clsfy->{'regexp'});
2550 # fallback
2551 return "";
2554 # assumes that $from and $to are defined and correctly filled,
2555 # and that $line holds a line of chunk header for unified diff
2556 sub format_unidiff_chunk_header {
2557 my ($line, $from, $to) = @_;
2559 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2560 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2562 $from_lines = 0 unless defined $from_lines;
2563 $to_lines = 0 unless defined $to_lines;
2565 if ($from->{'href'}) {
2566 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2567 -class=>"list"}, $from_text);
2569 if ($to->{'href'}) {
2570 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2571 -class=>"list"}, $to_text);
2573 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2574 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2575 return $line;
2578 # assumes that $from and $to are defined and correctly filled,
2579 # and that $line holds a line of chunk header for combined diff
2580 sub format_cc_diff_chunk_header {
2581 my ($line, $from, $to) = @_;
2583 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2584 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2586 @from_text = split(' ', $ranges);
2587 for (my $i = 0; $i < @from_text; ++$i) {
2588 ($from_start[$i], $from_nlines[$i]) =
2589 (split(',', substr($from_text[$i], 1)), 0);
2592 $to_text = pop @from_text;
2593 $to_start = pop @from_start;
2594 $to_nlines = pop @from_nlines;
2596 $line = "<span class=\"chunk_info\">$prefix ";
2597 for (my $i = 0; $i < @from_text; ++$i) {
2598 if ($from->{'href'}[$i]) {
2599 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2600 -class=>"list"}, $from_text[$i]);
2601 } else {
2602 $line .= $from_text[$i];
2604 $line .= " ";
2606 if ($to->{'href'}) {
2607 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2608 -class=>"list"}, $to_text);
2609 } else {
2610 $line .= $to_text;
2612 $line .= " $prefix</span>" .
2613 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2614 return $line;
2617 # process patch (diff) line (not to be used for diff headers),
2618 # returning HTML-formatted (but not wrapped) line.
2619 # If the line is passed as a reference, it is treated as HTML and not
2620 # esc_html()'ed.
2621 sub format_diff_line {
2622 my ($line, $diff_class, $from, $to) = @_;
2624 if (ref($line)) {
2625 $line = $$line;
2626 } else {
2627 chomp $line;
2628 $line = untabify($line);
2630 if ($from && $to && $line =~ m/^\@{2} /) {
2631 $line = format_unidiff_chunk_header($line, $from, $to);
2632 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2633 $line = format_cc_diff_chunk_header($line, $from, $to);
2634 } else {
2635 $line = esc_html($line, -nbsp=>1);
2639 my $diff_classes = "diff";
2640 $diff_classes .= " $diff_class" if ($diff_class);
2641 $line = "<div class=\"$diff_classes\">$line</div>\n";
2643 return $line;
2646 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2647 # linked. Pass the hash of the tree/commit to snapshot.
2648 sub format_snapshot_links {
2649 my ($hash) = @_;
2650 my $num_fmts = @snapshot_fmts;
2651 if ($num_fmts > 1) {
2652 # A parenthesized list of links bearing format names.
2653 # e.g. "snapshot (_tar.gz_ _zip_)"
2654 return "snapshot (" . join(' ', map
2655 $cgi->a({
2656 -href => href(
2657 action=>"snapshot",
2658 hash=>$hash,
2659 snapshot_format=>$_
2661 }, $known_snapshot_formats{$_}{'display'})
2662 , @snapshot_fmts) . ")";
2663 } elsif ($num_fmts == 1) {
2664 # A single "snapshot" link whose tooltip bears the format name.
2665 # i.e. "_snapshot_"
2666 my ($fmt) = @snapshot_fmts;
2667 return
2668 $cgi->a({
2669 -href => href(
2670 action=>"snapshot",
2671 hash=>$hash,
2672 snapshot_format=>$fmt
2674 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2675 }, "snapshot");
2676 } else { # $num_fmts == 0
2677 return undef;
2681 ## ......................................................................
2682 ## functions returning values to be passed, perhaps after some
2683 ## transformation, to other functions; e.g. returning arguments to href()
2685 # returns hash to be passed to href to generate gitweb URL
2686 # in -title key it returns description of link
2687 sub get_feed_info {
2688 my $format = shift || 'Atom';
2689 my %res = (action => lc($format));
2690 my $matched_ref = 0;
2692 # feed links are possible only for project views
2693 return unless (defined $project);
2694 # some views should link to OPML, or to generic project feed,
2695 # or don't have specific feed yet (so they should use generic)
2696 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2698 my $branch = undef;
2699 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2700 # (fullname) to differentiate from tag links; this also makes
2701 # possible to detect branch links
2702 for my $ref (get_branch_refs()) {
2703 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2704 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2705 $branch = $1;
2706 $matched_ref = $ref;
2707 last;
2710 # find log type for feed description (title)
2711 my $type = 'log';
2712 if (defined $file_name) {
2713 $type = "history of $file_name";
2714 $type .= "/" if ($action eq 'tree');
2715 $type .= " on '$branch'" if (defined $branch);
2716 } else {
2717 $type = "log of $branch" if (defined $branch);
2720 $res{-title} = $type;
2721 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2722 $res{'file_name'} = $file_name;
2724 return %res;
2727 ## ----------------------------------------------------------------------
2728 ## git utility subroutines, invoking git commands
2730 # returns path to the core git executable and the --git-dir parameter as list
2731 sub git_cmd {
2732 $number_of_git_cmds++;
2733 return $GIT, '--git-dir='.$git_dir;
2736 # quote the given arguments for passing them to the shell
2737 # quote_command("command", "arg 1", "arg with ' and ! characters")
2738 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2739 # Try to avoid using this function wherever possible.
2740 sub quote_command {
2741 return join(' ',
2742 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2745 # get HEAD ref of given project as hash
2746 sub git_get_head_hash {
2747 return git_get_full_hash(shift, 'HEAD');
2750 sub git_get_full_hash {
2751 return git_get_hash(@_);
2754 sub git_get_short_hash {
2755 return git_get_hash(@_, '--short=7');
2758 sub git_get_hash {
2759 my ($project, $hash, @options) = @_;
2760 my $o_git_dir = $git_dir;
2761 my $retval = undef;
2762 $git_dir = "$projectroot/$project";
2763 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2764 '--verify', '-q', @options, $hash) {
2765 $retval = <$fd>;
2766 chomp $retval if defined $retval;
2767 close $fd;
2769 if (defined $o_git_dir) {
2770 $git_dir = $o_git_dir;
2772 return $retval;
2775 # get type of given object
2776 sub git_get_type {
2777 my $hash = shift;
2779 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2780 my $type = <$fd>;
2781 close $fd or return;
2782 chomp $type;
2783 return $type;
2786 # repository configuration
2787 our $config_file = '';
2788 our %config;
2790 # store multiple values for single key as anonymous array reference
2791 # single values stored directly in the hash, not as [ <value> ]
2792 sub hash_set_multi {
2793 my ($hash, $key, $value) = @_;
2795 if (!exists $hash->{$key}) {
2796 $hash->{$key} = $value;
2797 } elsif (!ref $hash->{$key}) {
2798 $hash->{$key} = [ $hash->{$key}, $value ];
2799 } else {
2800 push @{$hash->{$key}}, $value;
2804 # return hash of git project configuration
2805 # optionally limited to some section, e.g. 'gitweb'
2806 sub git_parse_project_config {
2807 my $section_regexp = shift;
2808 my %config;
2810 local $/ = "\0";
2812 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2813 or return;
2815 while (my $keyval = <$fh>) {
2816 chomp $keyval;
2817 my ($key, $value) = split(/\n/, $keyval, 2);
2819 hash_set_multi(\%config, $key, $value)
2820 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2822 close $fh;
2824 return %config;
2827 # convert config value to boolean: 'true' or 'false'
2828 # no value, number > 0, 'true' and 'yes' values are true
2829 # rest of values are treated as false (never as error)
2830 sub config_to_bool {
2831 my $val = shift;
2833 return 1 if !defined $val; # section.key
2835 # strip leading and trailing whitespace
2836 $val =~ s/^\s+//;
2837 $val =~ s/\s+$//;
2839 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2840 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2843 # convert config value to simple decimal number
2844 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2845 # to be multiplied by 1024, 1048576, or 1073741824
2846 sub config_to_int {
2847 my $val = shift;
2849 # strip leading and trailing whitespace
2850 $val =~ s/^\s+//;
2851 $val =~ s/\s+$//;
2853 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2854 $unit = lc($unit);
2855 # unknown unit is treated as 1
2856 return $num * ($unit eq 'g' ? 1073741824 :
2857 $unit eq 'm' ? 1048576 :
2858 $unit eq 'k' ? 1024 : 1);
2860 return $val;
2863 # convert config value to array reference, if needed
2864 sub config_to_multi {
2865 my $val = shift;
2867 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2870 sub git_get_project_config {
2871 my ($key, $type) = @_;
2873 return unless defined $git_dir;
2875 # key sanity check
2876 return unless ($key);
2877 # only subsection, if exists, is case sensitive,
2878 # and not lowercased by 'git config -z -l'
2879 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2880 $lo =~ s/_//g;
2881 $key = join(".", lc($hi), $mi, lc($lo));
2882 return if ($lo =~ /\W/ || $hi =~ /\W/);
2883 } else {
2884 $key = lc($key);
2885 $key =~ s/_//g;
2886 return if ($key =~ /\W/);
2888 $key =~ s/^gitweb\.//;
2890 # type sanity check
2891 if (defined $type) {
2892 $type =~ s/^--//;
2893 $type = undef
2894 unless ($type eq 'bool' || $type eq 'int');
2897 # get config
2898 if (!defined $config_file ||
2899 $config_file ne "$git_dir/config") {
2900 %config = git_parse_project_config('gitweb');
2901 $config_file = "$git_dir/config";
2904 # check if config variable (key) exists
2905 return unless exists $config{"gitweb.$key"};
2907 # ensure given type
2908 if (!defined $type) {
2909 return $config{"gitweb.$key"};
2910 } elsif ($type eq 'bool') {
2911 # backward compatibility: 'git config --bool' returns true/false
2912 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2913 } elsif ($type eq 'int') {
2914 return config_to_int($config{"gitweb.$key"});
2916 return $config{"gitweb.$key"};
2919 # get hash of given path at given ref
2920 sub git_get_hash_by_path {
2921 my $base = shift;
2922 my $path = shift || return undef;
2923 my $type = shift;
2925 $path =~ s,/+$,,;
2927 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2928 or die_error(500, "Open git-ls-tree failed");
2929 my $line = <$fd>;
2930 close $fd or return undef;
2932 if (!defined $line) {
2933 # there is no tree or hash given by $path at $base
2934 return undef;
2937 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2938 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2939 if (defined $type && $type ne $2) {
2940 # type doesn't match
2941 return undef;
2943 return $3;
2946 # get path of entry with given hash at given tree-ish (ref)
2947 # used to get 'from' filename for combined diff (merge commit) for renames
2948 sub git_get_path_by_hash {
2949 my $base = shift || return;
2950 my $hash = shift || return;
2952 local $/ = "\0";
2954 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2955 or return undef;
2956 while (my $line = <$fd>) {
2957 chomp $line;
2959 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2960 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2961 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2962 close $fd;
2963 return $1;
2966 close $fd;
2967 return undef;
2970 ## ......................................................................
2971 ## git utility functions, directly accessing git repository
2973 # get the value of config variable either from file named as the variable
2974 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2975 # configuration variable in the repository config file.
2976 sub git_get_file_or_project_config {
2977 my ($path, $name) = @_;
2979 $git_dir = "$projectroot/$path";
2980 open my $fd, '<', "$git_dir/$name"
2981 or return git_get_project_config($name);
2982 my $conf = <$fd>;
2983 close $fd;
2984 if (defined $conf) {
2985 chomp $conf;
2987 return $conf;
2990 sub git_get_project_description {
2991 my $path = shift;
2992 return git_get_file_or_project_config($path, 'description');
2995 sub git_get_project_category {
2996 my $path = shift;
2997 return git_get_file_or_project_config($path, 'category');
3001 # supported formats:
3002 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
3003 # - if its contents is a number, use it as tag weight,
3004 # - otherwise add a tag with weight 1
3005 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
3006 # the same value multiple times increases tag weight
3007 # * `gitweb.ctag' multi-valued repo config variable
3008 sub git_get_project_ctags {
3009 my $project = shift;
3010 my $ctags = {};
3012 $git_dir = "$projectroot/$project";
3013 if (opendir my $dh, "$git_dir/ctags") {
3014 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
3015 foreach my $tagfile (@files) {
3016 open my $ct, '<', $tagfile
3017 or next;
3018 my $val = <$ct>;
3019 chomp $val if $val;
3020 close $ct;
3022 (my $ctag = $tagfile) =~ s#.*/##;
3023 if ($val =~ /^\d+$/) {
3024 $ctags->{$ctag} = $val;
3025 } else {
3026 $ctags->{$ctag} = 1;
3029 closedir $dh;
3031 } elsif (open my $fh, '<', "$git_dir/ctags") {
3032 while (my $line = <$fh>) {
3033 chomp $line;
3034 $ctags->{$line}++ if $line;
3036 close $fh;
3038 } else {
3039 my $taglist = config_to_multi(git_get_project_config('ctag'));
3040 foreach my $tag (@$taglist) {
3041 $ctags->{$tag}++;
3045 return $ctags;
3048 # return hash, where keys are content tags ('ctags'),
3049 # and values are sum of weights of given tag in every project
3050 sub git_gather_all_ctags {
3051 my $projects = shift;
3052 my $ctags = {};
3054 foreach my $p (@$projects) {
3055 foreach my $ct (keys %{$p->{'ctags'}}) {
3056 $ctags->{$ct} += $p->{'ctags'}->{$ct};
3060 return $ctags;
3063 sub git_populate_project_tagcloud {
3064 my $ctags = shift;
3066 # First, merge different-cased tags; tags vote on casing
3067 my %ctags_lc;
3068 foreach (keys %$ctags) {
3069 $ctags_lc{lc $_}->{count} += $ctags->{$_};
3070 if (not $ctags_lc{lc $_}->{topcount}
3071 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
3072 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
3073 $ctags_lc{lc $_}->{topname} = $_;
3077 my $cloud;
3078 my $matched = $input_params{'ctag'};
3079 if (eval { require HTML::TagCloud; 1; }) {
3080 $cloud = HTML::TagCloud->new;
3081 foreach my $ctag (sort keys %ctags_lc) {
3082 # Pad the title with spaces so that the cloud looks
3083 # less crammed.
3084 my $title = esc_html($ctags_lc{$ctag}->{topname});
3085 $title =~ s/ /&nbsp;/g;
3086 $title =~ s/^/&nbsp;/g;
3087 $title =~ s/$/&nbsp;/g;
3088 if (defined $matched && $matched eq $ctag) {
3089 $title = qq(<span class="match">$title</span>);
3091 $cloud->add($title, href(project=>undef, ctag=>$ctag),
3092 $ctags_lc{$ctag}->{count});
3094 } else {
3095 $cloud = {};
3096 foreach my $ctag (keys %ctags_lc) {
3097 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3098 if (defined $matched && $matched eq $ctag) {
3099 $title = qq(<span class="match">$title</span>);
3101 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3102 $cloud->{$ctag}{ctag} =
3103 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3106 return $cloud;
3109 sub git_show_project_tagcloud {
3110 my ($cloud, $count) = @_;
3111 if (ref $cloud eq 'HTML::TagCloud') {
3112 return $cloud->html_and_css($count);
3113 } else {
3114 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3115 return
3116 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3117 join (', ', map {
3118 $cloud->{$_}->{'ctag'}
3119 } splice(@tags, 0, $count)) .
3120 '</div>';
3124 sub git_get_project_url_list {
3125 my $path = shift;
3127 $git_dir = "$projectroot/$path";
3128 open my $fd, '<', "$git_dir/cloneurl"
3129 or return wantarray ?
3130 @{ config_to_multi(git_get_project_config('url')) } :
3131 config_to_multi(git_get_project_config('url'));
3132 my @git_project_url_list = map { chomp; $_ } <$fd>;
3133 close $fd;
3135 return wantarray ? @git_project_url_list : \@git_project_url_list;
3138 sub git_get_projects_list {
3139 my $filter = shift || '';
3140 my $paranoid = shift;
3141 my @list;
3143 if (-d $projects_list) {
3144 # search in directory
3145 my $dir = $projects_list;
3146 # remove the trailing "/"
3147 $dir =~ s!/+$!!;
3148 my $pfxlen = length("$dir");
3149 my $pfxdepth = ($dir =~ tr!/!!);
3150 # when filtering, search only given subdirectory
3151 if ($filter && !$paranoid) {
3152 $dir .= "/$filter";
3153 $dir =~ s!/+$!!;
3156 File::Find::find({
3157 follow_fast => 1, # follow symbolic links
3158 follow_skip => 2, # ignore duplicates
3159 dangling_symlinks => 0, # ignore dangling symlinks, silently
3160 wanted => sub {
3161 # global variables
3162 our $project_maxdepth;
3163 our $projectroot;
3164 # skip project-list toplevel, if we get it.
3165 return if (m!^[/.]$!);
3166 # only directories can be git repositories
3167 return unless (-d $_);
3168 # don't traverse too deep (Find is super slow on os x)
3169 # $project_maxdepth excludes depth of $projectroot
3170 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3171 $File::Find::prune = 1;
3172 return;
3175 my $path = substr($File::Find::name, $pfxlen + 1);
3176 # paranoidly only filter here
3177 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3178 next;
3180 # we check related file in $projectroot
3181 if (check_export_ok("$projectroot/$path")) {
3182 push @list, { path => $path };
3183 $File::Find::prune = 1;
3186 }, "$dir");
3188 } elsif (-f $projects_list) {
3189 # read from file(url-encoded):
3190 # 'git%2Fgit.git Linus+Torvalds'
3191 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3192 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3193 open my $fd, '<', $projects_list or return;
3194 PROJECT:
3195 while (my $line = <$fd>) {
3196 chomp $line;
3197 my ($path, $owner) = split ' ', $line;
3198 $path = unescape($path);
3199 $owner = unescape($owner);
3200 if (!defined $path) {
3201 next;
3203 # if $filter is rpovided, check if $path begins with $filter
3204 if ($filter && $path !~ m!^\Q$filter\E/!) {
3205 next;
3207 if (check_export_ok("$projectroot/$path")) {
3208 my $pr = {
3209 path => $path
3211 if ($owner) {
3212 $pr->{'owner'} = to_utf8($owner);
3214 push @list, $pr;
3217 close $fd;
3219 return @list;
3222 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3223 # as side effects it sets 'forks' field to list of forks for forked projects
3224 sub filter_forks_from_projects_list {
3225 my $projects = shift;
3227 my %trie; # prefix tree of directories (path components)
3228 # generate trie out of those directories that might contain forks
3229 foreach my $pr (@$projects) {
3230 my $path = $pr->{'path'};
3231 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3232 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3233 next unless ($path); # skip '.git' repository: tests, git-instaweb
3234 next unless (-d "$projectroot/$path"); # containing directory exists
3235 $pr->{'forks'} = []; # there can be 0 or more forks of project
3237 # add to trie
3238 my @dirs = split('/', $path);
3239 # walk the trie, until either runs out of components or out of trie
3240 my $ref = \%trie;
3241 while (scalar @dirs &&
3242 exists($ref->{$dirs[0]})) {
3243 $ref = $ref->{shift @dirs};
3245 # create rest of trie structure from rest of components
3246 foreach my $dir (@dirs) {
3247 $ref = $ref->{$dir} = {};
3249 # create end marker, store $pr as a data
3250 $ref->{''} = $pr if (!exists $ref->{''});
3253 # filter out forks, by finding shortest prefix match for paths
3254 my @filtered;
3255 PROJECT:
3256 foreach my $pr (@$projects) {
3257 # trie lookup
3258 my $ref = \%trie;
3259 DIR:
3260 foreach my $dir (split('/', $pr->{'path'})) {
3261 if (exists $ref->{''}) {
3262 # found [shortest] prefix, is a fork - skip it
3263 push @{$ref->{''}{'forks'}}, $pr;
3264 next PROJECT;
3266 if (!exists $ref->{$dir}) {
3267 # not in trie, cannot have prefix, not a fork
3268 push @filtered, $pr;
3269 next PROJECT;
3271 # If the dir is there, we just walk one step down the trie.
3272 $ref = $ref->{$dir};
3274 # we ran out of trie
3275 # (shouldn't happen: it's either no match, or end marker)
3276 push @filtered, $pr;
3279 return @filtered;
3282 # note: fill_project_list_info must be run first,
3283 # for 'descr_long' and 'ctags' to be filled
3284 sub search_projects_list {
3285 my ($projlist, %opts) = @_;
3286 my $tagfilter = $opts{'tagfilter'};
3287 my $search_re = $opts{'search_regexp'};
3289 return @$projlist
3290 unless ($tagfilter || $search_re);
3292 # searching projects require filling to be run before it;
3293 fill_project_list_info($projlist,
3294 $tagfilter ? 'ctags' : (),
3295 $search_re ? ('path', 'descr') : ());
3296 my @projects;
3297 PROJECT:
3298 foreach my $pr (@$projlist) {
3300 if ($tagfilter) {
3301 next unless ref($pr->{'ctags'}) eq 'HASH';
3302 next unless
3303 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3306 if ($search_re) {
3307 next unless
3308 $pr->{'path'} =~ /$search_re/ ||
3309 $pr->{'descr_long'} =~ /$search_re/;
3312 push @projects, $pr;
3315 return @projects;
3318 our $gitweb_project_owner = undef;
3319 sub git_get_project_list_from_file {
3321 return if (defined $gitweb_project_owner);
3323 $gitweb_project_owner = {};
3324 # read from file (url-encoded):
3325 # 'git%2Fgit.git Linus+Torvalds'
3326 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3327 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3328 if (-f $projects_list) {
3329 open(my $fd, '<', $projects_list);
3330 while (my $line = <$fd>) {
3331 chomp $line;
3332 my ($pr, $ow) = split ' ', $line;
3333 $pr = unescape($pr);
3334 $ow = unescape($ow);
3335 $gitweb_project_owner->{$pr} = to_utf8($ow);
3337 close $fd;
3341 sub git_get_project_owner {
3342 my $project = shift;
3343 my $owner;
3345 return undef unless $project;
3346 $git_dir = "$projectroot/$project";
3348 if (!defined $gitweb_project_owner) {
3349 git_get_project_list_from_file();
3352 if (exists $gitweb_project_owner->{$project}) {
3353 $owner = $gitweb_project_owner->{$project};
3355 if (!defined $owner){
3356 $owner = git_get_project_config('owner');
3358 if (!defined $owner) {
3359 $owner = get_file_owner("$git_dir");
3362 return $owner;
3365 sub git_get_last_activity {
3366 my ($path) = @_;
3367 my $fd;
3369 $git_dir = "$projectroot/$path";
3370 open($fd, "-|", git_cmd(), 'for-each-ref',
3371 '--format=%(committer)',
3372 '--sort=-committerdate',
3373 '--count=1',
3374 map { "refs/$_" } get_branch_refs ()) or return;
3375 my $most_recent = <$fd>;
3376 close $fd or return;
3377 if (defined $most_recent &&
3378 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3379 my $timestamp = $1;
3380 my $age = time - $timestamp;
3381 return ($age, age_string($age));
3383 return (undef, undef);
3386 # Implementation note: when a single remote is wanted, we cannot use 'git
3387 # remote show -n' because that command always work (assuming it's a remote URL
3388 # if it's not defined), and we cannot use 'git remote show' because that would
3389 # try to make a network roundtrip. So the only way to find if that particular
3390 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3391 # and when we find what we want.
3392 sub git_get_remotes_list {
3393 my $wanted = shift;
3394 my %remotes = ();
3396 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3397 return unless $fd;
3398 while (my $remote = <$fd>) {
3399 chomp $remote;
3400 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3401 next if $wanted and not $remote eq $wanted;
3402 my ($url, $key) = ($1, $2);
3404 $remotes{$remote} ||= { 'heads' => () };
3405 $remotes{$remote}{$key} = $url;
3407 close $fd or return;
3408 return wantarray ? %remotes : \%remotes;
3411 # Takes a hash of remotes as first parameter and fills it by adding the
3412 # available remote heads for each of the indicated remotes.
3413 sub fill_remote_heads {
3414 my $remotes = shift;
3415 my @heads = map { "remotes/$_" } keys %$remotes;
3416 my @remoteheads = git_get_heads_list(undef, @heads);
3417 foreach my $remote (keys %$remotes) {
3418 $remotes->{$remote}{'heads'} = [ grep {
3419 $_->{'name'} =~ s!^$remote/!!
3420 } @remoteheads ];
3424 sub git_get_references {
3425 my $type = shift || "";
3426 my %refs;
3427 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3428 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3429 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3430 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3431 or return;
3433 while (my $line = <$fd>) {
3434 chomp $line;
3435 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3436 if (defined $refs{$1}) {
3437 push @{$refs{$1}}, $2;
3438 } else {
3439 $refs{$1} = [ $2 ];
3443 close $fd or return;
3444 return \%refs;
3447 sub git_get_rev_name_tags {
3448 my $hash = shift || return undef;
3450 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3451 or return;
3452 my $name_rev = <$fd>;
3453 close $fd;
3455 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3456 return $1;
3457 } else {
3458 # catches also '$hash undefined' output
3459 return undef;
3463 ## ----------------------------------------------------------------------
3464 ## parse to hash functions
3466 sub parse_date {
3467 my $epoch = shift;
3468 my $tz = shift || "-0000";
3470 my %date;
3471 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3472 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3473 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3474 $date{'hour'} = $hour;
3475 $date{'minute'} = $min;
3476 $date{'mday'} = $mday;
3477 $date{'day'} = $days[$wday];
3478 $date{'month'} = $months[$mon];
3479 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3480 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3481 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3482 $mday, $months[$mon], $hour ,$min;
3483 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3484 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3486 my ($tz_sign, $tz_hour, $tz_min) =
3487 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3488 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3489 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3490 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3491 $date{'hour_local'} = $hour;
3492 $date{'minute_local'} = $min;
3493 $date{'tz_local'} = $tz;
3494 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3495 1900+$year, $mon+1, $mday,
3496 $hour, $min, $sec, $tz);
3497 return %date;
3500 sub parse_tag {
3501 my $tag_id = shift;
3502 my %tag;
3503 my @comment;
3505 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3506 $tag{'id'} = $tag_id;
3507 while (my $line = <$fd>) {
3508 chomp $line;
3509 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3510 $tag{'object'} = $1;
3511 } elsif ($line =~ m/^type (.+)$/) {
3512 $tag{'type'} = $1;
3513 } elsif ($line =~ m/^tag (.+)$/) {
3514 $tag{'name'} = $1;
3515 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3516 $tag{'author'} = $1;
3517 $tag{'author_epoch'} = $2;
3518 $tag{'author_tz'} = $3;
3519 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3520 $tag{'author_name'} = $1;
3521 $tag{'author_email'} = $2;
3522 } else {
3523 $tag{'author_name'} = $tag{'author'};
3525 } elsif ($line =~ m/--BEGIN/) {
3526 push @comment, $line;
3527 last;
3528 } elsif ($line eq "") {
3529 last;
3532 push @comment, <$fd>;
3533 $tag{'comment'} = \@comment;
3534 close $fd or return;
3535 if (!defined $tag{'name'}) {
3536 return
3538 return %tag
3541 sub parse_commit_text {
3542 my ($commit_text, $withparents) = @_;
3543 my @commit_lines = split '\n', $commit_text;
3544 my %co;
3546 pop @commit_lines; # Remove '\0'
3548 if (! @commit_lines) {
3549 return;
3552 my $header = shift @commit_lines;
3553 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3554 return;
3556 ($co{'id'}, my @parents) = split ' ', $header;
3557 while (my $line = shift @commit_lines) {
3558 last if $line eq "\n";
3559 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3560 $co{'tree'} = $1;
3561 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3562 push @parents, $1;
3563 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3564 $co{'author'} = to_utf8($1);
3565 $co{'author_epoch'} = $2;
3566 $co{'author_tz'} = $3;
3567 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3568 $co{'author_name'} = $1;
3569 $co{'author_email'} = $2;
3570 } else {
3571 $co{'author_name'} = $co{'author'};
3573 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3574 $co{'committer'} = to_utf8($1);
3575 $co{'committer_epoch'} = $2;
3576 $co{'committer_tz'} = $3;
3577 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3578 $co{'committer_name'} = $1;
3579 $co{'committer_email'} = $2;
3580 } else {
3581 $co{'committer_name'} = $co{'committer'};
3585 if (!defined $co{'tree'}) {
3586 return;
3588 $co{'parents'} = \@parents;
3589 $co{'parent'} = $parents[0];
3591 foreach my $title (@commit_lines) {
3592 $title =~ s/^ //;
3593 if ($title ne "") {
3594 $co{'title'} = chop_str($title, 80, 5);
3595 # remove leading stuff of merges to make the interesting part visible
3596 if (length($title) > 50) {
3597 $title =~ s/^Automatic //;
3598 $title =~ s/^merge (of|with) /Merge ... /i;
3599 if (length($title) > 50) {
3600 $title =~ s/(http|rsync):\/\///;
3602 if (length($title) > 50) {
3603 $title =~ s/(master|www|rsync)\.//;
3605 if (length($title) > 50) {
3606 $title =~ s/kernel.org:?//;
3608 if (length($title) > 50) {
3609 $title =~ s/\/pub\/scm//;
3612 $co{'title_short'} = chop_str($title, 50, 5);
3613 last;
3616 if (! defined $co{'title'} || $co{'title'} eq "") {
3617 $co{'title'} = $co{'title_short'} = '(no commit message)';
3619 # remove added spaces
3620 foreach my $line (@commit_lines) {
3621 $line =~ s/^ //;
3623 $co{'comment'} = \@commit_lines;
3625 my $age = time - $co{'committer_epoch'};
3626 $co{'age'} = $age;
3627 $co{'age_string'} = age_string($age);
3628 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3629 if ($age > 60*60*24*7*2) {
3630 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3631 $co{'age_string_age'} = $co{'age_string'};
3632 } else {
3633 $co{'age_string_date'} = $co{'age_string'};
3634 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3636 return %co;
3639 sub parse_commit {
3640 my ($commit_id) = @_;
3641 my %co;
3643 local $/ = "\0";
3645 open my $fd, "-|", git_cmd(), "rev-list",
3646 "--parents",
3647 "--header",
3648 "--max-count=1",
3649 $commit_id,
3650 "--",
3651 or die_error(500, "Open git-rev-list failed");
3652 %co = parse_commit_text(<$fd>, 1);
3653 close $fd;
3655 return %co;
3658 sub parse_commits {
3659 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3660 my @cos;
3662 $maxcount ||= 1;
3663 $skip ||= 0;
3665 local $/ = "\0";
3667 open my $fd, "-|", git_cmd(), "rev-list",
3668 "--header",
3669 @args,
3670 ("--max-count=" . $maxcount),
3671 ("--skip=" . $skip),
3672 @extra_options,
3673 $commit_id,
3674 "--",
3675 ($filename ? ($filename) : ())
3676 or die_error(500, "Open git-rev-list failed");
3677 while (my $line = <$fd>) {
3678 my %co = parse_commit_text($line);
3679 push @cos, \%co;
3681 close $fd;
3683 return wantarray ? @cos : \@cos;
3686 # parse line of git-diff-tree "raw" output
3687 sub parse_difftree_raw_line {
3688 my $line = shift;
3689 my %res;
3691 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3692 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3693 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3694 $res{'from_mode'} = $1;
3695 $res{'to_mode'} = $2;
3696 $res{'from_id'} = $3;
3697 $res{'to_id'} = $4;
3698 $res{'status'} = $5;
3699 $res{'similarity'} = $6;
3700 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3701 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3702 } else {
3703 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3706 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3707 # combined diff (for merge commit)
3708 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3709 $res{'nparents'} = length($1);
3710 $res{'from_mode'} = [ split(' ', $2) ];
3711 $res{'to_mode'} = pop @{$res{'from_mode'}};
3712 $res{'from_id'} = [ split(' ', $3) ];
3713 $res{'to_id'} = pop @{$res{'from_id'}};
3714 $res{'status'} = [ split('', $4) ];
3715 $res{'to_file'} = unquote($5);
3717 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3718 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3719 $res{'commit'} = $1;
3722 return wantarray ? %res : \%res;
3725 # wrapper: return parsed line of git-diff-tree "raw" output
3726 # (the argument might be raw line, or parsed info)
3727 sub parsed_difftree_line {
3728 my $line_or_ref = shift;
3730 if (ref($line_or_ref) eq "HASH") {
3731 # pre-parsed (or generated by hand)
3732 return $line_or_ref;
3733 } else {
3734 return parse_difftree_raw_line($line_or_ref);
3738 # parse line of git-ls-tree output
3739 sub parse_ls_tree_line {
3740 my $line = shift;
3741 my %opts = @_;
3742 my %res;
3744 if ($opts{'-l'}) {
3745 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3746 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3748 $res{'mode'} = $1;
3749 $res{'type'} = $2;
3750 $res{'hash'} = $3;
3751 $res{'size'} = $4;
3752 if ($opts{'-z'}) {
3753 $res{'name'} = $5;
3754 } else {
3755 $res{'name'} = unquote($5);
3757 } else {
3758 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3759 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3761 $res{'mode'} = $1;
3762 $res{'type'} = $2;
3763 $res{'hash'} = $3;
3764 if ($opts{'-z'}) {
3765 $res{'name'} = $4;
3766 } else {
3767 $res{'name'} = unquote($4);
3771 return wantarray ? %res : \%res;
3774 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3775 sub parse_from_to_diffinfo {
3776 my ($diffinfo, $from, $to, @parents) = @_;
3778 if ($diffinfo->{'nparents'}) {
3779 # combined diff
3780 $from->{'file'} = [];
3781 $from->{'href'} = [];
3782 fill_from_file_info($diffinfo, @parents)
3783 unless exists $diffinfo->{'from_file'};
3784 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3785 $from->{'file'}[$i] =
3786 defined $diffinfo->{'from_file'}[$i] ?
3787 $diffinfo->{'from_file'}[$i] :
3788 $diffinfo->{'to_file'};
3789 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3790 $from->{'href'}[$i] = href(action=>"blob",
3791 hash_base=>$parents[$i],
3792 hash=>$diffinfo->{'from_id'}[$i],
3793 file_name=>$from->{'file'}[$i]);
3794 } else {
3795 $from->{'href'}[$i] = undef;
3798 } else {
3799 # ordinary (not combined) diff
3800 $from->{'file'} = $diffinfo->{'from_file'};
3801 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3802 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3803 hash=>$diffinfo->{'from_id'},
3804 file_name=>$from->{'file'});
3805 } else {
3806 delete $from->{'href'};
3810 $to->{'file'} = $diffinfo->{'to_file'};
3811 if (!is_deleted($diffinfo)) { # file exists in result
3812 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3813 hash=>$diffinfo->{'to_id'},
3814 file_name=>$to->{'file'});
3815 } else {
3816 delete $to->{'href'};
3820 ## ......................................................................
3821 ## parse to array of hashes functions
3823 sub git_get_heads_list {
3824 my ($limit, @classes) = @_;
3825 @classes = get_branch_refs() unless @classes;
3826 my @patterns = map { "refs/$_" } @classes;
3827 my @headslist;
3829 open my $fd, '-|', git_cmd(), 'for-each-ref',
3830 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3831 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3832 @patterns
3833 or return;
3834 while (my $line = <$fd>) {
3835 my %ref_item;
3837 chomp $line;
3838 my ($refinfo, $committerinfo) = split(/\0/, $line);
3839 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3840 my ($committer, $epoch, $tz) =
3841 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3842 $ref_item{'fullname'} = $name;
3843 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3844 $name =~ s!^refs/($strip_refs|remotes)/!!;
3845 $ref_item{'name'} = $name;
3846 # for refs neither in 'heads' nor 'remotes' we want to
3847 # show their ref dir
3848 my $ref_dir = (defined $1) ? $1 : '';
3849 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3850 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3853 $ref_item{'id'} = $hash;
3854 $ref_item{'title'} = $title || '(no commit message)';
3855 $ref_item{'epoch'} = $epoch;
3856 if ($epoch) {
3857 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3858 } else {
3859 $ref_item{'age'} = "unknown";
3862 push @headslist, \%ref_item;
3864 close $fd;
3866 return wantarray ? @headslist : \@headslist;
3869 sub git_get_tags_list {
3870 my $limit = shift;
3871 my @tagslist;
3873 open my $fd, '-|', git_cmd(), 'for-each-ref',
3874 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3875 '--format=%(objectname) %(objecttype) %(refname) '.
3876 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3877 'refs/tags'
3878 or return;
3879 while (my $line = <$fd>) {
3880 my %ref_item;
3882 chomp $line;
3883 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3884 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3885 my ($creator, $epoch, $tz) =
3886 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3887 $ref_item{'fullname'} = $name;
3888 $name =~ s!^refs/tags/!!;
3890 $ref_item{'type'} = $type;
3891 $ref_item{'id'} = $id;
3892 $ref_item{'name'} = $name;
3893 if ($type eq "tag") {
3894 $ref_item{'subject'} = $title;
3895 $ref_item{'reftype'} = $reftype;
3896 $ref_item{'refid'} = $refid;
3897 } else {
3898 $ref_item{'reftype'} = $type;
3899 $ref_item{'refid'} = $id;
3902 if ($type eq "tag" || $type eq "commit") {
3903 $ref_item{'epoch'} = $epoch;
3904 if ($epoch) {
3905 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3906 } else {
3907 $ref_item{'age'} = "unknown";
3911 push @tagslist, \%ref_item;
3913 close $fd;
3915 return wantarray ? @tagslist : \@tagslist;
3918 ## ----------------------------------------------------------------------
3919 ## filesystem-related functions
3921 sub get_file_owner {
3922 my $path = shift;
3924 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3925 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3926 if (!defined $gcos) {
3927 return undef;
3929 my $owner = $gcos;
3930 $owner =~ s/[,;].*$//;
3931 return to_utf8($owner);
3934 # assume that file exists
3935 sub insert_file {
3936 my $filename = shift;
3938 open my $fd, '<', $filename;
3939 print map { to_utf8($_) } <$fd>;
3940 close $fd;
3943 ## ......................................................................
3944 ## mimetype related functions
3946 sub mimetype_guess_file {
3947 my $filename = shift;
3948 my $mimemap = shift;
3949 -r $mimemap or return undef;
3951 my %mimemap;
3952 open(my $mh, '<', $mimemap) or return undef;
3953 while (<$mh>) {
3954 next if m/^#/; # skip comments
3955 my ($mimetype, @exts) = split(/\s+/);
3956 foreach my $ext (@exts) {
3957 $mimemap{$ext} = $mimetype;
3960 close($mh);
3962 $filename =~ /\.([^.]*)$/;
3963 return $mimemap{$1};
3966 sub mimetype_guess {
3967 my $filename = shift;
3968 my $mime;
3969 $filename =~ /\./ or return undef;
3971 if ($mimetypes_file) {
3972 my $file = $mimetypes_file;
3973 if ($file !~ m!^/!) { # if it is relative path
3974 # it is relative to project
3975 $file = "$projectroot/$project/$file";
3977 $mime = mimetype_guess_file($filename, $file);
3979 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3980 return $mime;
3983 sub blob_mimetype {
3984 my $fd = shift;
3985 my $filename = shift;
3987 if ($filename) {
3988 my $mime = mimetype_guess($filename);
3989 $mime and return $mime;
3992 # just in case
3993 return $default_blob_plain_mimetype unless $fd;
3995 if (-T $fd) {
3996 return 'text/plain';
3997 } elsif (! $filename) {
3998 return 'application/octet-stream';
3999 } elsif ($filename =~ m/\.png$/i) {
4000 return 'image/png';
4001 } elsif ($filename =~ m/\.gif$/i) {
4002 return 'image/gif';
4003 } elsif ($filename =~ m/\.jpe?g$/i) {
4004 return 'image/jpeg';
4005 } else {
4006 return 'application/octet-stream';
4010 sub blob_contenttype {
4011 my ($fd, $file_name, $type) = @_;
4013 $type ||= blob_mimetype($fd, $file_name);
4014 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
4015 $type .= "; charset=$default_text_plain_charset";
4018 return $type;
4021 # guess file syntax for syntax highlighting; return undef if no highlighting
4022 # the name of syntax can (in the future) depend on syntax highlighter used
4023 sub guess_file_syntax {
4024 my ($highlight, $file_name) = @_;
4025 return undef unless ($highlight && defined $file_name);
4026 my $basename = basename($file_name, '.in');
4027 return $highlight_basename{$basename}
4028 if exists $highlight_basename{$basename};
4030 $basename =~ /\.([^.]*)$/;
4031 my $ext = $1 or return undef;
4032 return $highlight_ext{$ext}
4033 if exists $highlight_ext{$ext};
4035 return undef;
4038 # run highlighter and return FD of its output,
4039 # or return original FD if no highlighting
4040 sub run_highlighter {
4041 my ($fd, $highlight, $syntax) = @_;
4042 return $fd unless ($highlight);
4044 close $fd;
4045 my $syntax_arg = (defined $syntax) ? "--syntax $syntax" : "--force";
4046 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
4047 $to_utf8_pipe_command.
4048 quote_command($highlight_bin).
4049 " --replace-tabs=8 --fragment $syntax_arg |"
4050 or die_error(500, "Couldn't open file or run syntax highlighter");
4051 return $fd;
4054 ## ======================================================================
4055 ## functions printing HTML: header, footer, error page
4057 sub get_page_title {
4058 my $title = to_utf8($site_name);
4060 unless (defined $project) {
4061 if (defined $project_filter) {
4062 $title .= " - projects in '" . esc_path($project_filter) . "'";
4064 return $title;
4066 $title .= " - " . to_utf8($project);
4068 return $title unless (defined $action);
4069 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
4071 return $title unless (defined $file_name);
4072 $title .= " - " . esc_path($file_name);
4073 if ($action eq "tree" && $file_name !~ m|/$|) {
4074 $title .= "/";
4077 return $title;
4080 sub get_content_type_html {
4081 # require explicit support from the UA if we are to send the page as
4082 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4083 # we have to do this because MSIE sometimes globs '*/*', pretending to
4084 # support xhtml+xml but choking when it gets what it asked for.
4085 if (defined $cgi->http('HTTP_ACCEPT') &&
4086 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4087 $cgi->Accept('application/xhtml+xml') != 0) {
4088 return 'application/xhtml+xml';
4089 } else {
4090 return 'text/html';
4094 sub print_feed_meta {
4095 if (defined $project) {
4096 my %href_params = get_feed_info();
4097 if (!exists $href_params{'-title'}) {
4098 $href_params{'-title'} = 'log';
4101 foreach my $format (qw(RSS Atom)) {
4102 my $type = lc($format);
4103 my %link_attr = (
4104 '-rel' => 'alternate',
4105 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4106 '-type' => "application/$type+xml"
4109 $href_params{'extra_options'} = undef;
4110 $href_params{'action'} = $type;
4111 $link_attr{'-href'} = href(%href_params);
4112 print "<link ".
4113 "rel=\"$link_attr{'-rel'}\" ".
4114 "title=\"$link_attr{'-title'}\" ".
4115 "href=\"$link_attr{'-href'}\" ".
4116 "type=\"$link_attr{'-type'}\" ".
4117 "/>\n";
4119 $href_params{'extra_options'} = '--no-merges';
4120 $link_attr{'-href'} = href(%href_params);
4121 $link_attr{'-title'} .= ' (no merges)';
4122 print "<link ".
4123 "rel=\"$link_attr{'-rel'}\" ".
4124 "title=\"$link_attr{'-title'}\" ".
4125 "href=\"$link_attr{'-href'}\" ".
4126 "type=\"$link_attr{'-type'}\" ".
4127 "/>\n";
4130 } else {
4131 printf('<link rel="alternate" title="%s projects list" '.
4132 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4133 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4134 printf('<link rel="alternate" title="%s projects feeds" '.
4135 'href="%s" type="text/x-opml" />'."\n",
4136 esc_attr($site_name), href(project=>undef, action=>"opml"));
4140 sub print_header_links {
4141 my $status = shift;
4143 # print out each stylesheet that exist, providing backwards capability
4144 # for those people who defined $stylesheet in a config file
4145 if (defined $stylesheet) {
4146 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4147 } else {
4148 foreach my $stylesheet (@stylesheets) {
4149 next unless $stylesheet;
4150 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4153 print_feed_meta()
4154 if ($status eq '200 OK');
4155 if (defined $favicon) {
4156 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4160 sub print_nav_breadcrumbs_path {
4161 my $dirprefix = undef;
4162 while (my $part = shift) {
4163 $dirprefix .= "/" if defined $dirprefix;
4164 $dirprefix .= $part;
4165 print $cgi->a({-href => href(project => undef,
4166 project_filter => $dirprefix,
4167 action => "project_list")},
4168 esc_html($part)) . " / ";
4172 sub print_nav_breadcrumbs {
4173 my %opts = @_;
4175 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4176 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4178 if (defined $project) {
4179 my @dirname = split '/', $project;
4180 my $projectbasename = pop @dirname;
4181 print_nav_breadcrumbs_path(@dirname);
4182 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4183 if (defined $action) {
4184 my $action_print = $action ;
4185 if (defined $opts{-action_extra}) {
4186 $action_print = $cgi->a({-href => href(action=>$action)},
4187 $action);
4189 print " / $action_print";
4191 if (defined $opts{-action_extra}) {
4192 print " / $opts{-action_extra}";
4194 print "\n";
4195 } elsif (defined $project_filter) {
4196 print_nav_breadcrumbs_path(split '/', $project_filter);
4200 sub print_search_form {
4201 if (!defined $searchtext) {
4202 $searchtext = "";
4204 my $search_hash;
4205 if (defined $hash_base) {
4206 $search_hash = $hash_base;
4207 } elsif (defined $hash) {
4208 $search_hash = $hash;
4209 } else {
4210 $search_hash = "HEAD";
4212 my $action = $my_uri;
4213 my $use_pathinfo = gitweb_check_feature('pathinfo');
4214 if ($use_pathinfo) {
4215 $action .= "/".esc_url($project);
4217 print $cgi->start_form(-method => "get", -action => $action) .
4218 "<div class=\"search\">\n" .
4219 (!$use_pathinfo &&
4220 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4221 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4222 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4223 $cgi->popup_menu(-name => 'st', -default => 'commit',
4224 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4225 " " . $cgi->a({-href => href(action=>"search_help"),
4226 -title => "search help" }, "?") . " search:\n",
4227 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4228 "<span title=\"Extended regular expression\">" .
4229 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4230 -checked => $search_use_regexp) .
4231 "</span>" .
4232 "</div>" .
4233 $cgi->end_form() . "\n";
4236 sub git_header_html {
4237 my $status = shift || "200 OK";
4238 my $expires = shift;
4239 my %opts = @_;
4241 my $title = get_page_title();
4242 my $content_type = get_content_type_html();
4243 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4244 -status=> $status, -expires => $expires)
4245 unless ($opts{'-no_http_header'});
4246 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4247 print <<EOF;
4248 <?xml version="1.0" encoding="utf-8"?>
4249 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4250 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4251 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4252 <!-- git core binaries version $git_version -->
4253 <head>
4254 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4255 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4256 <meta name="robots" content="index, nofollow"/>
4257 <title>$title</title>
4259 # the stylesheet, favicon etc urls won't work correctly with path_info
4260 # unless we set the appropriate base URL
4261 if ($ENV{'PATH_INFO'}) {
4262 print "<base href=\"".esc_url($base_url)."\" />\n";
4264 print_header_links($status);
4266 if (defined $site_html_head_string) {
4267 print to_utf8($site_html_head_string);
4270 print "</head>\n" .
4271 "<body>\n";
4273 if (defined $site_header && -f $site_header) {
4274 insert_file($site_header);
4277 print "<div class=\"page_header\">\n";
4278 if (defined $logo) {
4279 print $cgi->a({-href => esc_url($logo_url),
4280 -title => $logo_label},
4281 $cgi->img({-src => esc_url($logo),
4282 -width => 72, -height => 27,
4283 -alt => "git",
4284 -class => "logo"}));
4286 print_nav_breadcrumbs(%opts);
4287 print "</div>\n";
4289 my $have_search = gitweb_check_feature('search');
4290 if (defined $project && $have_search) {
4291 print_search_form();
4295 sub git_footer_html {
4296 my $feed_class = 'rss_logo';
4298 print "<div class=\"page_footer\">\n";
4299 if (defined $project) {
4300 my $descr = git_get_project_description($project);
4301 if (defined $descr) {
4302 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4305 my %href_params = get_feed_info();
4306 if (!%href_params) {
4307 $feed_class .= ' generic';
4309 $href_params{'-title'} ||= 'log';
4311 foreach my $format (qw(RSS Atom)) {
4312 $href_params{'action'} = lc($format);
4313 print $cgi->a({-href => href(%href_params),
4314 -title => "$href_params{'-title'} $format feed",
4315 -class => $feed_class}, $format)."\n";
4318 } else {
4319 print $cgi->a({-href => href(project=>undef, action=>"opml",
4320 project_filter => $project_filter),
4321 -class => $feed_class}, "OPML") . " ";
4322 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4323 project_filter => $project_filter),
4324 -class => $feed_class}, "TXT") . "\n";
4326 print "</div>\n"; # class="page_footer"
4328 if (defined $t0 && gitweb_check_feature('timed')) {
4329 print "<div id=\"generating_info\">\n";
4330 print 'This page took '.
4331 '<span id="generating_time" class="time_span">'.
4332 tv_interval($t0, [ gettimeofday() ]).
4333 ' seconds </span>'.
4334 ' and '.
4335 '<span id="generating_cmd">'.
4336 $number_of_git_cmds.
4337 '</span> git commands '.
4338 " to generate.\n";
4339 print "</div>\n"; # class="page_footer"
4342 if (defined $site_footer && -f $site_footer) {
4343 insert_file($site_footer);
4346 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4347 if (defined $action &&
4348 $action eq 'blame_incremental') {
4349 print qq!<script type="text/javascript">\n!.
4350 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4351 qq! "!. href() .qq!");\n!.
4352 qq!</script>\n!;
4353 } else {
4354 my ($jstimezone, $tz_cookie, $datetime_class) =
4355 gitweb_get_feature('javascript-timezone');
4357 print qq!<script type="text/javascript">\n!.
4358 qq!window.onload = function () {\n!;
4359 if (gitweb_check_feature('javascript-actions')) {
4360 print qq! fixLinks();\n!;
4362 if ($jstimezone && $tz_cookie && $datetime_class) {
4363 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4364 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4366 print qq!};\n!.
4367 qq!</script>\n!;
4370 print "</body>\n" .
4371 "</html>";
4374 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4375 # Example: die_error(404, 'Hash not found')
4376 # By convention, use the following status codes (as defined in RFC 2616):
4377 # 400: Invalid or missing CGI parameters, or
4378 # requested object exists but has wrong type.
4379 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4380 # this server or project.
4381 # 404: Requested object/revision/project doesn't exist.
4382 # 500: The server isn't configured properly, or
4383 # an internal error occurred (e.g. failed assertions caused by bugs), or
4384 # an unknown error occurred (e.g. the git binary died unexpectedly).
4385 # 503: The server is currently unavailable (because it is overloaded,
4386 # or down for maintenance). Generally, this is a temporary state.
4387 sub die_error {
4388 my $status = shift || 500;
4389 my $error = esc_html(shift) || "Internal Server Error";
4390 my $extra = shift;
4391 my %opts = @_;
4393 my %http_responses = (
4394 400 => '400 Bad Request',
4395 403 => '403 Forbidden',
4396 404 => '404 Not Found',
4397 500 => '500 Internal Server Error',
4398 503 => '503 Service Unavailable',
4400 git_header_html($http_responses{$status}, undef, %opts);
4401 print <<EOF;
4402 <div class="page_body">
4403 <br /><br />
4404 $status - $error
4405 <br />
4407 if (defined $extra) {
4408 print "<hr />\n" .
4409 "$extra\n";
4411 print "</div>\n";
4413 git_footer_html();
4414 goto DONE_GITWEB
4415 unless ($opts{'-error_handler'});
4418 ## ----------------------------------------------------------------------
4419 ## functions printing or outputting HTML: navigation
4421 sub git_print_page_nav {
4422 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4423 $extra = '' if !defined $extra; # pager or formats
4425 my @navs = qw(summary shortlog log commit commitdiff tree);
4426 if ($suppress) {
4427 @navs = grep { $_ ne $suppress } @navs;
4430 my %arg = map { $_ => {action=>$_} } @navs;
4431 if (defined $head) {
4432 for (qw(commit commitdiff)) {
4433 $arg{$_}{'hash'} = $head;
4435 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4436 for (qw(shortlog log)) {
4437 $arg{$_}{'hash'} = $head;
4442 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4443 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4445 my @actions = gitweb_get_feature('actions');
4446 my %repl = (
4447 '%' => '%',
4448 'n' => $project, # project name
4449 'f' => $git_dir, # project path within filesystem
4450 'h' => $treehead || '', # current hash ('h' parameter)
4451 'b' => $treebase || '', # hash base ('hb' parameter)
4453 while (@actions) {
4454 my ($label, $link, $pos) = splice(@actions,0,3);
4455 # insert
4456 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4457 # munch munch
4458 $link =~ s/%([%nfhb])/$repl{$1}/g;
4459 $arg{$label}{'_href'} = $link;
4462 print "<div class=\"page_nav\">\n" .
4463 (join " | ",
4464 map { $_ eq $current ?
4465 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4466 } @navs);
4467 print "<br/>\n$extra<br/>\n" .
4468 "</div>\n";
4471 # returns a submenu for the nagivation of the refs views (tags, heads,
4472 # remotes) with the current view disabled and the remotes view only
4473 # available if the feature is enabled
4474 sub format_ref_views {
4475 my ($current) = @_;
4476 my @ref_views = qw{tags heads};
4477 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4478 return join " | ", map {
4479 $_ eq $current ? $_ :
4480 $cgi->a({-href => href(action=>$_)}, $_)
4481 } @ref_views
4484 sub format_paging_nav {
4485 my ($action, $page, $has_next_link) = @_;
4486 my $paging_nav;
4489 if ($page > 0) {
4490 $paging_nav .=
4491 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4492 " &sdot; " .
4493 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4494 -accesskey => "p", -title => "Alt-p"}, "prev");
4495 } else {
4496 $paging_nav .= "first &sdot; prev";
4499 if ($has_next_link) {
4500 $paging_nav .= " &sdot; " .
4501 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4502 -accesskey => "n", -title => "Alt-n"}, "next");
4503 } else {
4504 $paging_nav .= " &sdot; next";
4507 return $paging_nav;
4510 ## ......................................................................
4511 ## functions printing or outputting HTML: div
4513 sub git_print_header_div {
4514 my ($action, $title, $hash, $hash_base) = @_;
4515 my %args = ();
4517 $args{'action'} = $action;
4518 $args{'hash'} = $hash if $hash;
4519 $args{'hash_base'} = $hash_base if $hash_base;
4521 print "<div class=\"header\">\n" .
4522 $cgi->a({-href => href(%args), -class => "title"},
4523 $title ? $title : $action) .
4524 "\n</div>\n";
4527 sub format_repo_url {
4528 my ($name, $url) = @_;
4529 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4532 # Group output by placing it in a DIV element and adding a header.
4533 # Options for start_div() can be provided by passing a hash reference as the
4534 # first parameter to the function.
4535 # Options to git_print_header_div() can be provided by passing an array
4536 # reference. This must follow the options to start_div if they are present.
4537 # The content can be a scalar, which is output as-is, a scalar reference, which
4538 # is output after html escaping, an IO handle passed either as *handle or
4539 # *handle{IO}, or a function reference. In the latter case all following
4540 # parameters will be taken as argument to the content function call.
4541 sub git_print_section {
4542 my ($div_args, $header_args, $content);
4543 my $arg = shift;
4544 if (ref($arg) eq 'HASH') {
4545 $div_args = $arg;
4546 $arg = shift;
4548 if (ref($arg) eq 'ARRAY') {
4549 $header_args = $arg;
4550 $arg = shift;
4552 $content = $arg;
4554 print $cgi->start_div($div_args);
4555 git_print_header_div(@$header_args);
4557 if (ref($content) eq 'CODE') {
4558 $content->(@_);
4559 } elsif (ref($content) eq 'SCALAR') {
4560 print esc_html($$content);
4561 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4562 print <$content>;
4563 } elsif (!ref($content) && defined($content)) {
4564 print $content;
4567 print $cgi->end_div;
4570 sub format_timestamp_html {
4571 my $date = shift;
4572 my $strtime = $date->{'rfc2822'};
4574 my (undef, undef, $datetime_class) =
4575 gitweb_get_feature('javascript-timezone');
4576 if ($datetime_class) {
4577 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4580 my $localtime_format = '(%02d:%02d %s)';
4581 if ($date->{'hour_local'} < 6) {
4582 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4584 $strtime .= ' ' .
4585 sprintf($localtime_format,
4586 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4588 return $strtime;
4591 # Outputs the author name and date in long form
4592 sub git_print_authorship {
4593 my $co = shift;
4594 my %opts = @_;
4595 my $tag = $opts{-tag} || 'div';
4596 my $author = $co->{'author_name'};
4598 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4599 print "<$tag class=\"author_date\">" .
4600 format_search_author($author, "author", esc_html($author)) .
4601 " [".format_timestamp_html(\%ad)."]".
4602 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4603 "</$tag>\n";
4606 # Outputs table rows containing the full author or committer information,
4607 # in the format expected for 'commit' view (& similar).
4608 # Parameters are a commit hash reference, followed by the list of people
4609 # to output information for. If the list is empty it defaults to both
4610 # author and committer.
4611 sub git_print_authorship_rows {
4612 my $co = shift;
4613 # too bad we can't use @people = @_ || ('author', 'committer')
4614 my @people = @_;
4615 @people = ('author', 'committer') unless @people;
4616 foreach my $who (@people) {
4617 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4618 print "<tr><td>$who</td><td>" .
4619 format_search_author($co->{"${who}_name"}, $who,
4620 esc_html($co->{"${who}_name"})) . " " .
4621 format_search_author($co->{"${who}_email"}, $who,
4622 esc_html("<" . $co->{"${who}_email"} . ">")) .
4623 "</td><td rowspan=\"2\">" .
4624 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4625 "</td></tr>\n" .
4626 "<tr>" .
4627 "<td></td><td>" .
4628 format_timestamp_html(\%wd) .
4629 "</td>" .
4630 "</tr>\n";
4634 sub git_print_page_path {
4635 my $name = shift;
4636 my $type = shift;
4637 my $hb = shift;
4640 print "<div class=\"page_path\">";
4641 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4642 -title => 'tree root'}, to_utf8("[$project]"));
4643 print " / ";
4644 if (defined $name) {
4645 my @dirname = split '/', $name;
4646 my $basename = pop @dirname;
4647 my $fullname = '';
4649 foreach my $dir (@dirname) {
4650 $fullname .= ($fullname ? '/' : '') . $dir;
4651 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4652 hash_base=>$hb),
4653 -title => $fullname}, esc_path($dir));
4654 print " / ";
4656 if (defined $type && $type eq 'blob') {
4657 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4658 hash_base=>$hb),
4659 -title => $name}, esc_path($basename));
4660 } elsif (defined $type && $type eq 'tree') {
4661 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4662 hash_base=>$hb),
4663 -title => $name}, esc_path($basename));
4664 print " / ";
4665 } else {
4666 print esc_path($basename);
4669 print "<br/></div>\n";
4672 sub git_print_log {
4673 my $log = shift;
4674 my %opts = @_;
4676 if ($opts{'-remove_title'}) {
4677 # remove title, i.e. first line of log
4678 shift @$log;
4680 # remove leading empty lines
4681 while (defined $log->[0] && $log->[0] eq "") {
4682 shift @$log;
4685 # print log
4686 my $skip_blank_line = 0;
4687 foreach my $line (@$log) {
4688 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4689 if (! $opts{'-remove_signoff'}) {
4690 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4691 $skip_blank_line = 1;
4693 next;
4696 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4697 if (! $opts{'-remove_signoff'}) {
4698 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4699 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4700 "</span><br/>\n";
4701 $skip_blank_line = 1;
4703 next;
4706 # print only one empty line
4707 # do not print empty line after signoff
4708 if ($line eq "") {
4709 next if ($skip_blank_line);
4710 $skip_blank_line = 1;
4711 } else {
4712 $skip_blank_line = 0;
4715 print format_log_line_html($line) . "<br/>\n";
4718 if ($opts{'-final_empty_line'}) {
4719 # end with single empty line
4720 print "<br/>\n" unless $skip_blank_line;
4724 # return link target (what link points to)
4725 sub git_get_link_target {
4726 my $hash = shift;
4727 my $link_target;
4729 # read link
4730 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4731 or return;
4733 local $/ = undef;
4734 $link_target = <$fd>;
4736 close $fd
4737 or return;
4739 return $link_target;
4742 # given link target, and the directory (basedir) the link is in,
4743 # return target of link relative to top directory (top tree);
4744 # return undef if it is not possible (including absolute links).
4745 sub normalize_link_target {
4746 my ($link_target, $basedir) = @_;
4748 # absolute symlinks (beginning with '/') cannot be normalized
4749 return if (substr($link_target, 0, 1) eq '/');
4751 # normalize link target to path from top (root) tree (dir)
4752 my $path;
4753 if ($basedir) {
4754 $path = $basedir . '/' . $link_target;
4755 } else {
4756 # we are in top (root) tree (dir)
4757 $path = $link_target;
4760 # remove //, /./, and /../
4761 my @path_parts;
4762 foreach my $part (split('/', $path)) {
4763 # discard '.' and ''
4764 next if (!$part || $part eq '.');
4765 # handle '..'
4766 if ($part eq '..') {
4767 if (@path_parts) {
4768 pop @path_parts;
4769 } else {
4770 # link leads outside repository (outside top dir)
4771 return;
4773 } else {
4774 push @path_parts, $part;
4777 $path = join('/', @path_parts);
4779 return $path;
4782 # print tree entry (row of git_tree), but without encompassing <tr> element
4783 sub git_print_tree_entry {
4784 my ($t, $basedir, $hash_base, $have_blame) = @_;
4786 my %base_key = ();
4787 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4789 # The format of a table row is: mode list link. Where mode is
4790 # the mode of the entry, list is the name of the entry, an href,
4791 # and link is the action links of the entry.
4793 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4794 if (exists $t->{'size'}) {
4795 print "<td class=\"size\">$t->{'size'}</td>\n";
4797 if ($t->{'type'} eq "blob") {
4798 print "<td class=\"list\">" .
4799 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4800 file_name=>"$basedir$t->{'name'}", %base_key),
4801 -class => "list"}, esc_path($t->{'name'}));
4802 if (S_ISLNK(oct $t->{'mode'})) {
4803 my $link_target = git_get_link_target($t->{'hash'});
4804 if ($link_target) {
4805 my $norm_target = normalize_link_target($link_target, $basedir);
4806 if (defined $norm_target) {
4807 print " -> " .
4808 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4809 file_name=>$norm_target),
4810 -title => $norm_target}, esc_path($link_target));
4811 } else {
4812 print " -> " . esc_path($link_target);
4816 print "</td>\n";
4817 print "<td class=\"link\">";
4818 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4819 file_name=>"$basedir$t->{'name'}", %base_key)},
4820 "blob");
4821 if ($have_blame) {
4822 print " | " .
4823 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4824 file_name=>"$basedir$t->{'name'}", %base_key)},
4825 "blame");
4827 if (defined $hash_base) {
4828 print " | " .
4829 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4830 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4831 "history");
4833 print " | " .
4834 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4835 file_name=>"$basedir$t->{'name'}")},
4836 "raw");
4837 print "</td>\n";
4839 } elsif ($t->{'type'} eq "tree") {
4840 print "<td class=\"list\">";
4841 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4842 file_name=>"$basedir$t->{'name'}",
4843 %base_key)},
4844 esc_path($t->{'name'}));
4845 print "</td>\n";
4846 print "<td class=\"link\">";
4847 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4848 file_name=>"$basedir$t->{'name'}",
4849 %base_key)},
4850 "tree");
4851 if (defined $hash_base) {
4852 print " | " .
4853 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4854 file_name=>"$basedir$t->{'name'}")},
4855 "history");
4857 print "</td>\n";
4858 } else {
4859 # unknown object: we can only present history for it
4860 # (this includes 'commit' object, i.e. submodule support)
4861 print "<td class=\"list\">" .
4862 esc_path($t->{'name'}) .
4863 "</td>\n";
4864 print "<td class=\"link\">";
4865 if (defined $hash_base) {
4866 print $cgi->a({-href => href(action=>"history",
4867 hash_base=>$hash_base,
4868 file_name=>"$basedir$t->{'name'}")},
4869 "history");
4871 print "</td>\n";
4875 ## ......................................................................
4876 ## functions printing large fragments of HTML
4878 # get pre-image filenames for merge (combined) diff
4879 sub fill_from_file_info {
4880 my ($diff, @parents) = @_;
4882 $diff->{'from_file'} = [ ];
4883 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4884 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4885 if ($diff->{'status'}[$i] eq 'R' ||
4886 $diff->{'status'}[$i] eq 'C') {
4887 $diff->{'from_file'}[$i] =
4888 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4892 return $diff;
4895 # is current raw difftree line of file deletion
4896 sub is_deleted {
4897 my $diffinfo = shift;
4899 return $diffinfo->{'to_id'} eq ('0' x 40);
4902 # does patch correspond to [previous] difftree raw line
4903 # $diffinfo - hashref of parsed raw diff format
4904 # $patchinfo - hashref of parsed patch diff format
4905 # (the same keys as in $diffinfo)
4906 sub is_patch_split {
4907 my ($diffinfo, $patchinfo) = @_;
4909 return defined $diffinfo && defined $patchinfo
4910 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4914 sub git_difftree_body {
4915 my ($difftree, $hash, @parents) = @_;
4916 my ($parent) = $parents[0];
4917 my $have_blame = gitweb_check_feature('blame');
4918 print "<div class=\"list_head\">\n";
4919 if ($#{$difftree} > 10) {
4920 print(($#{$difftree} + 1) . " files changed:\n");
4922 print "</div>\n";
4924 print "<table class=\"" .
4925 (@parents > 1 ? "combined " : "") .
4926 "diff_tree\">\n";
4928 # header only for combined diff in 'commitdiff' view
4929 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4930 if ($has_header) {
4931 # table header
4932 print "<thead><tr>\n" .
4933 "<th></th><th></th>\n"; # filename, patchN link
4934 for (my $i = 0; $i < @parents; $i++) {
4935 my $par = $parents[$i];
4936 print "<th>" .
4937 $cgi->a({-href => href(action=>"commitdiff",
4938 hash=>$hash, hash_parent=>$par),
4939 -title => 'commitdiff to parent number ' .
4940 ($i+1) . ': ' . substr($par,0,7)},
4941 $i+1) .
4942 "&nbsp;</th>\n";
4944 print "</tr></thead>\n<tbody>\n";
4947 my $alternate = 1;
4948 my $patchno = 0;
4949 foreach my $line (@{$difftree}) {
4950 my $diff = parsed_difftree_line($line);
4952 if ($alternate) {
4953 print "<tr class=\"dark\">\n";
4954 } else {
4955 print "<tr class=\"light\">\n";
4957 $alternate ^= 1;
4959 if (exists $diff->{'nparents'}) { # combined diff
4961 fill_from_file_info($diff, @parents)
4962 unless exists $diff->{'from_file'};
4964 if (!is_deleted($diff)) {
4965 # file exists in the result (child) commit
4966 print "<td>" .
4967 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4968 file_name=>$diff->{'to_file'},
4969 hash_base=>$hash),
4970 -class => "list"}, esc_path($diff->{'to_file'})) .
4971 "</td>\n";
4972 } else {
4973 print "<td>" .
4974 esc_path($diff->{'to_file'}) .
4975 "</td>\n";
4978 if ($action eq 'commitdiff') {
4979 # link to patch
4980 $patchno++;
4981 print "<td class=\"link\">" .
4982 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4983 "patch") .
4984 " | " .
4985 "</td>\n";
4988 my $has_history = 0;
4989 my $not_deleted = 0;
4990 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4991 my $hash_parent = $parents[$i];
4992 my $from_hash = $diff->{'from_id'}[$i];
4993 my $from_path = $diff->{'from_file'}[$i];
4994 my $status = $diff->{'status'}[$i];
4996 $has_history ||= ($status ne 'A');
4997 $not_deleted ||= ($status ne 'D');
4999 if ($status eq 'A') {
5000 print "<td class=\"link\" align=\"right\"> | </td>\n";
5001 } elsif ($status eq 'D') {
5002 print "<td class=\"link\">" .
5003 $cgi->a({-href => href(action=>"blob",
5004 hash_base=>$hash,
5005 hash=>$from_hash,
5006 file_name=>$from_path)},
5007 "blob" . ($i+1)) .
5008 " | </td>\n";
5009 } else {
5010 if ($diff->{'to_id'} eq $from_hash) {
5011 print "<td class=\"link nochange\">";
5012 } else {
5013 print "<td class=\"link\">";
5015 print $cgi->a({-href => href(action=>"blobdiff",
5016 hash=>$diff->{'to_id'},
5017 hash_parent=>$from_hash,
5018 hash_base=>$hash,
5019 hash_parent_base=>$hash_parent,
5020 file_name=>$diff->{'to_file'},
5021 file_parent=>$from_path)},
5022 "diff" . ($i+1)) .
5023 " | </td>\n";
5027 print "<td class=\"link\">";
5028 if ($not_deleted) {
5029 print $cgi->a({-href => href(action=>"blob",
5030 hash=>$diff->{'to_id'},
5031 file_name=>$diff->{'to_file'},
5032 hash_base=>$hash)},
5033 "blob");
5034 print " | " if ($has_history);
5036 if ($has_history) {
5037 print $cgi->a({-href => href(action=>"history",
5038 file_name=>$diff->{'to_file'},
5039 hash_base=>$hash)},
5040 "history");
5042 print "</td>\n";
5044 print "</tr>\n";
5045 next; # instead of 'else' clause, to avoid extra indent
5047 # else ordinary diff
5049 my ($to_mode_oct, $to_mode_str, $to_file_type);
5050 my ($from_mode_oct, $from_mode_str, $from_file_type);
5051 if ($diff->{'to_mode'} ne ('0' x 6)) {
5052 $to_mode_oct = oct $diff->{'to_mode'};
5053 if (S_ISREG($to_mode_oct)) { # only for regular file
5054 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
5056 $to_file_type = file_type($diff->{'to_mode'});
5058 if ($diff->{'from_mode'} ne ('0' x 6)) {
5059 $from_mode_oct = oct $diff->{'from_mode'};
5060 if (S_ISREG($from_mode_oct)) { # only for regular file
5061 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5063 $from_file_type = file_type($diff->{'from_mode'});
5066 if ($diff->{'status'} eq "A") { # created
5067 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5068 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5069 $mode_chng .= "]</span>";
5070 print "<td>";
5071 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5072 hash_base=>$hash, file_name=>$diff->{'file'}),
5073 -class => "list"}, esc_path($diff->{'file'}));
5074 print "</td>\n";
5075 print "<td>$mode_chng</td>\n";
5076 print "<td class=\"link\">";
5077 if ($action eq 'commitdiff') {
5078 # link to patch
5079 $patchno++;
5080 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5081 "patch") .
5082 " | ";
5084 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5085 hash_base=>$hash, file_name=>$diff->{'file'})},
5086 "blob");
5087 print "</td>\n";
5089 } elsif ($diff->{'status'} eq "D") { # deleted
5090 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5091 print "<td>";
5092 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5093 hash_base=>$parent, file_name=>$diff->{'file'}),
5094 -class => "list"}, esc_path($diff->{'file'}));
5095 print "</td>\n";
5096 print "<td>$mode_chng</td>\n";
5097 print "<td class=\"link\">";
5098 if ($action eq 'commitdiff') {
5099 # link to patch
5100 $patchno++;
5101 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5102 "patch") .
5103 " | ";
5105 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5106 hash_base=>$parent, file_name=>$diff->{'file'})},
5107 "blob") . " | ";
5108 if ($have_blame) {
5109 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5110 file_name=>$diff->{'file'})},
5111 "blame") . " | ";
5113 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5114 file_name=>$diff->{'file'})},
5115 "history");
5116 print "</td>\n";
5118 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5119 my $mode_chnge = "";
5120 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5121 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5122 if ($from_file_type ne $to_file_type) {
5123 $mode_chnge .= " from $from_file_type to $to_file_type";
5125 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5126 if ($from_mode_str && $to_mode_str) {
5127 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5128 } elsif ($to_mode_str) {
5129 $mode_chnge .= " mode: $to_mode_str";
5132 $mode_chnge .= "]</span>\n";
5134 print "<td>";
5135 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5136 hash_base=>$hash, file_name=>$diff->{'file'}),
5137 -class => "list"}, esc_path($diff->{'file'}));
5138 print "</td>\n";
5139 print "<td>$mode_chnge</td>\n";
5140 print "<td class=\"link\">";
5141 if ($action eq 'commitdiff') {
5142 # link to patch
5143 $patchno++;
5144 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5145 "patch") .
5146 " | ";
5147 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5148 # "commit" view and modified file (not onlu mode changed)
5149 print $cgi->a({-href => href(action=>"blobdiff",
5150 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5151 hash_base=>$hash, hash_parent_base=>$parent,
5152 file_name=>$diff->{'file'})},
5153 "diff") .
5154 " | ";
5156 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5157 hash_base=>$hash, file_name=>$diff->{'file'})},
5158 "blob") . " | ";
5159 if ($have_blame) {
5160 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5161 file_name=>$diff->{'file'})},
5162 "blame") . " | ";
5164 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5165 file_name=>$diff->{'file'})},
5166 "history");
5167 print "</td>\n";
5169 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5170 my %status_name = ('R' => 'moved', 'C' => 'copied');
5171 my $nstatus = $status_name{$diff->{'status'}};
5172 my $mode_chng = "";
5173 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5174 # mode also for directories, so we cannot use $to_mode_str
5175 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5177 print "<td>" .
5178 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5179 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5180 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5181 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5182 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5183 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5184 -class => "list"}, esc_path($diff->{'from_file'})) .
5185 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5186 "<td class=\"link\">";
5187 if ($action eq 'commitdiff') {
5188 # link to patch
5189 $patchno++;
5190 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5191 "patch") .
5192 " | ";
5193 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5194 # "commit" view and modified file (not only pure rename or copy)
5195 print $cgi->a({-href => href(action=>"blobdiff",
5196 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5197 hash_base=>$hash, hash_parent_base=>$parent,
5198 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5199 "diff") .
5200 " | ";
5202 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5203 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5204 "blob") . " | ";
5205 if ($have_blame) {
5206 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5207 file_name=>$diff->{'to_file'})},
5208 "blame") . " | ";
5210 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5211 file_name=>$diff->{'to_file'})},
5212 "history");
5213 print "</td>\n";
5215 } # we should not encounter Unmerged (U) or Unknown (X) status
5216 print "</tr>\n";
5218 print "</tbody>" if $has_header;
5219 print "</table>\n";
5222 # Print context lines and then rem/add lines in a side-by-side manner.
5223 sub print_sidebyside_diff_lines {
5224 my ($ctx, $rem, $add) = @_;
5226 # print context block before add/rem block
5227 if (@$ctx) {
5228 print join '',
5229 '<div class="chunk_block ctx">',
5230 '<div class="old">',
5231 @$ctx,
5232 '</div>',
5233 '<div class="new">',
5234 @$ctx,
5235 '</div>',
5236 '</div>';
5239 if (!@$add) {
5240 # pure removal
5241 print join '',
5242 '<div class="chunk_block rem">',
5243 '<div class="old">',
5244 @$rem,
5245 '</div>',
5246 '</div>';
5247 } elsif (!@$rem) {
5248 # pure addition
5249 print join '',
5250 '<div class="chunk_block add">',
5251 '<div class="new">',
5252 @$add,
5253 '</div>',
5254 '</div>';
5255 } else {
5256 print join '',
5257 '<div class="chunk_block chg">',
5258 '<div class="old">',
5259 @$rem,
5260 '</div>',
5261 '<div class="new">',
5262 @$add,
5263 '</div>',
5264 '</div>';
5268 # Print context lines and then rem/add lines in inline manner.
5269 sub print_inline_diff_lines {
5270 my ($ctx, $rem, $add) = @_;
5272 print @$ctx, @$rem, @$add;
5275 # Format removed and added line, mark changed part and HTML-format them.
5276 # Implementation is based on contrib/diff-highlight
5277 sub format_rem_add_lines_pair {
5278 my ($rem, $add, $num_parents) = @_;
5280 # We need to untabify lines before split()'ing them;
5281 # otherwise offsets would be invalid.
5282 chomp $rem;
5283 chomp $add;
5284 $rem = untabify($rem);
5285 $add = untabify($add);
5287 my @rem = split(//, $rem);
5288 my @add = split(//, $add);
5289 my ($esc_rem, $esc_add);
5290 # Ignore leading +/- characters for each parent.
5291 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5292 my ($prefix_has_nonspace, $suffix_has_nonspace);
5294 my $shorter = (@rem < @add) ? @rem : @add;
5295 while ($prefix_len < $shorter) {
5296 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5298 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5299 $prefix_len++;
5302 while ($prefix_len + $suffix_len < $shorter) {
5303 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5305 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5306 $suffix_len++;
5309 # Mark lines that are different from each other, but have some common
5310 # part that isn't whitespace. If lines are completely different, don't
5311 # mark them because that would make output unreadable, especially if
5312 # diff consists of multiple lines.
5313 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5314 $esc_rem = esc_html_hl_regions($rem, 'marked',
5315 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5316 $esc_add = esc_html_hl_regions($add, 'marked',
5317 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5318 } else {
5319 $esc_rem = esc_html($rem, -nbsp=>1);
5320 $esc_add = esc_html($add, -nbsp=>1);
5323 return format_diff_line(\$esc_rem, 'rem'),
5324 format_diff_line(\$esc_add, 'add');
5327 # HTML-format diff context, removed and added lines.
5328 sub format_ctx_rem_add_lines {
5329 my ($ctx, $rem, $add, $num_parents) = @_;
5330 my (@new_ctx, @new_rem, @new_add);
5331 my $can_highlight = 0;
5332 my $is_combined = ($num_parents > 1);
5334 # Highlight if every removed line has a corresponding added line.
5335 if (@$add > 0 && @$add == @$rem) {
5336 $can_highlight = 1;
5338 # Highlight lines in combined diff only if the chunk contains
5339 # diff between the same version, e.g.
5341 # - a
5342 # - b
5343 # + c
5344 # + d
5346 # Otherwise the highlightling would be confusing.
5347 if ($is_combined) {
5348 for (my $i = 0; $i < @$add; $i++) {
5349 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5350 my $prefix_add = substr($add->[$i], 0, $num_parents);
5352 $prefix_rem =~ s/-/+/g;
5354 if ($prefix_rem ne $prefix_add) {
5355 $can_highlight = 0;
5356 last;
5362 if ($can_highlight) {
5363 for (my $i = 0; $i < @$add; $i++) {
5364 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5365 $rem->[$i], $add->[$i], $num_parents);
5366 push @new_rem, $line_rem;
5367 push @new_add, $line_add;
5369 } else {
5370 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5371 @new_add = map { format_diff_line($_, 'add') } @$add;
5374 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5376 return (\@new_ctx, \@new_rem, \@new_add);
5379 # Print context lines and then rem/add lines.
5380 sub print_diff_lines {
5381 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5382 my $is_combined = $num_parents > 1;
5384 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5385 $num_parents);
5387 if ($diff_style eq 'sidebyside' && !$is_combined) {
5388 print_sidebyside_diff_lines($ctx, $rem, $add);
5389 } else {
5390 # default 'inline' style and unknown styles
5391 print_inline_diff_lines($ctx, $rem, $add);
5395 sub print_diff_chunk {
5396 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5397 my (@ctx, @rem, @add);
5399 # The class of the previous line.
5400 my $prev_class = '';
5402 return unless @chunk;
5404 # incomplete last line might be among removed or added lines,
5405 # or both, or among context lines: find which
5406 for (my $i = 1; $i < @chunk; $i++) {
5407 if ($chunk[$i][0] eq 'incomplete') {
5408 $chunk[$i][0] = $chunk[$i-1][0];
5412 # guardian
5413 push @chunk, ["", ""];
5415 foreach my $line_info (@chunk) {
5416 my ($class, $line) = @$line_info;
5418 # print chunk headers
5419 if ($class && $class eq 'chunk_header') {
5420 print format_diff_line($line, $class, $from, $to);
5421 next;
5424 ## print from accumulator when have some add/rem lines or end
5425 # of chunk (flush context lines), or when have add and rem
5426 # lines and new block is reached (otherwise add/rem lines could
5427 # be reordered)
5428 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5429 (@rem && @add && $class ne $prev_class)) {
5430 print_diff_lines(\@ctx, \@rem, \@add,
5431 $diff_style, $num_parents);
5432 @ctx = @rem = @add = ();
5435 ## adding lines to accumulator
5436 # guardian value
5437 last unless $line;
5438 # rem, add or change
5439 if ($class eq 'rem') {
5440 push @rem, $line;
5441 } elsif ($class eq 'add') {
5442 push @add, $line;
5444 # context line
5445 if ($class eq 'ctx') {
5446 push @ctx, $line;
5449 $prev_class = $class;
5453 sub git_patchset_body {
5454 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5455 my ($hash_parent) = $hash_parents[0];
5457 my $is_combined = (@hash_parents > 1);
5458 my $patch_idx = 0;
5459 my $patch_number = 0;
5460 my $patch_line;
5461 my $diffinfo;
5462 my $to_name;
5463 my (%from, %to);
5464 my @chunk; # for side-by-side diff
5466 print "<div class=\"patchset\">\n";
5468 # skip to first patch
5469 while ($patch_line = <$fd>) {
5470 chomp $patch_line;
5472 last if ($patch_line =~ m/^diff /);
5475 PATCH:
5476 while ($patch_line) {
5478 # parse "git diff" header line
5479 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5480 # $1 is from_name, which we do not use
5481 $to_name = unquote($2);
5482 $to_name =~ s!^b/!!;
5483 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5484 # $1 is 'cc' or 'combined', which we do not use
5485 $to_name = unquote($2);
5486 } else {
5487 $to_name = undef;
5490 # check if current patch belong to current raw line
5491 # and parse raw git-diff line if needed
5492 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5493 # this is continuation of a split patch
5494 print "<div class=\"patch cont\">\n";
5495 } else {
5496 # advance raw git-diff output if needed
5497 $patch_idx++ if defined $diffinfo;
5499 # read and prepare patch information
5500 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5502 # compact combined diff output can have some patches skipped
5503 # find which patch (using pathname of result) we are at now;
5504 if ($is_combined) {
5505 while ($to_name ne $diffinfo->{'to_file'}) {
5506 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5507 format_diff_cc_simplified($diffinfo, @hash_parents) .
5508 "</div>\n"; # class="patch"
5510 $patch_idx++;
5511 $patch_number++;
5513 last if $patch_idx > $#$difftree;
5514 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5518 # modifies %from, %to hashes
5519 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5521 # this is first patch for raw difftree line with $patch_idx index
5522 # we index @$difftree array from 0, but number patches from 1
5523 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5526 # git diff header
5527 #assert($patch_line =~ m/^diff /) if DEBUG;
5528 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5529 $patch_number++;
5530 # print "git diff" header
5531 print format_git_diff_header_line($patch_line, $diffinfo,
5532 \%from, \%to);
5534 # print extended diff header
5535 print "<div class=\"diff extended_header\">\n";
5536 EXTENDED_HEADER:
5537 while ($patch_line = <$fd>) {
5538 chomp $patch_line;
5540 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5542 print format_extended_diff_header_line($patch_line, $diffinfo,
5543 \%from, \%to);
5545 print "</div>\n"; # class="diff extended_header"
5547 # from-file/to-file diff header
5548 if (! $patch_line) {
5549 print "</div>\n"; # class="patch"
5550 last PATCH;
5552 next PATCH if ($patch_line =~ m/^diff /);
5553 #assert($patch_line =~ m/^---/) if DEBUG;
5555 my $last_patch_line = $patch_line;
5556 $patch_line = <$fd>;
5557 chomp $patch_line;
5558 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5560 print format_diff_from_to_header($last_patch_line, $patch_line,
5561 $diffinfo, \%from, \%to,
5562 @hash_parents);
5564 # the patch itself
5565 LINE:
5566 while ($patch_line = <$fd>) {
5567 chomp $patch_line;
5569 next PATCH if ($patch_line =~ m/^diff /);
5571 my $class = diff_line_class($patch_line, \%from, \%to);
5573 if ($class eq 'chunk_header') {
5574 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5575 @chunk = ();
5578 push @chunk, [ $class, $patch_line ];
5581 } continue {
5582 if (@chunk) {
5583 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5584 @chunk = ();
5586 print "</div>\n"; # class="patch"
5589 # for compact combined (--cc) format, with chunk and patch simplification
5590 # the patchset might be empty, but there might be unprocessed raw lines
5591 for (++$patch_idx if $patch_number > 0;
5592 $patch_idx < @$difftree;
5593 ++$patch_idx) {
5594 # read and prepare patch information
5595 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5597 # generate anchor for "patch" links in difftree / whatchanged part
5598 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5599 format_diff_cc_simplified($diffinfo, @hash_parents) .
5600 "</div>\n"; # class="patch"
5602 $patch_number++;
5605 if ($patch_number == 0) {
5606 if (@hash_parents > 1) {
5607 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5608 } else {
5609 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5613 print "</div>\n"; # class="patchset"
5616 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5618 sub git_project_search_form {
5619 my ($searchtext, $search_use_regexp) = @_;
5621 my $limit = '';
5622 if ($project_filter) {
5623 $limit = " in '$project_filter/'";
5626 print "<div class=\"projsearch\">\n";
5627 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5628 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5629 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5630 if (defined $project_filter);
5631 print $cgi->textfield(-name => 's', -value => $searchtext,
5632 -title => "Search project by name and description$limit",
5633 -size => 60) . "\n" .
5634 "<span title=\"Extended regular expression\">" .
5635 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5636 -checked => $search_use_regexp) .
5637 "</span>\n" .
5638 $cgi->submit(-name => 'btnS', -value => 'Search') .
5639 $cgi->end_form() . "\n" .
5640 $cgi->a({-href => href(project => undef, searchtext => undef,
5641 project_filter => $project_filter)},
5642 esc_html("List all projects$limit")) . "<br />\n";
5643 print "</div>\n";
5646 # entry for given @keys needs filling if at least one of keys in list
5647 # is not present in %$project_info
5648 sub project_info_needs_filling {
5649 my ($project_info, @keys) = @_;
5651 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5652 foreach my $key (@keys) {
5653 if (!exists $project_info->{$key}) {
5654 return 1;
5657 return;
5660 # fills project list info (age, description, owner, category, forks, etc.)
5661 # for each project in the list, removing invalid projects from
5662 # returned list, or fill only specified info.
5664 # Invalid projects are removed from the returned list if and only if you
5665 # ask 'age' or 'age_string' to be filled, because they are the only fields
5666 # that run unconditionally git command that requires repository, and
5667 # therefore do always check if project repository is invalid.
5669 # USAGE:
5670 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5671 # ensures that 'descr_long' and 'ctags' fields are filled
5672 # * @project_list = fill_project_list_info(\@project_list)
5673 # ensures that all fields are filled (and invalid projects removed)
5675 # NOTE: modifies $projlist, but does not remove entries from it
5676 sub fill_project_list_info {
5677 my ($projlist, @wanted_keys) = @_;
5678 my @projects;
5679 my $filter_set = sub { return @_; };
5680 if (@wanted_keys) {
5681 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5682 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5685 my $show_ctags = gitweb_check_feature('ctags');
5686 PROJECT:
5687 foreach my $pr (@$projlist) {
5688 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5689 my (@activity) = git_get_last_activity($pr->{'path'});
5690 unless (@activity) {
5691 next PROJECT;
5693 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5695 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5696 my $descr = git_get_project_description($pr->{'path'}) || "";
5697 $descr = to_utf8($descr);
5698 $pr->{'descr_long'} = $descr;
5699 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5701 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5702 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5704 if ($show_ctags &&
5705 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5706 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5708 if ($projects_list_group_categories &&
5709 project_info_needs_filling($pr, $filter_set->('category'))) {
5710 my $cat = git_get_project_category($pr->{'path'}) ||
5711 $project_list_default_category;
5712 $pr->{'category'} = to_utf8($cat);
5715 push @projects, $pr;
5718 return @projects;
5721 sub sort_projects_list {
5722 my ($projlist, $order) = @_;
5724 sub order_str {
5725 my $key = shift;
5726 return sub { $a->{$key} cmp $b->{$key} };
5729 sub order_num_then_undef {
5730 my $key = shift;
5731 return sub {
5732 defined $a->{$key} ?
5733 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5734 (defined $b->{$key} ? 1 : 0)
5738 my %orderings = (
5739 project => order_str('path'),
5740 descr => order_str('descr_long'),
5741 owner => order_str('owner'),
5742 age => order_num_then_undef('age'),
5745 my $ordering = $orderings{$order};
5746 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5749 # returns a hash of categories, containing the list of project
5750 # belonging to each category
5751 sub build_projlist_by_category {
5752 my ($projlist, $from, $to) = @_;
5753 my %categories;
5755 $from = 0 unless defined $from;
5756 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5758 for (my $i = $from; $i <= $to; $i++) {
5759 my $pr = $projlist->[$i];
5760 push @{$categories{ $pr->{'category'} }}, $pr;
5763 return wantarray ? %categories : \%categories;
5766 # print 'sort by' <th> element, generating 'sort by $name' replay link
5767 # if that order is not selected
5768 sub print_sort_th {
5769 print format_sort_th(@_);
5772 sub format_sort_th {
5773 my ($name, $order, $header) = @_;
5774 my $sort_th = "";
5775 $header ||= ucfirst($name);
5777 if ($order eq $name) {
5778 $sort_th .= "<th>$header</th>\n";
5779 } else {
5780 $sort_th .= "<th>" .
5781 $cgi->a({-href => href(-replay=>1, order=>$name),
5782 -class => "header"}, $header) .
5783 "</th>\n";
5786 return $sort_th;
5789 sub git_project_list_rows {
5790 my ($projlist, $from, $to, $check_forks) = @_;
5792 $from = 0 unless defined $from;
5793 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5795 my $alternate = 1;
5796 for (my $i = $from; $i <= $to; $i++) {
5797 my $pr = $projlist->[$i];
5799 if ($alternate) {
5800 print "<tr class=\"dark\">\n";
5801 } else {
5802 print "<tr class=\"light\">\n";
5804 $alternate ^= 1;
5806 if ($check_forks) {
5807 print "<td>";
5808 if ($pr->{'forks'}) {
5809 my $nforks = scalar @{$pr->{'forks'}};
5810 if ($nforks > 0) {
5811 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5812 -title => "$nforks forks"}, "+");
5813 } else {
5814 print $cgi->span({-title => "$nforks forks"}, "+");
5817 print "</td>\n";
5819 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5820 -class => "list"},
5821 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5822 "</td>\n" .
5823 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5824 -class => "list",
5825 -title => $pr->{'descr_long'}},
5826 $search_regexp
5827 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5828 $pr->{'descr'}, $search_regexp)
5829 : esc_html($pr->{'descr'})) .
5830 "</td>\n";
5831 unless ($omit_owner) {
5832 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5834 unless ($omit_age_column) {
5835 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5836 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5838 print"<td class=\"link\">" .
5839 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5840 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5841 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5842 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5843 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5844 "</td>\n" .
5845 "</tr>\n";
5849 sub git_project_list_body {
5850 # actually uses global variable $project
5851 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5852 my @projects = @$projlist;
5854 my $check_forks = gitweb_check_feature('forks');
5855 my $show_ctags = gitweb_check_feature('ctags');
5856 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5857 $check_forks = undef
5858 if ($tagfilter || $search_regexp);
5860 # filtering out forks before filling info allows to do less work
5861 @projects = filter_forks_from_projects_list(\@projects)
5862 if ($check_forks);
5863 # search_projects_list pre-fills required info
5864 @projects = search_projects_list(\@projects,
5865 'search_regexp' => $search_regexp,
5866 'tagfilter' => $tagfilter)
5867 if ($tagfilter || $search_regexp);
5868 # fill the rest
5869 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5870 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5871 push @all_fields, 'owner' unless($omit_owner);
5872 @projects = fill_project_list_info(\@projects, @all_fields);
5874 $order ||= $default_projects_order;
5875 $from = 0 unless defined $from;
5876 $to = $#projects if (!defined $to || $#projects < $to);
5878 # short circuit
5879 if ($from > $to) {
5880 print "<center>\n".
5881 "<b>No such projects found</b><br />\n".
5882 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5883 "</center>\n<br />\n";
5884 return;
5887 @projects = sort_projects_list(\@projects, $order);
5889 if ($show_ctags) {
5890 my $ctags = git_gather_all_ctags(\@projects);
5891 my $cloud = git_populate_project_tagcloud($ctags);
5892 print git_show_project_tagcloud($cloud, 64);
5895 print "<table class=\"project_list\">\n";
5896 unless ($no_header) {
5897 print "<tr>\n";
5898 if ($check_forks) {
5899 print "<th></th>\n";
5901 print_sort_th('project', $order, 'Project');
5902 print_sort_th('descr', $order, 'Description');
5903 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5904 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5905 print "<th></th>\n" . # for links
5906 "</tr>\n";
5909 if ($projects_list_group_categories) {
5910 # only display categories with projects in the $from-$to window
5911 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5912 my %categories = build_projlist_by_category(\@projects, $from, $to);
5913 foreach my $cat (sort keys %categories) {
5914 unless ($cat eq "") {
5915 print "<tr>\n";
5916 if ($check_forks) {
5917 print "<td></td>\n";
5919 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5920 print "</tr>\n";
5923 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5925 } else {
5926 git_project_list_rows(\@projects, $from, $to, $check_forks);
5929 if (defined $extra) {
5930 print "<tr>\n";
5931 if ($check_forks) {
5932 print "<td></td>\n";
5934 print "<td colspan=\"5\">$extra</td>\n" .
5935 "</tr>\n";
5937 print "</table>\n";
5940 sub git_log_body {
5941 # uses global variable $project
5942 my ($commitlist, $from, $to, $refs, $extra) = @_;
5944 $from = 0 unless defined $from;
5945 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5947 for (my $i = 0; $i <= $to; $i++) {
5948 my %co = %{$commitlist->[$i]};
5949 next if !%co;
5950 my $commit = $co{'id'};
5951 my $ref = format_ref_marker($refs, $commit);
5952 git_print_header_div('commit',
5953 "<span class=\"age\">$co{'age_string'}</span>" .
5954 esc_html($co{'title'}) . $ref,
5955 $commit);
5956 print "<div class=\"title_text\">\n" .
5957 "<div class=\"log_link\">\n" .
5958 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5959 " | " .
5960 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5961 " | " .
5962 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5963 "<br/>\n" .
5964 "</div>\n";
5965 git_print_authorship(\%co, -tag => 'span');
5966 print "<br/>\n</div>\n";
5968 print "<div class=\"log_body\">\n";
5969 git_print_log($co{'comment'}, -final_empty_line=> 1);
5970 print "</div>\n";
5972 if ($extra) {
5973 print "<div class=\"page_nav\">\n";
5974 print "$extra\n";
5975 print "</div>\n";
5979 sub git_shortlog_body {
5980 # uses global variable $project
5981 my ($commitlist, $from, $to, $refs, $extra) = @_;
5983 $from = 0 unless defined $from;
5984 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5986 print "<table class=\"shortlog\">\n";
5987 my $alternate = 1;
5988 for (my $i = $from; $i <= $to; $i++) {
5989 my %co = %{$commitlist->[$i]};
5990 my $commit = $co{'id'};
5991 my $ref = format_ref_marker($refs, $commit);
5992 if ($alternate) {
5993 print "<tr class=\"dark\">\n";
5994 } else {
5995 print "<tr class=\"light\">\n";
5997 $alternate ^= 1;
5998 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5999 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6000 format_author_html('td', \%co, 10) . "<td>";
6001 print format_subject_html($co{'title'}, $co{'title_short'},
6002 href(action=>"commit", hash=>$commit), $ref);
6003 print "</td>\n" .
6004 "<td class=\"link\">" .
6005 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
6006 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
6007 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
6008 my $snapshot_links = format_snapshot_links($commit);
6009 if (defined $snapshot_links) {
6010 print " | " . $snapshot_links;
6012 print "</td>\n" .
6013 "</tr>\n";
6015 if (defined $extra) {
6016 print "<tr>\n" .
6017 "<td colspan=\"4\">$extra</td>\n" .
6018 "</tr>\n";
6020 print "</table>\n";
6023 sub git_history_body {
6024 # Warning: assumes constant type (blob or tree) during history
6025 my ($commitlist, $from, $to, $refs, $extra,
6026 $file_name, $file_hash, $ftype) = @_;
6028 $from = 0 unless defined $from;
6029 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
6031 print "<table class=\"history\">\n";
6032 my $alternate = 1;
6033 for (my $i = $from; $i <= $to; $i++) {
6034 my %co = %{$commitlist->[$i]};
6035 if (!%co) {
6036 next;
6038 my $commit = $co{'id'};
6040 my $ref = format_ref_marker($refs, $commit);
6042 if ($alternate) {
6043 print "<tr class=\"dark\">\n";
6044 } else {
6045 print "<tr class=\"light\">\n";
6047 $alternate ^= 1;
6048 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6049 # shortlog: format_author_html('td', \%co, 10)
6050 format_author_html('td', \%co, 15, 3) . "<td>";
6051 # originally git_history used chop_str($co{'title'}, 50)
6052 print format_subject_html($co{'title'}, $co{'title_short'},
6053 href(action=>"commit", hash=>$commit), $ref);
6054 print "</td>\n" .
6055 "<td class=\"link\">" .
6056 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
6057 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
6059 if ($ftype eq 'blob') {
6060 my $blob_current = $file_hash;
6061 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6062 if (defined $blob_current && defined $blob_parent &&
6063 $blob_current ne $blob_parent) {
6064 print " | " .
6065 $cgi->a({-href => href(action=>"blobdiff",
6066 hash=>$blob_current, hash_parent=>$blob_parent,
6067 hash_base=>$hash_base, hash_parent_base=>$commit,
6068 file_name=>$file_name)},
6069 "diff to current");
6072 print "</td>\n" .
6073 "</tr>\n";
6075 if (defined $extra) {
6076 print "<tr>\n" .
6077 "<td colspan=\"4\">$extra</td>\n" .
6078 "</tr>\n";
6080 print "</table>\n";
6083 sub git_tags_body {
6084 # uses global variable $project
6085 my ($taglist, $from, $to, $extra) = @_;
6086 $from = 0 unless defined $from;
6087 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6089 print "<table class=\"tags\">\n";
6090 my $alternate = 1;
6091 for (my $i = $from; $i <= $to; $i++) {
6092 my $entry = $taglist->[$i];
6093 my %tag = %$entry;
6094 my $comment = $tag{'subject'};
6095 my $comment_short;
6096 if (defined $comment) {
6097 $comment_short = chop_str($comment, 30, 5);
6099 if ($alternate) {
6100 print "<tr class=\"dark\">\n";
6101 } else {
6102 print "<tr class=\"light\">\n";
6104 $alternate ^= 1;
6105 if (defined $tag{'age'}) {
6106 print "<td><i>$tag{'age'}</i></td>\n";
6107 } else {
6108 print "<td></td>\n";
6110 print "<td>" .
6111 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6112 -class => "list name"}, esc_html($tag{'name'})) .
6113 "</td>\n" .
6114 "<td>";
6115 if (defined $comment) {
6116 print format_subject_html($comment, $comment_short,
6117 href(action=>"tag", hash=>$tag{'id'}));
6119 print "</td>\n" .
6120 "<td class=\"selflink\">";
6121 if ($tag{'type'} eq "tag") {
6122 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6123 } else {
6124 print "&nbsp;";
6126 print "</td>\n" .
6127 "<td class=\"link\">" . " | " .
6128 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6129 if ($tag{'reftype'} eq "commit") {
6130 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6131 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6132 } elsif ($tag{'reftype'} eq "blob") {
6133 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6135 print "</td>\n" .
6136 "</tr>";
6138 if (defined $extra) {
6139 print "<tr>\n" .
6140 "<td colspan=\"5\">$extra</td>\n" .
6141 "</tr>\n";
6143 print "</table>\n";
6146 sub git_heads_body {
6147 # uses global variable $project
6148 my ($headlist, $head_at, $from, $to, $extra) = @_;
6149 $from = 0 unless defined $from;
6150 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6152 print "<table class=\"heads\">\n";
6153 my $alternate = 1;
6154 for (my $i = $from; $i <= $to; $i++) {
6155 my $entry = $headlist->[$i];
6156 my %ref = %$entry;
6157 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6158 if ($alternate) {
6159 print "<tr class=\"dark\">\n";
6160 } else {
6161 print "<tr class=\"light\">\n";
6163 $alternate ^= 1;
6164 print "<td><i>$ref{'age'}</i></td>\n" .
6165 ($curr ? "<td class=\"current_head\">" : "<td>") .
6166 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6167 -class => "list name"},esc_html($ref{'name'})) .
6168 "</td>\n" .
6169 "<td class=\"link\">" .
6170 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6171 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6172 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6173 "</td>\n" .
6174 "</tr>";
6176 if (defined $extra) {
6177 print "<tr>\n" .
6178 "<td colspan=\"3\">$extra</td>\n" .
6179 "</tr>\n";
6181 print "</table>\n";
6184 # Display a single remote block
6185 sub git_remote_block {
6186 my ($remote, $rdata, $limit, $head) = @_;
6188 my $heads = $rdata->{'heads'};
6189 my $fetch = $rdata->{'fetch'};
6190 my $push = $rdata->{'push'};
6192 my $urls_table = "<table class=\"projects_list\">\n" ;
6194 if (defined $fetch) {
6195 if ($fetch eq $push) {
6196 $urls_table .= format_repo_url("URL", $fetch);
6197 } else {
6198 $urls_table .= format_repo_url("Fetch URL", $fetch);
6199 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6201 } elsif (defined $push) {
6202 $urls_table .= format_repo_url("Push URL", $push);
6203 } else {
6204 $urls_table .= format_repo_url("", "No remote URL");
6207 $urls_table .= "</table>\n";
6209 my $dots;
6210 if (defined $limit && $limit < @$heads) {
6211 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6214 print $urls_table;
6215 git_heads_body($heads, $head, 0, $limit, $dots);
6218 # Display a list of remote names with the respective fetch and push URLs
6219 sub git_remotes_list {
6220 my ($remotedata, $limit) = @_;
6221 print "<table class=\"heads\">\n";
6222 my $alternate = 1;
6223 my @remotes = sort keys %$remotedata;
6225 my $limited = $limit && $limit < @remotes;
6227 $#remotes = $limit - 1 if $limited;
6229 while (my $remote = shift @remotes) {
6230 my $rdata = $remotedata->{$remote};
6231 my $fetch = $rdata->{'fetch'};
6232 my $push = $rdata->{'push'};
6233 if ($alternate) {
6234 print "<tr class=\"dark\">\n";
6235 } else {
6236 print "<tr class=\"light\">\n";
6238 $alternate ^= 1;
6239 print "<td>" .
6240 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6241 -class=> "list name"},esc_html($remote)) .
6242 "</td>";
6243 print "<td class=\"link\">" .
6244 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6245 " | " .
6246 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6247 "</td>";
6249 print "</tr>\n";
6252 if ($limited) {
6253 print "<tr>\n" .
6254 "<td colspan=\"3\">" .
6255 $cgi->a({-href => href(action=>"remotes")}, "...") .
6256 "</td>\n" . "</tr>\n";
6259 print "</table>";
6262 # Display remote heads grouped by remote, unless there are too many
6263 # remotes, in which case we only display the remote names
6264 sub git_remotes_body {
6265 my ($remotedata, $limit, $head) = @_;
6266 if ($limit and $limit < keys %$remotedata) {
6267 git_remotes_list($remotedata, $limit);
6268 } else {
6269 fill_remote_heads($remotedata);
6270 while (my ($remote, $rdata) = each %$remotedata) {
6271 git_print_section({-class=>"remote", -id=>$remote},
6272 ["remotes", $remote, $remote], sub {
6273 git_remote_block($remote, $rdata, $limit, $head);
6279 sub git_search_message {
6280 my %co = @_;
6282 my $greptype;
6283 if ($searchtype eq 'commit') {
6284 $greptype = "--grep=";
6285 } elsif ($searchtype eq 'author') {
6286 $greptype = "--author=";
6287 } elsif ($searchtype eq 'committer') {
6288 $greptype = "--committer=";
6290 $greptype .= $searchtext;
6291 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6292 $greptype, '--regexp-ignore-case',
6293 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6295 my $paging_nav = '';
6296 if ($page > 0) {
6297 $paging_nav .=
6298 $cgi->a({-href => href(-replay=>1, page=>undef)},
6299 "first") .
6300 " &sdot; " .
6301 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6302 -accesskey => "p", -title => "Alt-p"}, "prev");
6303 } else {
6304 $paging_nav .= "first &sdot; prev";
6306 my $next_link = '';
6307 if ($#commitlist >= 100) {
6308 $next_link =
6309 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6310 -accesskey => "n", -title => "Alt-n"}, "next");
6311 $paging_nav .= " &sdot; $next_link";
6312 } else {
6313 $paging_nav .= " &sdot; next";
6316 git_header_html();
6318 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6319 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6320 if ($page == 0 && !@commitlist) {
6321 print "<p>No match.</p>\n";
6322 } else {
6323 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6326 git_footer_html();
6329 sub git_search_changes {
6330 my %co = @_;
6332 local $/ = "\n";
6333 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6334 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6335 ($search_use_regexp ? '--pickaxe-regex' : ())
6336 or die_error(500, "Open git-log failed");
6338 git_header_html();
6340 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6341 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6343 print "<table class=\"pickaxe search\">\n";
6344 my $alternate = 1;
6345 undef %co;
6346 my @files;
6347 while (my $line = <$fd>) {
6348 chomp $line;
6349 next unless $line;
6351 my %set = parse_difftree_raw_line($line);
6352 if (defined $set{'commit'}) {
6353 # finish previous commit
6354 if (%co) {
6355 print "</td>\n" .
6356 "<td class=\"link\">" .
6357 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6358 "commit") .
6359 " | " .
6360 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6361 hash_base=>$co{'id'})},
6362 "tree") .
6363 "</td>\n" .
6364 "</tr>\n";
6367 if ($alternate) {
6368 print "<tr class=\"dark\">\n";
6369 } else {
6370 print "<tr class=\"light\">\n";
6372 $alternate ^= 1;
6373 %co = parse_commit($set{'commit'});
6374 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6375 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6376 "<td><i>$author</i></td>\n" .
6377 "<td>" .
6378 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6379 -class => "list subject"},
6380 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6381 } elsif (defined $set{'to_id'}) {
6382 next if ($set{'to_id'} =~ m/^0{40}$/);
6384 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6385 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6386 -class => "list"},
6387 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6388 "<br/>\n";
6391 close $fd;
6393 # finish last commit (warning: repetition!)
6394 if (%co) {
6395 print "</td>\n" .
6396 "<td class=\"link\">" .
6397 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6398 "commit") .
6399 " | " .
6400 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6401 hash_base=>$co{'id'})},
6402 "tree") .
6403 "</td>\n" .
6404 "</tr>\n";
6407 print "</table>\n";
6409 git_footer_html();
6412 sub git_search_files {
6413 my %co = @_;
6415 local $/ = "\n";
6416 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6417 $search_use_regexp ? ('-E', '-i') : '-F',
6418 $searchtext, $co{'tree'}
6419 or die_error(500, "Open git-grep failed");
6421 git_header_html();
6423 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6424 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6426 print "<table class=\"grep_search\">\n";
6427 my $alternate = 1;
6428 my $matches = 0;
6429 my $lastfile = '';
6430 my $file_href;
6431 while (my $line = <$fd>) {
6432 chomp $line;
6433 my ($file, $lno, $ltext, $binary);
6434 last if ($matches++ > 1000);
6435 if ($line =~ /^Binary file (.+) matches$/) {
6436 $file = $1;
6437 $binary = 1;
6438 } else {
6439 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6440 $file =~ s/^$co{'tree'}://;
6442 if ($file ne $lastfile) {
6443 $lastfile and print "</td></tr>\n";
6444 if ($alternate++) {
6445 print "<tr class=\"dark\">\n";
6446 } else {
6447 print "<tr class=\"light\">\n";
6449 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6450 file_name=>$file);
6451 print "<td class=\"list\">".
6452 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6453 print "</td><td>\n";
6454 $lastfile = $file;
6456 if ($binary) {
6457 print "<div class=\"binary\">Binary file</div>\n";
6458 } else {
6459 $ltext = untabify($ltext);
6460 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6461 $ltext = esc_html($1, -nbsp=>1);
6462 $ltext .= '<span class="match">';
6463 $ltext .= esc_html($2, -nbsp=>1);
6464 $ltext .= '</span>';
6465 $ltext .= esc_html($3, -nbsp=>1);
6466 } else {
6467 $ltext = esc_html($ltext, -nbsp=>1);
6469 print "<div class=\"pre\">" .
6470 $cgi->a({-href => $file_href.'#l'.$lno,
6471 -class => "linenr"}, sprintf('%4i', $lno)) .
6472 ' ' . $ltext . "</div>\n";
6475 if ($lastfile) {
6476 print "</td></tr>\n";
6477 if ($matches > 1000) {
6478 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6480 } else {
6481 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6483 close $fd;
6485 print "</table>\n";
6487 git_footer_html();
6490 sub git_search_grep_body {
6491 my ($commitlist, $from, $to, $extra) = @_;
6492 $from = 0 unless defined $from;
6493 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6495 print "<table class=\"commit_search\">\n";
6496 my $alternate = 1;
6497 for (my $i = $from; $i <= $to; $i++) {
6498 my %co = %{$commitlist->[$i]};
6499 if (!%co) {
6500 next;
6502 my $commit = $co{'id'};
6503 if ($alternate) {
6504 print "<tr class=\"dark\">\n";
6505 } else {
6506 print "<tr class=\"light\">\n";
6508 $alternate ^= 1;
6509 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6510 format_author_html('td', \%co, 15, 5) .
6511 "<td>" .
6512 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6513 -class => "list subject"},
6514 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6515 my $comment = $co{'comment'};
6516 foreach my $line (@$comment) {
6517 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6518 my ($lead, $match, $trail) = ($1, $2, $3);
6519 $match = chop_str($match, 70, 5, 'center');
6520 my $contextlen = int((80 - length($match))/2);
6521 $contextlen = 30 if ($contextlen > 30);
6522 $lead = chop_str($lead, $contextlen, 10, 'left');
6523 $trail = chop_str($trail, $contextlen, 10, 'right');
6525 $lead = esc_html($lead);
6526 $match = esc_html($match);
6527 $trail = esc_html($trail);
6529 print "$lead<span class=\"match\">$match</span>$trail<br />";
6532 print "</td>\n" .
6533 "<td class=\"link\">" .
6534 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6535 " | " .
6536 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6537 " | " .
6538 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6539 print "</td>\n" .
6540 "</tr>\n";
6542 if (defined $extra) {
6543 print "<tr>\n" .
6544 "<td colspan=\"3\">$extra</td>\n" .
6545 "</tr>\n";
6547 print "</table>\n";
6550 ## ======================================================================
6551 ## ======================================================================
6552 ## actions
6554 sub git_project_list {
6555 my $order = $input_params{'order'};
6556 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6557 die_error(400, "Unknown order parameter");
6560 my @list = git_get_projects_list($project_filter, $strict_export);
6561 if (!@list) {
6562 die_error(404, "No projects found");
6565 git_header_html();
6566 if (defined $home_text && -f $home_text) {
6567 print "<div class=\"index_include\">\n";
6568 insert_file($home_text);
6569 print "</div>\n";
6572 git_project_search_form($searchtext, $search_use_regexp);
6573 git_project_list_body(\@list, $order);
6574 git_footer_html();
6577 sub git_forks {
6578 my $order = $input_params{'order'};
6579 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6580 die_error(400, "Unknown order parameter");
6583 my $filter = $project;
6584 $filter =~ s/\.git$//;
6585 my @list = git_get_projects_list($filter);
6586 if (!@list) {
6587 die_error(404, "No forks found");
6590 git_header_html();
6591 git_print_page_nav('','');
6592 git_print_header_div('summary', "$project forks");
6593 git_project_list_body(\@list, $order);
6594 git_footer_html();
6597 sub git_project_index {
6598 my @projects = git_get_projects_list($project_filter, $strict_export);
6599 if (!@projects) {
6600 die_error(404, "No projects found");
6603 print $cgi->header(
6604 -type => 'text/plain',
6605 -charset => 'utf-8',
6606 -content_disposition => 'inline; filename="index.aux"');
6608 foreach my $pr (@projects) {
6609 if (!exists $pr->{'owner'}) {
6610 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6613 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6614 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6615 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6616 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6617 $path =~ s/ /\+/g;
6618 $owner =~ s/ /\+/g;
6620 print "$path $owner\n";
6624 sub git_summary {
6625 my $descr = git_get_project_description($project) || "none";
6626 my %co = parse_commit("HEAD");
6627 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6628 my $head = $co{'id'};
6629 my $remote_heads = gitweb_check_feature('remote_heads');
6631 my $owner = git_get_project_owner($project);
6633 my $refs = git_get_references();
6634 # These get_*_list functions return one more to allow us to see if
6635 # there are more ...
6636 my @taglist = git_get_tags_list(16);
6637 my @headlist = git_get_heads_list(16);
6638 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6639 my @forklist;
6640 my $check_forks = gitweb_check_feature('forks');
6642 if ($check_forks) {
6643 # find forks of a project
6644 my $filter = $project;
6645 $filter =~ s/\.git$//;
6646 @forklist = git_get_projects_list($filter);
6647 # filter out forks of forks
6648 @forklist = filter_forks_from_projects_list(\@forklist)
6649 if (@forklist);
6652 git_header_html();
6653 git_print_page_nav('summary','', $head);
6655 print "<div class=\"title\">&nbsp;</div>\n";
6656 print "<table class=\"projects_list\">\n" .
6657 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6658 if ($owner and not $omit_owner) {
6659 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . email_obfuscate($owner) . "</td></tr>\n";
6661 if (defined $cd{'rfc2822'}) {
6662 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6663 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6666 # use per project git URL list in $projectroot/$project/cloneurl
6667 # or make project git URL from git base URL and project name
6668 my $url_tag = "URL";
6669 my @url_list = git_get_project_url_list($project);
6670 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6671 foreach my $git_url (@url_list) {
6672 next unless $git_url;
6673 print format_repo_url($url_tag, $git_url);
6674 $url_tag = "";
6677 # Tag cloud
6678 my $show_ctags = gitweb_check_feature('ctags');
6679 if ($show_ctags) {
6680 my $ctags = git_get_project_ctags($project);
6681 if (%$ctags) {
6682 # without ability to add tags, don't show if there are none
6683 my $cloud = git_populate_project_tagcloud($ctags);
6684 print "<tr id=\"metadata_ctags\">" .
6685 "<td>content tags</td>" .
6686 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6687 "</tr>\n";
6691 print "</table>\n";
6693 # If XSS prevention is on, we don't include README.html.
6694 # TODO: Allow a readme in some safe format.
6695 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6696 print "<div class=\"title\">readme</div>\n" .
6697 "<div class=\"readme\">\n";
6698 insert_file("$projectroot/$project/README.html");
6699 print "\n</div>\n"; # class="readme"
6702 # we need to request one more than 16 (0..15) to check if
6703 # those 16 are all
6704 my @commitlist = $head ? parse_commits($head, 17) : ();
6705 if (@commitlist) {
6706 git_print_header_div('shortlog');
6707 git_shortlog_body(\@commitlist, 0, 15, $refs,
6708 $#commitlist <= 15 ? undef :
6709 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6712 if (@taglist) {
6713 git_print_header_div('tags');
6714 git_tags_body(\@taglist, 0, 15,
6715 $#taglist <= 15 ? undef :
6716 $cgi->a({-href => href(action=>"tags")}, "..."));
6719 if (@headlist) {
6720 git_print_header_div('heads');
6721 git_heads_body(\@headlist, $head, 0, 15,
6722 $#headlist <= 15 ? undef :
6723 $cgi->a({-href => href(action=>"heads")}, "..."));
6726 if (%remotedata) {
6727 git_print_header_div('remotes');
6728 git_remotes_body(\%remotedata, 15, $head);
6731 if (@forklist) {
6732 git_print_header_div('forks');
6733 git_project_list_body(\@forklist, 'age', 0, 15,
6734 $#forklist <= 15 ? undef :
6735 $cgi->a({-href => href(action=>"forks")}, "..."),
6736 'no_header');
6739 git_footer_html();
6742 sub git_tag {
6743 my %tag = parse_tag($hash);
6745 if (! %tag) {
6746 die_error(404, "Unknown tag object");
6749 my $head = git_get_head_hash($project);
6750 git_header_html();
6751 git_print_page_nav('','', $head,undef,$head);
6752 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6753 print "<div class=\"title_text\">\n" .
6754 "<table class=\"object_header\">\n" .
6755 "<tr>\n" .
6756 "<td>object</td>\n" .
6757 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6758 $tag{'object'}) . "</td>\n" .
6759 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6760 $tag{'type'}) . "</td>\n" .
6761 "</tr>\n";
6762 if (defined($tag{'author'})) {
6763 git_print_authorship_rows(\%tag, 'author');
6765 print "</table>\n\n" .
6766 "</div>\n";
6767 print "<div class=\"page_body\">";
6768 my $comment = $tag{'comment'};
6769 foreach my $line (@$comment) {
6770 chomp $line;
6771 print esc_html($line, -nbsp=>1) . "<br/>\n";
6773 print "</div>\n";
6774 git_footer_html();
6777 sub git_blame_common {
6778 my $format = shift || 'porcelain';
6779 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6780 $format = 'incremental';
6781 $action = 'blame_incremental'; # for page title etc
6784 # permissions
6785 gitweb_check_feature('blame')
6786 or die_error(403, "Blame view not allowed");
6788 # error checking
6789 die_error(400, "No file name given") unless $file_name;
6790 $hash_base ||= git_get_head_hash($project);
6791 die_error(404, "Couldn't find base commit") unless $hash_base;
6792 my %co = parse_commit($hash_base)
6793 or die_error(404, "Commit not found");
6794 my $ftype = "blob";
6795 if (!defined $hash) {
6796 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6797 or die_error(404, "Error looking up file");
6798 } else {
6799 $ftype = git_get_type($hash);
6800 if ($ftype !~ "blob") {
6801 die_error(400, "Object is not a blob");
6805 my $fd;
6806 if ($format eq 'incremental') {
6807 # get file contents (as base)
6808 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6809 or die_error(500, "Open git-cat-file failed");
6810 } elsif ($format eq 'data') {
6811 # run git-blame --incremental
6812 open $fd, "-|", git_cmd(), "blame", "--incremental",
6813 $hash_base, "--", $file_name
6814 or die_error(500, "Open git-blame --incremental failed");
6815 } else {
6816 # run git-blame --porcelain
6817 open $fd, "-|", git_cmd(), "blame", '-p',
6818 $hash_base, '--', $file_name
6819 or die_error(500, "Open git-blame --porcelain failed");
6821 binmode $fd, ':utf8';
6823 # incremental blame data returns early
6824 if ($format eq 'data') {
6825 print $cgi->header(
6826 -type=>"text/plain", -charset => "utf-8",
6827 -status=> "200 OK");
6828 local $| = 1; # output autoflush
6829 while (my $line = <$fd>) {
6830 print to_utf8($line);
6832 close $fd
6833 or print "ERROR $!\n";
6835 print 'END';
6836 if (defined $t0 && gitweb_check_feature('timed')) {
6837 print ' '.
6838 tv_interval($t0, [ gettimeofday() ]).
6839 ' '.$number_of_git_cmds;
6841 print "\n";
6843 return;
6846 # page header
6847 git_header_html();
6848 my $formats_nav =
6849 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6850 "blob") .
6851 " | ";
6852 if ($format eq 'incremental') {
6853 $formats_nav .=
6854 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6855 "blame") . " (non-incremental)";
6856 } else {
6857 $formats_nav .=
6858 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6859 "blame") . " (incremental)";
6861 $formats_nav .=
6862 " | " .
6863 $cgi->a({-href => href(action=>"history", -replay=>1)},
6864 "history") .
6865 " | " .
6866 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6867 "HEAD");
6868 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6869 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6870 git_print_page_path($file_name, $ftype, $hash_base);
6872 # page body
6873 if ($format eq 'incremental') {
6874 print "<noscript>\n<div class=\"error\"><center><b>\n".
6875 "This page requires JavaScript to run.\n Use ".
6876 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6877 'this page').
6878 " instead.\n".
6879 "</b></center></div>\n</noscript>\n";
6881 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6884 print qq!<div class="page_body">\n!;
6885 print qq!<div id="progress_info">... / ...</div>\n!
6886 if ($format eq 'incremental');
6887 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6888 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6889 qq!<thead>\n!.
6890 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6891 qq!</thead>\n!.
6892 qq!<tbody>\n!;
6894 my @rev_color = qw(light dark);
6895 my $num_colors = scalar(@rev_color);
6896 my $current_color = 0;
6898 if ($format eq 'incremental') {
6899 my $color_class = $rev_color[$current_color];
6901 #contents of a file
6902 my $linenr = 0;
6903 LINE:
6904 while (my $line = <$fd>) {
6905 chomp $line;
6906 $linenr++;
6908 print qq!<tr id="l$linenr" class="$color_class">!.
6909 qq!<td class="sha1"><a href=""> </a></td>!.
6910 qq!<td class="linenr">!.
6911 qq!<a class="linenr" href="">$linenr</a></td>!;
6912 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6913 print qq!</tr>\n!;
6916 } else { # porcelain, i.e. ordinary blame
6917 my %metainfo = (); # saves information about commits
6919 # blame data
6920 LINE:
6921 while (my $line = <$fd>) {
6922 chomp $line;
6923 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6924 # no <lines in group> for subsequent lines in group of lines
6925 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6926 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6927 if (!exists $metainfo{$full_rev}) {
6928 $metainfo{$full_rev} = { 'nprevious' => 0 };
6930 my $meta = $metainfo{$full_rev};
6931 my $data;
6932 while ($data = <$fd>) {
6933 chomp $data;
6934 last if ($data =~ s/^\t//); # contents of line
6935 if ($data =~ /^(\S+)(?: (.*))?$/) {
6936 $meta->{$1} = $2 unless exists $meta->{$1};
6938 if ($data =~ /^previous /) {
6939 $meta->{'nprevious'}++;
6942 my $short_rev = substr($full_rev, 0, 8);
6943 my $author = $meta->{'author'};
6944 my %date =
6945 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6946 my $date = $date{'iso-tz'};
6947 if ($group_size) {
6948 $current_color = ($current_color + 1) % $num_colors;
6950 my $tr_class = $rev_color[$current_color];
6951 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6952 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6953 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6954 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6955 if ($group_size) {
6956 print "<td class=\"sha1\"";
6957 print " title=\"". esc_html($author) . ", $date\"";
6958 print " rowspan=\"$group_size\"" if ($group_size > 1);
6959 print ">";
6960 print $cgi->a({-href => href(action=>"commit",
6961 hash=>$full_rev,
6962 file_name=>$file_name)},
6963 esc_html($short_rev));
6964 if ($group_size >= 2) {
6965 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6966 if (@author_initials) {
6967 print "<br />" .
6968 esc_html(join('', @author_initials));
6969 # or join('.', ...)
6972 print "</td>\n";
6974 # 'previous' <sha1 of parent commit> <filename at commit>
6975 if (exists $meta->{'previous'} &&
6976 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6977 $meta->{'parent'} = $1;
6978 $meta->{'file_parent'} = unquote($2);
6980 my $linenr_commit =
6981 exists($meta->{'parent'}) ?
6982 $meta->{'parent'} : $full_rev;
6983 my $linenr_filename =
6984 exists($meta->{'file_parent'}) ?
6985 $meta->{'file_parent'} : unquote($meta->{'filename'});
6986 my $blamed = href(action => 'blame',
6987 file_name => $linenr_filename,
6988 hash_base => $linenr_commit);
6989 print "<td class=\"linenr\">";
6990 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6991 -class => "linenr" },
6992 esc_html($lineno));
6993 print "</td>";
6994 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6995 print "</tr>\n";
6996 } # end while
7000 # footer
7001 print "</tbody>\n".
7002 "</table>\n"; # class="blame"
7003 print "</div>\n"; # class="blame_body"
7004 close $fd
7005 or print "Reading blob failed\n";
7007 git_footer_html();
7010 sub git_blame {
7011 git_blame_common();
7014 sub git_blame_incremental {
7015 git_blame_common('incremental');
7018 sub git_blame_data {
7019 git_blame_common('data');
7022 sub git_tags {
7023 my $head = git_get_head_hash($project);
7024 git_header_html();
7025 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
7026 git_print_header_div('summary', $project);
7028 my @tagslist = git_get_tags_list();
7029 if (@tagslist) {
7030 git_tags_body(\@tagslist);
7032 git_footer_html();
7035 sub git_heads {
7036 my $head = git_get_head_hash($project);
7037 git_header_html();
7038 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
7039 git_print_header_div('summary', $project);
7041 my @headslist = git_get_heads_list();
7042 if (@headslist) {
7043 git_heads_body(\@headslist, $head);
7045 git_footer_html();
7048 # used both for single remote view and for list of all the remotes
7049 sub git_remotes {
7050 gitweb_check_feature('remote_heads')
7051 or die_error(403, "Remote heads view is disabled");
7053 my $head = git_get_head_hash($project);
7054 my $remote = $input_params{'hash'};
7056 my $remotedata = git_get_remotes_list($remote);
7057 die_error(500, "Unable to get remote information") unless defined $remotedata;
7059 unless (%$remotedata) {
7060 die_error(404, defined $remote ?
7061 "Remote $remote not found" :
7062 "No remotes found");
7065 git_header_html(undef, undef, -action_extra => $remote);
7066 git_print_page_nav('', '', $head, undef, $head,
7067 format_ref_views($remote ? '' : 'remotes'));
7069 fill_remote_heads($remotedata);
7070 if (defined $remote) {
7071 git_print_header_div('remotes', "$remote remote for $project");
7072 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7073 } else {
7074 git_print_header_div('summary', "$project remotes");
7075 git_remotes_body($remotedata, undef, $head);
7078 git_footer_html();
7081 sub git_blob_plain {
7082 my $type = shift;
7083 my $expires;
7085 if (!defined $hash) {
7086 if (defined $file_name) {
7087 my $base = $hash_base || git_get_head_hash($project);
7088 $hash = git_get_hash_by_path($base, $file_name, "blob")
7089 or die_error(404, "Cannot find file");
7090 } else {
7091 die_error(400, "No file name defined");
7093 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7094 # blobs defined by non-textual hash id's can be cached
7095 $expires = "+1d";
7098 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7099 or die_error(500, "Open git-cat-file blob '$hash' failed");
7101 # content-type (can include charset)
7102 $type = blob_contenttype($fd, $file_name, $type);
7104 # "save as" filename, even when no $file_name is given
7105 my $save_as = "$hash";
7106 if (defined $file_name) {
7107 $save_as = $file_name;
7108 } elsif ($type =~ m/^text\//) {
7109 $save_as .= '.txt';
7112 # With XSS prevention on, blobs of all types except a few known safe
7113 # ones are served with "Content-Disposition: attachment" to make sure
7114 # they don't run in our security domain. For certain image types,
7115 # blob view writes an <img> tag referring to blob_plain view, and we
7116 # want to be sure not to break that by serving the image as an
7117 # attachment (though Firefox 3 doesn't seem to care).
7118 my $sandbox = $prevent_xss &&
7119 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7121 # serve text/* as text/plain
7122 if ($prevent_xss &&
7123 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7124 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7125 my $rest = $1;
7126 $rest = defined $rest ? $rest : '';
7127 $type = "text/plain$rest";
7130 print $cgi->header(
7131 -type => $type,
7132 -expires => $expires,
7133 -content_disposition =>
7134 ($sandbox ? 'attachment' : 'inline')
7135 . '; filename="' . $save_as . '"');
7136 local $/ = undef;
7137 binmode STDOUT, ':raw';
7138 print <$fd>;
7139 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7140 close $fd;
7143 sub git_blob {
7144 my $expires;
7146 if (!defined $hash) {
7147 if (defined $file_name) {
7148 my $base = $hash_base || git_get_head_hash($project);
7149 $hash = git_get_hash_by_path($base, $file_name, "blob")
7150 or die_error(404, "Cannot find file");
7151 } else {
7152 die_error(400, "No file name defined");
7154 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7155 # blobs defined by non-textual hash id's can be cached
7156 $expires = "+1d";
7159 my $have_blame = gitweb_check_feature('blame');
7160 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7161 or die_error(500, "Couldn't cat $file_name, $hash");
7162 my $mimetype = blob_mimetype($fd, $file_name);
7163 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7164 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7165 close $fd;
7166 return git_blob_plain($mimetype);
7168 # we can have blame only for text/* mimetype
7169 $have_blame &&= ($mimetype =~ m!^text/!);
7171 my $highlight = gitweb_check_feature('highlight');
7172 my $syntax = guess_file_syntax($highlight, $file_name);
7173 $fd = run_highlighter($fd, $highlight, $syntax);
7175 git_header_html(undef, $expires);
7176 my $formats_nav = '';
7177 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7178 if (defined $file_name) {
7179 if ($have_blame) {
7180 $formats_nav .=
7181 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7182 "blame") .
7183 " | ";
7185 $formats_nav .=
7186 $cgi->a({-href => href(action=>"history", -replay=>1)},
7187 "history") .
7188 " | " .
7189 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7190 "raw") .
7191 " | " .
7192 $cgi->a({-href => href(action=>"blob",
7193 hash_base=>"HEAD", file_name=>$file_name)},
7194 "HEAD");
7195 } else {
7196 $formats_nav .=
7197 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7198 "raw");
7200 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7201 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7202 } else {
7203 print "<div class=\"page_nav\">\n" .
7204 "<br/><br/></div>\n" .
7205 "<div class=\"title\">".esc_html($hash)."</div>\n";
7207 git_print_page_path($file_name, "blob", $hash_base);
7208 print "<div class=\"page_body\">\n";
7209 if ($mimetype =~ m!^image/!) {
7210 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7211 if ($file_name) {
7212 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7214 print qq! src="! .
7215 href(action=>"blob_plain", hash=>$hash,
7216 hash_base=>$hash_base, file_name=>$file_name) .
7217 qq!" />\n!;
7218 } else {
7219 my $nr;
7220 while (my $line = <$fd>) {
7221 chomp $line;
7222 $nr++;
7223 $line = untabify($line);
7224 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7225 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7226 $highlight ? sanitize($line) : esc_html($line, -nbsp=>1);
7229 close $fd
7230 or print "Reading blob failed.\n";
7231 print "</div>";
7232 git_footer_html();
7235 sub git_tree {
7236 if (!defined $hash_base) {
7237 $hash_base = "HEAD";
7239 if (!defined $hash) {
7240 if (defined $file_name) {
7241 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7242 } else {
7243 $hash = $hash_base;
7246 die_error(404, "No such tree") unless defined($hash);
7248 my $show_sizes = gitweb_check_feature('show-sizes');
7249 my $have_blame = gitweb_check_feature('blame');
7251 my @entries = ();
7253 local $/ = "\0";
7254 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7255 ($show_sizes ? '-l' : ()), @extra_options, $hash
7256 or die_error(500, "Open git-ls-tree failed");
7257 @entries = map { chomp; $_ } <$fd>;
7258 close $fd
7259 or die_error(404, "Reading tree failed");
7262 my $refs = git_get_references();
7263 my $ref = format_ref_marker($refs, $hash_base);
7264 git_header_html();
7265 my $basedir = '';
7266 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7267 my @views_nav = ();
7268 if (defined $file_name) {
7269 push @views_nav,
7270 $cgi->a({-href => href(action=>"history", -replay=>1)},
7271 "history"),
7272 $cgi->a({-href => href(action=>"tree",
7273 hash_base=>"HEAD", file_name=>$file_name)},
7274 "HEAD"),
7276 my $snapshot_links = format_snapshot_links($hash);
7277 if (defined $snapshot_links) {
7278 # FIXME: Should be available when we have no hash base as well.
7279 push @views_nav, $snapshot_links;
7281 git_print_page_nav('tree','', $hash_base, undef, undef,
7282 join(' | ', @views_nav));
7283 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7284 } else {
7285 undef $hash_base;
7286 print "<div class=\"page_nav\">\n";
7287 print "<br/><br/></div>\n";
7288 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7290 if (defined $file_name) {
7291 $basedir = $file_name;
7292 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7293 $basedir .= '/';
7295 git_print_page_path($file_name, 'tree', $hash_base);
7297 print "<div class=\"page_body\">\n";
7298 print "<table class=\"tree\">\n";
7299 my $alternate = 1;
7300 # '..' (top directory) link if possible
7301 if (defined $hash_base &&
7302 defined $file_name && $file_name =~ m![^/]+$!) {
7303 if ($alternate) {
7304 print "<tr class=\"dark\">\n";
7305 } else {
7306 print "<tr class=\"light\">\n";
7308 $alternate ^= 1;
7310 my $up = $file_name;
7311 $up =~ s!/?[^/]+$!!;
7312 undef $up unless $up;
7313 # based on git_print_tree_entry
7314 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7315 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7316 print '<td class="list">';
7317 print $cgi->a({-href => href(action=>"tree",
7318 hash_base=>$hash_base,
7319 file_name=>$up)},
7320 "..");
7321 print "</td>\n";
7322 print "<td class=\"link\"></td>\n";
7324 print "</tr>\n";
7326 foreach my $line (@entries) {
7327 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7329 if ($alternate) {
7330 print "<tr class=\"dark\">\n";
7331 } else {
7332 print "<tr class=\"light\">\n";
7334 $alternate ^= 1;
7336 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7338 print "</tr>\n";
7340 print "</table>\n" .
7341 "</div>";
7342 git_footer_html();
7345 sub sanitize_for_filename {
7346 my $name = shift;
7348 $name =~ s!/!-!g;
7349 $name =~ s/[^[:alnum:]_.-]//g;
7351 return $name;
7354 sub snapshot_name {
7355 my ($project, $hash) = @_;
7357 # path/to/project.git -> project
7358 # path/to/project/.git -> project
7359 my $name = to_utf8($project);
7360 $name =~ s,([^/])/*\.git$,$1,;
7361 $name = sanitize_for_filename(basename($name));
7363 my $ver = $hash;
7364 if ($hash =~ /^[0-9a-fA-F]+$/) {
7365 # shorten SHA-1 hash
7366 my $full_hash = git_get_full_hash($project, $hash);
7367 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7368 $ver = git_get_short_hash($project, $hash);
7370 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7371 # tags don't need shortened SHA-1 hash
7372 $ver = $1;
7373 } else {
7374 # branches and other need shortened SHA-1 hash
7375 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7376 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7377 my $ref_dir = (defined $1) ? $1 : '';
7378 $ver = $2;
7380 $ref_dir = sanitize_for_filename($ref_dir);
7381 # for refs neither in heads nor remotes we want to
7382 # add a ref dir to archive name
7383 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7384 $ver = $ref_dir . '-' . $ver;
7387 $ver .= '-' . git_get_short_hash($project, $hash);
7389 # special case of sanitization for filename - we change
7390 # slashes to dots instead of dashes
7391 # in case of hierarchical branch names
7392 $ver =~ s!/!.!g;
7393 $ver =~ s/[^[:alnum:]_.-]//g;
7395 # name = project-version_string
7396 $name = "$name-$ver";
7398 return wantarray ? ($name, $name) : $name;
7401 sub exit_if_unmodified_since {
7402 my ($latest_epoch) = @_;
7403 our $cgi;
7405 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7406 if (defined $if_modified) {
7407 my $since;
7408 if (eval { require HTTP::Date; 1; }) {
7409 $since = HTTP::Date::str2time($if_modified);
7410 } elsif (eval { require Time::ParseDate; 1; }) {
7411 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7413 if (defined $since && $latest_epoch <= $since) {
7414 my %latest_date = parse_date($latest_epoch);
7415 print $cgi->header(
7416 -last_modified => $latest_date{'rfc2822'},
7417 -status => '304 Not Modified');
7418 goto DONE_GITWEB;
7423 sub git_snapshot {
7424 my $format = $input_params{'snapshot_format'};
7425 if (!@snapshot_fmts) {
7426 die_error(403, "Snapshots not allowed");
7428 # default to first supported snapshot format
7429 $format ||= $snapshot_fmts[0];
7430 if ($format !~ m/^[a-z0-9]+$/) {
7431 die_error(400, "Invalid snapshot format parameter");
7432 } elsif (!exists($known_snapshot_formats{$format})) {
7433 die_error(400, "Unknown snapshot format");
7434 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7435 die_error(403, "Snapshot format not allowed");
7436 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7437 die_error(403, "Unsupported snapshot format");
7440 my $type = git_get_type("$hash^{}");
7441 if (!$type) {
7442 die_error(404, 'Object does not exist');
7443 } elsif ($type eq 'blob') {
7444 die_error(400, 'Object is not a tree-ish');
7447 my ($name, $prefix) = snapshot_name($project, $hash);
7448 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7450 my %co = parse_commit($hash);
7451 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7453 my $cmd = quote_command(
7454 git_cmd(), 'archive',
7455 "--format=$known_snapshot_formats{$format}{'format'}",
7456 "--prefix=$prefix/", $hash);
7457 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7458 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7461 $filename =~ s/(["\\])/\\$1/g;
7462 my %latest_date;
7463 if (%co) {
7464 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7467 print $cgi->header(
7468 -type => $known_snapshot_formats{$format}{'type'},
7469 -content_disposition => 'inline; filename="' . $filename . '"',
7470 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7471 -status => '200 OK');
7473 open my $fd, "-|", $cmd
7474 or die_error(500, "Execute git-archive failed");
7475 binmode STDOUT, ':raw';
7476 print <$fd>;
7477 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7478 close $fd;
7481 sub git_log_generic {
7482 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7484 my $head = git_get_head_hash($project);
7485 if (!defined $base) {
7486 $base = $head;
7488 if (!defined $page) {
7489 $page = 0;
7491 my $refs = git_get_references();
7493 my $commit_hash = $base;
7494 if (defined $parent) {
7495 $commit_hash = "$parent..$base";
7497 my @commitlist =
7498 parse_commits($commit_hash, 101, (100 * $page),
7499 defined $file_name ? ($file_name, "--full-history") : ());
7501 my $ftype;
7502 if (!defined $file_hash && defined $file_name) {
7503 # some commits could have deleted file in question,
7504 # and not have it in tree, but one of them has to have it
7505 for (my $i = 0; $i < @commitlist; $i++) {
7506 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7507 last if defined $file_hash;
7510 if (defined $file_hash) {
7511 $ftype = git_get_type($file_hash);
7513 if (defined $file_name && !defined $ftype) {
7514 die_error(500, "Unknown type of object");
7516 my %co;
7517 if (defined $file_name) {
7518 %co = parse_commit($base)
7519 or die_error(404, "Unknown commit object");
7523 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7524 my $next_link = '';
7525 if ($#commitlist >= 100) {
7526 $next_link =
7527 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7528 -accesskey => "n", -title => "Alt-n"}, "next");
7530 my $patch_max = gitweb_get_feature('patches');
7531 if ($patch_max && !defined $file_name) {
7532 if ($patch_max < 0 || @commitlist <= $patch_max) {
7533 $paging_nav .= " &sdot; " .
7534 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7535 "patches");
7539 git_header_html();
7540 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7541 if (defined $file_name) {
7542 git_print_header_div('commit', esc_html($co{'title'}), $base);
7543 } else {
7544 git_print_header_div('summary', $project)
7546 git_print_page_path($file_name, $ftype, $hash_base)
7547 if (defined $file_name);
7549 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7550 $file_name, $file_hash, $ftype);
7552 git_footer_html();
7555 sub git_log {
7556 git_log_generic('log', \&git_log_body,
7557 $hash, $hash_parent);
7560 sub git_commit {
7561 $hash ||= $hash_base || "HEAD";
7562 my %co = parse_commit($hash)
7563 or die_error(404, "Unknown commit object");
7565 my $parent = $co{'parent'};
7566 my $parents = $co{'parents'}; # listref
7568 # we need to prepare $formats_nav before any parameter munging
7569 my $formats_nav;
7570 if (!defined $parent) {
7571 # --root commitdiff
7572 $formats_nav .= '(initial)';
7573 } elsif (@$parents == 1) {
7574 # single parent commit
7575 $formats_nav .=
7576 '(parent: ' .
7577 $cgi->a({-href => href(action=>"commit",
7578 hash=>$parent)},
7579 esc_html(substr($parent, 0, 7))) .
7580 ')';
7581 } else {
7582 # merge commit
7583 $formats_nav .=
7584 '(merge: ' .
7585 join(' ', map {
7586 $cgi->a({-href => href(action=>"commit",
7587 hash=>$_)},
7588 esc_html(substr($_, 0, 7)));
7589 } @$parents ) .
7590 ')';
7592 if (gitweb_check_feature('patches') && @$parents <= 1) {
7593 $formats_nav .= " | " .
7594 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7595 "patch");
7598 if (!defined $parent) {
7599 $parent = "--root";
7601 my @difftree;
7602 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7603 @diff_opts,
7604 (@$parents <= 1 ? $parent : '-c'),
7605 $hash, "--"
7606 or die_error(500, "Open git-diff-tree failed");
7607 @difftree = map { chomp; $_ } <$fd>;
7608 close $fd or die_error(404, "Reading git-diff-tree failed");
7610 # non-textual hash id's can be cached
7611 my $expires;
7612 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7613 $expires = "+1d";
7615 my $refs = git_get_references();
7616 my $ref = format_ref_marker($refs, $co{'id'});
7618 git_header_html(undef, $expires);
7619 git_print_page_nav('commit', '',
7620 $hash, $co{'tree'}, $hash,
7621 $formats_nav);
7623 if (defined $co{'parent'}) {
7624 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7625 } else {
7626 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7628 print "<div class=\"title_text\">\n" .
7629 "<table class=\"object_header\">\n";
7630 git_print_authorship_rows(\%co);
7631 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7632 print "<tr>" .
7633 "<td>tree</td>" .
7634 "<td class=\"sha1\">" .
7635 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7636 class => "list"}, $co{'tree'}) .
7637 "</td>" .
7638 "<td class=\"link\">" .
7639 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7640 "tree");
7641 my $snapshot_links = format_snapshot_links($hash);
7642 if (defined $snapshot_links) {
7643 print " | " . $snapshot_links;
7645 print "</td>" .
7646 "</tr>\n";
7648 foreach my $par (@$parents) {
7649 print "<tr>" .
7650 "<td>parent</td>" .
7651 "<td class=\"sha1\">" .
7652 $cgi->a({-href => href(action=>"commit", hash=>$par),
7653 class => "list"}, $par) .
7654 "</td>" .
7655 "<td class=\"link\">" .
7656 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7657 " | " .
7658 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7659 "</td>" .
7660 "</tr>\n";
7662 print "</table>".
7663 "</div>\n";
7665 print "<div class=\"page_body\">\n";
7666 git_print_log($co{'comment'});
7667 print "</div>\n";
7669 git_difftree_body(\@difftree, $hash, @$parents);
7671 git_footer_html();
7674 sub git_object {
7675 # object is defined by:
7676 # - hash or hash_base alone
7677 # - hash_base and file_name
7678 my $type;
7680 # - hash or hash_base alone
7681 if ($hash || ($hash_base && !defined $file_name)) {
7682 my $object_id = $hash || $hash_base;
7684 open my $fd, "-|", quote_command(
7685 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7686 or die_error(404, "Object does not exist");
7687 $type = <$fd>;
7688 defined $type && chomp $type;
7689 close $fd
7690 or die_error(404, "Object does not exist");
7692 # - hash_base and file_name
7693 } elsif ($hash_base && defined $file_name) {
7694 $file_name =~ s,/+$,,;
7696 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7697 or die_error(404, "Base object does not exist");
7699 # here errors should not happen
7700 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7701 or die_error(500, "Open git-ls-tree failed");
7702 my $line = <$fd>;
7703 close $fd;
7705 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7706 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7707 die_error(404, "File or directory for given base does not exist");
7709 $type = $2;
7710 $hash = $3;
7711 } else {
7712 die_error(400, "Not enough information to find object");
7715 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7716 hash=>$hash, hash_base=>$hash_base,
7717 file_name=>$file_name),
7718 -status => '302 Found');
7721 sub git_blobdiff {
7722 my $format = shift || 'html';
7723 my $diff_style = $input_params{'diff_style'} || 'inline';
7725 my $fd;
7726 my @difftree;
7727 my %diffinfo;
7728 my $expires;
7730 # preparing $fd and %diffinfo for git_patchset_body
7731 # new style URI
7732 if (defined $hash_base && defined $hash_parent_base) {
7733 if (defined $file_name) {
7734 # read raw output
7735 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7736 $hash_parent_base, $hash_base,
7737 "--", (defined $file_parent ? $file_parent : ()), $file_name
7738 or die_error(500, "Open git-diff-tree failed");
7739 @difftree = map { chomp; $_ } <$fd>;
7740 close $fd
7741 or die_error(404, "Reading git-diff-tree failed");
7742 @difftree
7743 or die_error(404, "Blob diff not found");
7745 } elsif (defined $hash &&
7746 $hash =~ /[0-9a-fA-F]{40}/) {
7747 # try to find filename from $hash
7749 # read filtered raw output
7750 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7751 $hash_parent_base, $hash_base, "--"
7752 or die_error(500, "Open git-diff-tree failed");
7753 @difftree =
7754 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7755 # $hash == to_id
7756 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7757 map { chomp; $_ } <$fd>;
7758 close $fd
7759 or die_error(404, "Reading git-diff-tree failed");
7760 @difftree
7761 or die_error(404, "Blob diff not found");
7763 } else {
7764 die_error(400, "Missing one of the blob diff parameters");
7767 if (@difftree > 1) {
7768 die_error(400, "Ambiguous blob diff specification");
7771 %diffinfo = parse_difftree_raw_line($difftree[0]);
7772 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7773 $file_name ||= $diffinfo{'to_file'};
7775 $hash_parent ||= $diffinfo{'from_id'};
7776 $hash ||= $diffinfo{'to_id'};
7778 # non-textual hash id's can be cached
7779 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7780 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7781 $expires = '+1d';
7784 # open patch output
7785 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7786 '-p', ($format eq 'html' ? "--full-index" : ()),
7787 $hash_parent_base, $hash_base,
7788 "--", (defined $file_parent ? $file_parent : ()), $file_name
7789 or die_error(500, "Open git-diff-tree failed");
7792 # old/legacy style URI -- not generated anymore since 1.4.3.
7793 if (!%diffinfo) {
7794 die_error('404 Not Found', "Missing one of the blob diff parameters")
7797 # header
7798 if ($format eq 'html') {
7799 my $formats_nav =
7800 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7801 "raw");
7802 $formats_nav .= diff_style_nav($diff_style);
7803 git_header_html(undef, $expires);
7804 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7805 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7806 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7807 } else {
7808 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7809 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7811 if (defined $file_name) {
7812 git_print_page_path($file_name, "blob", $hash_base);
7813 } else {
7814 print "<div class=\"page_path\"></div>\n";
7817 } elsif ($format eq 'plain') {
7818 print $cgi->header(
7819 -type => 'text/plain',
7820 -charset => 'utf-8',
7821 -expires => $expires,
7822 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7824 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7826 } else {
7827 die_error(400, "Unknown blobdiff format");
7830 # patch
7831 if ($format eq 'html') {
7832 print "<div class=\"page_body\">\n";
7834 git_patchset_body($fd, $diff_style,
7835 [ \%diffinfo ], $hash_base, $hash_parent_base);
7836 close $fd;
7838 print "</div>\n"; # class="page_body"
7839 git_footer_html();
7841 } else {
7842 while (my $line = <$fd>) {
7843 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7844 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7846 print $line;
7848 last if $line =~ m!^\+\+\+!;
7850 local $/ = undef;
7851 print <$fd>;
7852 close $fd;
7856 sub git_blobdiff_plain {
7857 git_blobdiff('plain');
7860 # assumes that it is added as later part of already existing navigation,
7861 # so it returns "| foo | bar" rather than just "foo | bar"
7862 sub diff_style_nav {
7863 my ($diff_style, $is_combined) = @_;
7864 $diff_style ||= 'inline';
7866 return "" if ($is_combined);
7868 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7869 my %styles = @styles;
7870 @styles =
7871 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7873 return join '',
7874 map { " | ".$_ }
7875 map {
7876 $_ eq $diff_style ? $styles{$_} :
7877 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7878 } @styles;
7881 sub git_commitdiff {
7882 my %params = @_;
7883 my $format = $params{-format} || 'html';
7884 my $diff_style = $input_params{'diff_style'} || 'inline';
7886 my ($patch_max) = gitweb_get_feature('patches');
7887 if ($format eq 'patch') {
7888 die_error(403, "Patch view not allowed") unless $patch_max;
7891 $hash ||= $hash_base || "HEAD";
7892 my %co = parse_commit($hash)
7893 or die_error(404, "Unknown commit object");
7895 # choose format for commitdiff for merge
7896 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7897 $hash_parent = '--cc';
7899 # we need to prepare $formats_nav before almost any parameter munging
7900 my $formats_nav;
7901 if ($format eq 'html') {
7902 $formats_nav =
7903 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7904 "raw");
7905 if ($patch_max && @{$co{'parents'}} <= 1) {
7906 $formats_nav .= " | " .
7907 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7908 "patch");
7910 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7912 if (defined $hash_parent &&
7913 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7914 # commitdiff with two commits given
7915 my $hash_parent_short = $hash_parent;
7916 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7917 $hash_parent_short = substr($hash_parent, 0, 7);
7919 $formats_nav .=
7920 ' (from';
7921 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7922 if ($co{'parents'}[$i] eq $hash_parent) {
7923 $formats_nav .= ' parent ' . ($i+1);
7924 last;
7927 $formats_nav .= ': ' .
7928 $cgi->a({-href => href(-replay=>1,
7929 hash=>$hash_parent, hash_base=>undef)},
7930 esc_html($hash_parent_short)) .
7931 ')';
7932 } elsif (!$co{'parent'}) {
7933 # --root commitdiff
7934 $formats_nav .= ' (initial)';
7935 } elsif (scalar @{$co{'parents'}} == 1) {
7936 # single parent commit
7937 $formats_nav .=
7938 ' (parent: ' .
7939 $cgi->a({-href => href(-replay=>1,
7940 hash=>$co{'parent'}, hash_base=>undef)},
7941 esc_html(substr($co{'parent'}, 0, 7))) .
7942 ')';
7943 } else {
7944 # merge commit
7945 if ($hash_parent eq '--cc') {
7946 $formats_nav .= ' | ' .
7947 $cgi->a({-href => href(-replay=>1,
7948 hash=>$hash, hash_parent=>'-c')},
7949 'combined');
7950 } else { # $hash_parent eq '-c'
7951 $formats_nav .= ' | ' .
7952 $cgi->a({-href => href(-replay=>1,
7953 hash=>$hash, hash_parent=>'--cc')},
7954 'compact');
7956 $formats_nav .=
7957 ' (merge: ' .
7958 join(' ', map {
7959 $cgi->a({-href => href(-replay=>1,
7960 hash=>$_, hash_base=>undef)},
7961 esc_html(substr($_, 0, 7)));
7962 } @{$co{'parents'}} ) .
7963 ')';
7967 my $hash_parent_param = $hash_parent;
7968 if (!defined $hash_parent_param) {
7969 # --cc for multiple parents, --root for parentless
7970 $hash_parent_param =
7971 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7974 # read commitdiff
7975 my $fd;
7976 my @difftree;
7977 if ($format eq 'html') {
7978 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7979 "--no-commit-id", "--patch-with-raw", "--full-index",
7980 $hash_parent_param, $hash, "--"
7981 or die_error(500, "Open git-diff-tree failed");
7983 while (my $line = <$fd>) {
7984 chomp $line;
7985 # empty line ends raw part of diff-tree output
7986 last unless $line;
7987 push @difftree, scalar parse_difftree_raw_line($line);
7990 } elsif ($format eq 'plain') {
7991 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7992 '-p', $hash_parent_param, $hash, "--"
7993 or die_error(500, "Open git-diff-tree failed");
7994 } elsif ($format eq 'patch') {
7995 # For commit ranges, we limit the output to the number of
7996 # patches specified in the 'patches' feature.
7997 # For single commits, we limit the output to a single patch,
7998 # diverging from the git-format-patch default.
7999 my @commit_spec = ();
8000 if ($hash_parent) {
8001 if ($patch_max > 0) {
8002 push @commit_spec, "-$patch_max";
8004 push @commit_spec, '-n', "$hash_parent..$hash";
8005 } else {
8006 if ($params{-single}) {
8007 push @commit_spec, '-1';
8008 } else {
8009 if ($patch_max > 0) {
8010 push @commit_spec, "-$patch_max";
8012 push @commit_spec, "-n";
8014 push @commit_spec, '--root', $hash;
8016 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
8017 '--encoding=utf8', '--stdout', @commit_spec
8018 or die_error(500, "Open git-format-patch failed");
8019 } else {
8020 die_error(400, "Unknown commitdiff format");
8023 # non-textual hash id's can be cached
8024 my $expires;
8025 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8026 $expires = "+1d";
8029 # write commit message
8030 if ($format eq 'html') {
8031 my $refs = git_get_references();
8032 my $ref = format_ref_marker($refs, $co{'id'});
8034 git_header_html(undef, $expires);
8035 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
8036 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
8037 print "<div class=\"title_text\">\n" .
8038 "<table class=\"object_header\">\n";
8039 git_print_authorship_rows(\%co);
8040 print "</table>".
8041 "</div>\n";
8042 print "<div class=\"page_body\">\n";
8043 if (@{$co{'comment'}} > 1) {
8044 print "<div class=\"log\">\n";
8045 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
8046 print "</div>\n"; # class="log"
8049 } elsif ($format eq 'plain') {
8050 my $refs = git_get_references("tags");
8051 my $tagname = git_get_rev_name_tags($hash);
8052 my $filename = basename($project) . "-$hash.patch";
8054 print $cgi->header(
8055 -type => 'text/plain',
8056 -charset => 'utf-8',
8057 -expires => $expires,
8058 -content_disposition => 'inline; filename="' . "$filename" . '"');
8059 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8060 print "From: " . to_utf8($co{'author'}) . "\n";
8061 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8062 print "Subject: " . to_utf8($co{'title'}) . "\n";
8064 print "X-Git-Tag: $tagname\n" if $tagname;
8065 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8067 foreach my $line (@{$co{'comment'}}) {
8068 print to_utf8($line) . "\n";
8070 print "---\n\n";
8071 } elsif ($format eq 'patch') {
8072 my $filename = basename($project) . "-$hash.patch";
8074 print $cgi->header(
8075 -type => 'text/plain',
8076 -charset => 'utf-8',
8077 -expires => $expires,
8078 -content_disposition => 'inline; filename="' . "$filename" . '"');
8081 # write patch
8082 if ($format eq 'html') {
8083 my $use_parents = !defined $hash_parent ||
8084 $hash_parent eq '-c' || $hash_parent eq '--cc';
8085 git_difftree_body(\@difftree, $hash,
8086 $use_parents ? @{$co{'parents'}} : $hash_parent);
8087 print "<br/>\n";
8089 git_patchset_body($fd, $diff_style,
8090 \@difftree, $hash,
8091 $use_parents ? @{$co{'parents'}} : $hash_parent);
8092 close $fd;
8093 print "</div>\n"; # class="page_body"
8094 git_footer_html();
8096 } elsif ($format eq 'plain') {
8097 local $/ = undef;
8098 print <$fd>;
8099 close $fd
8100 or print "Reading git-diff-tree failed\n";
8101 } elsif ($format eq 'patch') {
8102 local $/ = undef;
8103 print <$fd>;
8104 close $fd
8105 or print "Reading git-format-patch failed\n";
8109 sub git_commitdiff_plain {
8110 git_commitdiff(-format => 'plain');
8113 # format-patch-style patches
8114 sub git_patch {
8115 git_commitdiff(-format => 'patch', -single => 1);
8118 sub git_patches {
8119 git_commitdiff(-format => 'patch');
8122 sub git_history {
8123 git_log_generic('history', \&git_history_body,
8124 $hash_base, $hash_parent_base,
8125 $file_name, $hash);
8128 sub git_search {
8129 $searchtype ||= 'commit';
8131 # check if appropriate features are enabled
8132 gitweb_check_feature('search')
8133 or die_error(403, "Search is disabled");
8134 if ($searchtype eq 'pickaxe') {
8135 # pickaxe may take all resources of your box and run for several minutes
8136 # with every query - so decide by yourself how public you make this feature
8137 gitweb_check_feature('pickaxe')
8138 or die_error(403, "Pickaxe search is disabled");
8140 if ($searchtype eq 'grep') {
8141 # grep search might be potentially CPU-intensive, too
8142 gitweb_check_feature('grep')
8143 or die_error(403, "Grep search is disabled");
8146 if (!defined $searchtext) {
8147 die_error(400, "Text field is empty");
8149 if (!defined $hash) {
8150 $hash = git_get_head_hash($project);
8152 my %co = parse_commit($hash);
8153 if (!%co) {
8154 die_error(404, "Unknown commit object");
8156 if (!defined $page) {
8157 $page = 0;
8160 if ($searchtype eq 'commit' ||
8161 $searchtype eq 'author' ||
8162 $searchtype eq 'committer') {
8163 git_search_message(%co);
8164 } elsif ($searchtype eq 'pickaxe') {
8165 git_search_changes(%co);
8166 } elsif ($searchtype eq 'grep') {
8167 git_search_files(%co);
8168 } else {
8169 die_error(400, "Unknown search type");
8173 sub git_search_help {
8174 git_header_html();
8175 git_print_page_nav('','', $hash,$hash,$hash);
8176 print <<EOT;
8177 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8178 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8179 the pattern entered is recognized as the POSIX extended
8180 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8181 insensitive).</p>
8182 <dl>
8183 <dt><b>commit</b></dt>
8184 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8186 my $have_grep = gitweb_check_feature('grep');
8187 if ($have_grep) {
8188 print <<EOT;
8189 <dt><b>grep</b></dt>
8190 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8191 a different one) are searched for the given pattern. On large trees, this search can take
8192 a while and put some strain on the server, so please use it with some consideration. Note that
8193 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8194 case-sensitive.</dd>
8197 print <<EOT;
8198 <dt><b>author</b></dt>
8199 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8200 <dt><b>committer</b></dt>
8201 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8203 my $have_pickaxe = gitweb_check_feature('pickaxe');
8204 if ($have_pickaxe) {
8205 print <<EOT;
8206 <dt><b>pickaxe</b></dt>
8207 <dd>All commits that caused the string to appear or disappear from any file (changes that
8208 added, removed or "modified" the string) will be listed. This search can take a while and
8209 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8210 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8213 print "</dl>\n";
8214 git_footer_html();
8217 sub git_shortlog {
8218 git_log_generic('shortlog', \&git_shortlog_body,
8219 $hash, $hash_parent);
8222 ## ......................................................................
8223 ## feeds (RSS, Atom; OPML)
8225 sub git_feed {
8226 my $format = shift || 'atom';
8227 my $have_blame = gitweb_check_feature('blame');
8229 # Atom: http://www.atomenabled.org/developers/syndication/
8230 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8231 if ($format ne 'rss' && $format ne 'atom') {
8232 die_error(400, "Unknown web feed format");
8235 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8236 my $head = $hash || 'HEAD';
8237 my @commitlist = parse_commits($head, 150, 0, $file_name);
8239 my %latest_commit;
8240 my %latest_date;
8241 my $content_type = "application/$format+xml";
8242 if (defined $cgi->http('HTTP_ACCEPT') &&
8243 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8244 # browser (feed reader) prefers text/xml
8245 $content_type = 'text/xml';
8247 if (defined($commitlist[0])) {
8248 %latest_commit = %{$commitlist[0]};
8249 my $latest_epoch = $latest_commit{'committer_epoch'};
8250 exit_if_unmodified_since($latest_epoch);
8251 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8253 print $cgi->header(
8254 -type => $content_type,
8255 -charset => 'utf-8',
8256 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8257 -status => '200 OK');
8259 # Optimization: skip generating the body if client asks only
8260 # for Last-Modified date.
8261 return if ($cgi->request_method() eq 'HEAD');
8263 # header variables
8264 my $title = "$site_name - $project/$action";
8265 my $feed_type = 'log';
8266 if (defined $hash) {
8267 $title .= " - '$hash'";
8268 $feed_type = 'branch log';
8269 if (defined $file_name) {
8270 $title .= " :: $file_name";
8271 $feed_type = 'history';
8273 } elsif (defined $file_name) {
8274 $title .= " - $file_name";
8275 $feed_type = 'history';
8277 $title .= " $feed_type";
8278 $title = esc_html($title);
8279 my $descr = git_get_project_description($project);
8280 if (defined $descr) {
8281 $descr = esc_html($descr);
8282 } else {
8283 $descr = "$project " .
8284 ($format eq 'rss' ? 'RSS' : 'Atom') .
8285 " feed";
8287 my $owner = git_get_project_owner($project);
8288 $owner = esc_html($owner);
8290 #header
8291 my $alt_url;
8292 if (defined $file_name) {
8293 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8294 } elsif (defined $hash) {
8295 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8296 } else {
8297 $alt_url = href(-full=>1, action=>"summary");
8299 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8300 if ($format eq 'rss') {
8301 print <<XML;
8302 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8303 <channel>
8305 print "<title>$title</title>\n" .
8306 "<link>$alt_url</link>\n" .
8307 "<description>$descr</description>\n" .
8308 "<language>en</language>\n" .
8309 # project owner is responsible for 'editorial' content
8310 "<managingEditor>$owner</managingEditor>\n";
8311 if (defined $logo || defined $favicon) {
8312 # prefer the logo to the favicon, since RSS
8313 # doesn't allow both
8314 my $img = esc_url($logo || $favicon);
8315 print "<image>\n" .
8316 "<url>$img</url>\n" .
8317 "<title>$title</title>\n" .
8318 "<link>$alt_url</link>\n" .
8319 "</image>\n";
8321 if (%latest_date) {
8322 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8323 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8325 print "<generator>gitweb v.$version/$git_version</generator>\n";
8326 } elsif ($format eq 'atom') {
8327 print <<XML;
8328 <feed xmlns="http://www.w3.org/2005/Atom">
8330 print "<title>$title</title>\n" .
8331 "<subtitle>$descr</subtitle>\n" .
8332 '<link rel="alternate" type="text/html" href="' .
8333 $alt_url . '" />' . "\n" .
8334 '<link rel="self" type="' . $content_type . '" href="' .
8335 $cgi->self_url() . '" />' . "\n" .
8336 "<id>" . href(-full=>1) . "</id>\n" .
8337 # use project owner for feed author
8338 '<author><name>'. email_obfuscate($owner) . '</name></author>\n';
8339 if (defined $favicon) {
8340 print "<icon>" . esc_url($favicon) . "</icon>\n";
8342 if (defined $logo) {
8343 # not twice as wide as tall: 72 x 27 pixels
8344 print "<logo>" . esc_url($logo) . "</logo>\n";
8346 if (! %latest_date) {
8347 # dummy date to keep the feed valid until commits trickle in:
8348 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8349 } else {
8350 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8352 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8355 # contents
8356 for (my $i = 0; $i <= $#commitlist; $i++) {
8357 my %co = %{$commitlist[$i]};
8358 my $commit = $co{'id'};
8359 # we read 150, we always show 30 and the ones more recent than 48 hours
8360 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8361 last;
8363 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8365 # get list of changed files
8366 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8367 $co{'parent'} || "--root",
8368 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8369 or next;
8370 my @difftree = map { chomp; $_ } <$fd>;
8371 close $fd
8372 or next;
8374 # print element (entry, item)
8375 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8376 if ($format eq 'rss') {
8377 print "<item>\n" .
8378 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8379 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8380 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8381 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8382 "<link>$co_url</link>\n" .
8383 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8384 "<content:encoded>" .
8385 "<![CDATA[\n";
8386 } elsif ($format eq 'atom') {
8387 print "<entry>\n" .
8388 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8389 "<updated>$cd{'iso-8601'}</updated>\n" .
8390 "<author>\n" .
8391 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8392 if ($co{'author_email'}) {
8393 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8395 print "</author>\n" .
8396 # use committer for contributor
8397 "<contributor>\n" .
8398 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8399 if ($co{'committer_email'}) {
8400 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8402 print "</contributor>\n" .
8403 "<published>$cd{'iso-8601'}</published>\n" .
8404 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8405 "<id>$co_url</id>\n" .
8406 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8407 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8409 my $comment = $co{'comment'};
8410 print "<pre>\n";
8411 foreach my $line (@$comment) {
8412 $line = esc_html($line);
8413 print "$line\n";
8415 print "</pre><ul>\n";
8416 foreach my $difftree_line (@difftree) {
8417 my %difftree = parse_difftree_raw_line($difftree_line);
8418 next if !$difftree{'from_id'};
8420 my $file = $difftree{'file'} || $difftree{'to_file'};
8422 print "<li>" .
8423 "[" .
8424 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8425 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8426 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8427 file_name=>$file, file_parent=>$difftree{'from_file'}),
8428 -title => "diff"}, 'D');
8429 if ($have_blame) {
8430 print $cgi->a({-href => href(-full=>1, action=>"blame",
8431 file_name=>$file, hash_base=>$commit),
8432 -title => "blame"}, 'B');
8434 # if this is not a feed of a file history
8435 if (!defined $file_name || $file_name ne $file) {
8436 print $cgi->a({-href => href(-full=>1, action=>"history",
8437 file_name=>$file, hash=>$commit),
8438 -title => "history"}, 'H');
8440 $file = esc_path($file);
8441 print "] ".
8442 "$file</li>\n";
8444 if ($format eq 'rss') {
8445 print "</ul>]]>\n" .
8446 "</content:encoded>\n" .
8447 "</item>\n";
8448 } elsif ($format eq 'atom') {
8449 print "</ul>\n</div>\n" .
8450 "</content>\n" .
8451 "</entry>\n";
8455 # end of feed
8456 if ($format eq 'rss') {
8457 print "</channel>\n</rss>\n";
8458 } elsif ($format eq 'atom') {
8459 print "</feed>\n";
8463 sub git_rss {
8464 git_feed('rss');
8467 sub git_atom {
8468 git_feed('atom');
8471 sub git_opml {
8472 my @list = git_get_projects_list($project_filter, $strict_export);
8473 if (!@list) {
8474 die_error(404, "No projects found");
8477 print $cgi->header(
8478 -type => 'text/xml',
8479 -charset => 'utf-8',
8480 -content_disposition => 'inline; filename="opml.xml"');
8482 my $title = esc_html($site_name);
8483 my $filter = " within subdirectory ";
8484 if (defined $project_filter) {
8485 $filter .= esc_html($project_filter);
8486 } else {
8487 $filter = "";
8489 print <<XML;
8490 <?xml version="1.0" encoding="utf-8"?>
8491 <opml version="1.0">
8492 <head>
8493 <title>$title OPML Export$filter</title>
8494 </head>
8495 <body>
8496 <outline text="git RSS feeds">
8499 foreach my $pr (@list) {
8500 my %proj = %$pr;
8501 my $head = git_get_head_hash($proj{'path'});
8502 if (!defined $head) {
8503 next;
8505 $git_dir = "$projectroot/$proj{'path'}";
8506 my %co = parse_commit($head);
8507 if (!%co) {
8508 next;
8511 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8512 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8513 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8514 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8516 print <<XML;
8517 </outline>
8518 </body>
8519 </opml>