gitweb: include full fork information in cache
[git/gitweb.git] / gitweb / gitweb.perl
blob47ad5124f9cb50d956f1da87c9ffc9264b699d71
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 use constant GITWEB_CACHE_FORMAT => "Gitweb Cache Format 1";
22 binmode STDOUT, ':utf8';
24 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
25 eval 'sub CGI::multi_param { CGI::param(@_) }'
28 our $t0 = [ gettimeofday() ];
29 our $number_of_git_cmds = 0;
31 BEGIN {
32 CGI->compile() if $ENV{'MOD_PERL'};
35 our $version = "++GIT_VERSION++";
37 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
38 sub evaluate_uri {
39 our $cgi;
41 our $my_url = $cgi->url();
42 our $my_uri = $cgi->url(-absolute => 1);
44 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
45 # needed and used only for URLs with nonempty PATH_INFO
46 our $base_url = $my_url;
48 # When the script is used as DirectoryIndex, the URL does not contain the name
49 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
50 # have to do it ourselves. We make $path_info global because it's also used
51 # later on.
53 # Another issue with the script being the DirectoryIndex is that the resulting
54 # $my_url data is not the full script URL: this is good, because we want
55 # generated links to keep implying the script name if it wasn't explicitly
56 # indicated in the URL we're handling, but it means that $my_url cannot be used
57 # as base URL.
58 # Therefore, if we needed to strip PATH_INFO, then we know that we have
59 # to build the base URL ourselves:
60 our $path_info = decode_utf8($ENV{"PATH_INFO"});
61 if ($path_info) {
62 # $path_info has already been URL-decoded by the web server, but
63 # $my_url and $my_uri have not. URL-decode them so we can properly
64 # strip $path_info.
65 $my_url = unescape($my_url);
66 $my_uri = unescape($my_uri);
67 if ($my_url =~ s,\Q$path_info\E$,, &&
68 $my_uri =~ s,\Q$path_info\E$,, &&
69 defined $ENV{'SCRIPT_NAME'}) {
70 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
74 # target of the home link on top of all pages
75 our $home_link = $my_uri || "/";
78 # core git executable to use
79 # this can just be "git" if your webserver has a sensible PATH
80 our $GIT = "++GIT_BINDIR++/git";
82 # absolute fs-path which will be prepended to the project path
83 #our $projectroot = "/pub/scm";
84 our $projectroot = "++GITWEB_PROJECTROOT++";
86 # fs traversing limit for getting project list
87 # the number is relative to the projectroot
88 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
90 # string of the home link on top of all pages
91 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
93 # extra breadcrumbs preceding the home link
94 our @extra_breadcrumbs = ();
96 # name of your site or organization to appear in page titles
97 # replace this with something more descriptive for clearer bookmarks
98 our $site_name = "++GITWEB_SITENAME++"
99 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
101 # html snippet to include in the <head> section of each page
102 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
103 # filename of html text to include at top of each page
104 our $site_header = "++GITWEB_SITE_HEADER++";
105 # html text to include at home page
106 our $home_text = "++GITWEB_HOMETEXT++";
107 # filename of html text to include at bottom of each page
108 our $site_footer = "++GITWEB_SITE_FOOTER++";
110 # URI of stylesheets
111 our @stylesheets = ("++GITWEB_CSS++");
112 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
113 our $stylesheet = undef;
114 # URI of GIT logo (72x27 size)
115 our $logo = "++GITWEB_LOGO++";
116 # URI of GIT favicon, assumed to be image/png type
117 our $favicon = "++GITWEB_FAVICON++";
118 # URI of gitweb.js (JavaScript code for gitweb)
119 our $javascript = "++GITWEB_JS++";
121 # URI and label (title) of GIT logo link
122 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
123 #our $logo_label = "git documentation";
124 our $logo_url = "http://git-scm.com/";
125 our $logo_label = "git homepage";
127 # source of projects list
128 our $projects_list = "++GITWEB_LIST++";
130 # the width (in characters) of the projects list "Description" column
131 our $projects_list_description_width = 25;
133 # group projects by category on the projects list
134 # (enabled if this variable evaluates to true)
135 our $projects_list_group_categories = 0;
137 # default category if none specified
138 # (leave the empty string for no category)
139 our $project_list_default_category = "";
141 # default order of projects list
142 # valid values are none, project, descr, owner, and age
143 our $default_projects_order = "project";
145 # show repository only if this file exists
146 # (only effective if this variable evaluates to true)
147 our $export_ok = "++GITWEB_EXPORT_OK++";
149 # don't generate age column on the projects list page
150 our $omit_age_column = 0;
152 # don't generate information about owners of repositories
153 our $omit_owner=0;
155 # show repository only if this subroutine returns true
156 # when given the path to the project, for example:
157 # sub { return -e "$_[0]/git-daemon-export-ok"; }
158 our $export_auth_hook = undef;
160 # only allow viewing of repositories also shown on the overview page
161 our $strict_export = "++GITWEB_STRICT_EXPORT++";
163 # list of git base URLs used for URL to where fetch project from,
164 # i.e. full URL is "$git_base_url/$project"
165 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
167 # default blob_plain mimetype and default charset for text/plain blob
168 our $default_blob_plain_mimetype = 'text/plain';
169 our $default_text_plain_charset = undef;
171 # file to use for guessing MIME types before trying /etc/mime.types
172 # (relative to the current git repository)
173 our $mimetypes_file = undef;
175 # assume this charset if line contains non-UTF-8 characters;
176 # it should be valid encoding (see Encoding::Supported(3pm) for list),
177 # for which encoding all byte sequences are valid, for example
178 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
179 # could be even 'utf-8' for the old behavior)
180 our $fallback_encoding = 'latin1';
182 # rename detection options for git-diff and git-diff-tree
183 # - default is '-M', with the cost proportional to
184 # (number of removed files) * (number of new files).
185 # - more costly is '-C' (which implies '-M'), with the cost proportional to
186 # (number of changed files + number of removed files) * (number of new files)
187 # - even more costly is '-C', '--find-copies-harder' with cost
188 # (number of files in the original tree) * (number of new files)
189 # - one might want to include '-B' option, e.g. '-B', '-M'
190 our @diff_opts = ('-M'); # taken from git_commit
192 # Disables features that would allow repository owners to inject script into
193 # the gitweb domain.
194 our $prevent_xss = 0;
196 # Path to the highlight executable to use (must be the one from
197 # http://www.andre-simon.de due to assumptions about parameters and output).
198 # Useful if highlight is not installed on your webserver's PATH.
199 # [Default: highlight]
200 our $highlight_bin = "++HIGHLIGHT_BIN++";
202 # Whether to include project list on the gitweb front page; 0 means yes,
203 # 1 means no list but show tag cloud if enabled (all projects still need
204 # to be scanned, unless the info is cached), 2 means no list and no tag cloud
205 # (very fast)
206 our $frontpage_no_project_list = 0;
208 # projects list cache for busy sites with many projects;
209 # if you set this to non-zero, it will be used as the cached
210 # index lifetime in minutes
212 # the cached list version is stored in $cache_dir/$cache_name and can
213 # be tweaked by other scripts running with the same uid as gitweb -
214 # use this ONLY at secure installations; only single gitweb project
215 # root per system is supported, unless you tweak configuration!
216 our $projlist_cache_lifetime = 0; # in minutes
217 # FHS compliant $cache_dir would be "/var/cache/gitweb"
218 our $cache_dir =
219 (defined $ENV{'TMPDIR'} ? $ENV{'TMPDIR'} : '/tmp').'/gitweb';
220 our $projlist_cache_name = 'gitweb.index.cache';
221 our $cache_grpshared = 0;
223 # information about snapshot formats that gitweb is capable of serving
224 our %known_snapshot_formats = (
225 # name => {
226 # 'display' => display name,
227 # 'type' => mime type,
228 # 'suffix' => filename suffix,
229 # 'format' => --format for git-archive,
230 # 'compressor' => [compressor command and arguments]
231 # (array reference, optional)
232 # 'disabled' => boolean (optional)}
234 'tgz' => {
235 'display' => 'tar.gz',
236 'type' => 'application/x-gzip',
237 'suffix' => '.tar.gz',
238 'format' => 'tar',
239 'compressor' => ['gzip', '-n']},
241 'tbz2' => {
242 'display' => 'tar.bz2',
243 'type' => 'application/x-bzip2',
244 'suffix' => '.tar.bz2',
245 'format' => 'tar',
246 'compressor' => ['bzip2']},
248 'txz' => {
249 'display' => 'tar.xz',
250 'type' => 'application/x-xz',
251 'suffix' => '.tar.xz',
252 'format' => 'tar',
253 'compressor' => ['xz'],
254 'disabled' => 1},
256 'zip' => {
257 'display' => 'zip',
258 'type' => 'application/x-zip',
259 'suffix' => '.zip',
260 'format' => 'zip'},
263 # Aliases so we understand old gitweb.snapshot values in repository
264 # configuration.
265 our %known_snapshot_format_aliases = (
266 'gzip' => 'tgz',
267 'bzip2' => 'tbz2',
268 'xz' => 'txz',
270 # backward compatibility: legacy gitweb config support
271 'x-gzip' => undef, 'gz' => undef,
272 'x-bzip2' => undef, 'bz2' => undef,
273 'x-zip' => undef, '' => undef,
276 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
277 # are changed, it may be appropriate to change these values too via
278 # $GITWEB_CONFIG.
279 our %avatar_size = (
280 'default' => 16,
281 'double' => 32
284 # Used to set the maximum load that we will still respond to gitweb queries.
285 # If server load exceed this value then return "503 server busy" error.
286 # If gitweb cannot determined server load, it is taken to be 0.
287 # Leave it undefined (or set to 'undef') to turn off load checking.
288 our $maxload = 300;
290 # configuration for 'highlight' (http://www.andre-simon.de/)
291 # match by basename
292 our %highlight_basename = (
293 #'Program' => 'py',
294 #'Library' => 'py',
295 'SConstruct' => 'py', # SCons equivalent of Makefile
296 'Makefile' => 'make',
298 # match by extension
299 our %highlight_ext = (
300 # main extensions, defining name of syntax;
301 # see files in /usr/share/highlight/langDefs/ directory
302 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
303 # alternate extensions, see /etc/highlight/filetypes.conf
304 (map { $_ => 'c' } qw(c h)),
305 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
306 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
307 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
308 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
309 (map { $_ => 'make'} qw(make mak mk)),
310 (map { $_ => 'xml' } qw(xml xhtml html htm)),
313 # You define site-wide feature defaults here; override them with
314 # $GITWEB_CONFIG as necessary.
315 our %feature = (
316 # feature => {
317 # 'sub' => feature-sub (subroutine),
318 # 'override' => allow-override (boolean),
319 # 'default' => [ default options...] (array reference)}
321 # if feature is overridable (it means that allow-override has true value),
322 # then feature-sub will be called with default options as parameters;
323 # return value of feature-sub indicates if to enable specified feature
325 # if there is no 'sub' key (no feature-sub), then feature cannot be
326 # overridden
328 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
329 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
330 # is enabled
332 # Enable the 'blame' blob view, showing the last commit that modified
333 # each line in the file. This can be very CPU-intensive.
335 # To enable system wide have in $GITWEB_CONFIG
336 # $feature{'blame'}{'default'} = [1];
337 # To have project specific config enable override in $GITWEB_CONFIG
338 # $feature{'blame'}{'override'} = 1;
339 # and in project config gitweb.blame = 0|1;
340 'blame' => {
341 'sub' => sub { feature_bool('blame', @_) },
342 'override' => 0,
343 'default' => [0]},
345 # Enable the 'snapshot' link, providing a compressed archive of any
346 # tree. This can potentially generate high traffic if you have large
347 # project.
349 # Value is a list of formats defined in %known_snapshot_formats that
350 # you wish to offer.
351 # To disable system wide have in $GITWEB_CONFIG
352 # $feature{'snapshot'}{'default'} = [];
353 # To have project specific config enable override in $GITWEB_CONFIG
354 # $feature{'snapshot'}{'override'} = 1;
355 # and in project config, a comma-separated list of formats or "none"
356 # to disable. Example: gitweb.snapshot = tbz2,zip;
357 'snapshot' => {
358 'sub' => \&feature_snapshot,
359 'override' => 0,
360 'default' => ['tgz']},
362 # Enable text search, which will list the commits which match author,
363 # committer or commit text to a given string. Enabled by default.
364 # Project specific override is not supported.
366 # Note that this controls all search features, which means that if
367 # it is disabled, then 'grep' and 'pickaxe' search would also be
368 # disabled.
369 'search' => {
370 'override' => 0,
371 'default' => [1]},
373 # Enable grep search, which will list the files in currently selected
374 # tree containing the given string. Enabled by default. This can be
375 # potentially CPU-intensive, of course.
376 # Note that you need to have 'search' feature enabled too.
378 # To enable system wide have in $GITWEB_CONFIG
379 # $feature{'grep'}{'default'} = [1];
380 # To have project specific config enable override in $GITWEB_CONFIG
381 # $feature{'grep'}{'override'} = 1;
382 # and in project config gitweb.grep = 0|1;
383 'grep' => {
384 'sub' => sub { feature_bool('grep', @_) },
385 'override' => 0,
386 'default' => [1]},
388 # Enable the pickaxe search, which will list the commits that modified
389 # a given string in a file. This can be practical and quite faster
390 # alternative to 'blame', but still potentially CPU-intensive.
391 # Note that you need to have 'search' feature enabled too.
393 # To enable system wide have in $GITWEB_CONFIG
394 # $feature{'pickaxe'}{'default'} = [1];
395 # To have project specific config enable override in $GITWEB_CONFIG
396 # $feature{'pickaxe'}{'override'} = 1;
397 # and in project config gitweb.pickaxe = 0|1;
398 'pickaxe' => {
399 'sub' => sub { feature_bool('pickaxe', @_) },
400 'override' => 0,
401 'default' => [1]},
403 # Enable showing size of blobs in a 'tree' view, in a separate
404 # column, similar to what 'ls -l' does. This cost a bit of IO.
406 # To disable system wide have in $GITWEB_CONFIG
407 # $feature{'show-sizes'}{'default'} = [0];
408 # To have project specific config enable override in $GITWEB_CONFIG
409 # $feature{'show-sizes'}{'override'} = 1;
410 # and in project config gitweb.showsizes = 0|1;
411 'show-sizes' => {
412 'sub' => sub { feature_bool('showsizes', @_) },
413 'override' => 0,
414 'default' => [1]},
416 # Make gitweb use an alternative format of the URLs which can be
417 # more readable and natural-looking: project name is embedded
418 # directly in the path and the query string contains other
419 # auxiliary information. All gitweb installations recognize
420 # URL in either format; this configures in which formats gitweb
421 # generates links.
423 # To enable system wide have in $GITWEB_CONFIG
424 # $feature{'pathinfo'}{'default'} = [1];
425 # Project specific override is not supported.
427 # Note that you will need to change the default location of CSS,
428 # favicon, logo and possibly other files to an absolute URL. Also,
429 # if gitweb.cgi serves as your indexfile, you will need to force
430 # $my_uri to contain the script name in your $GITWEB_CONFIG.
431 'pathinfo' => {
432 'override' => 0,
433 'default' => [0]},
435 # Make gitweb consider projects in project root subdirectories
436 # to be forks of existing projects. Given project $projname.git,
437 # projects matching $projname/*.git will not be shown in the main
438 # projects list, instead a '+' mark will be added to $projname
439 # there and a 'forks' view will be enabled for the project, listing
440 # all the forks. If project list is taken from a file, forks have
441 # to be listed after the main project.
443 # To enable system wide have in $GITWEB_CONFIG
444 # $feature{'forks'}{'default'} = [1];
445 # Project specific override is not supported.
446 'forks' => {
447 'override' => 0,
448 'default' => [0]},
450 # Insert custom links to the action bar of all project pages.
451 # This enables you mainly to link to third-party scripts integrating
452 # into gitweb; e.g. git-browser for graphical history representation
453 # or custom web-based repository administration interface.
455 # The 'default' value consists of a list of triplets in the form
456 # (label, link, position) where position is the label after which
457 # to insert the link and link is a format string where %n expands
458 # to the project name, %f to the project path within the filesystem,
459 # %h to the current hash (h gitweb parameter) and %b to the current
460 # hash base (hb gitweb parameter); %% expands to %.
462 # To enable system wide have in $GITWEB_CONFIG e.g.
463 # $feature{'actions'}{'default'} = [('graphiclog',
464 # '/git-browser/by-commit.html?r=%n', 'summary')];
465 # Project specific override is not supported.
466 'actions' => {
467 'override' => 0,
468 'default' => []},
470 # Allow gitweb scan project content tags of project repository,
471 # and display the popular Web 2.0-ish "tag cloud" near the projects
472 # list. Note that this is something COMPLETELY different from the
473 # normal Git tags.
475 # gitweb by itself can show existing tags, but it does not handle
476 # tagging itself; you need to do it externally, outside gitweb.
477 # The format is described in git_get_project_ctags() subroutine.
478 # You may want to install the HTML::TagCloud Perl module to get
479 # a pretty tag cloud instead of just a list of tags.
481 # To enable system wide have in $GITWEB_CONFIG
482 # $feature{'ctags'}{'default'} = [1];
483 # Project specific override is not supported.
485 # A value of 0 means no ctags display or editing. A value of
486 # 1 enables ctags display but never editing. A non-empty value
487 # that is not a string of digits enables ctags display AND the
488 # ability to add tags using a form that uses method POST and
489 # an action value set to the configured 'ctags' value.
490 'ctags' => {
491 'override' => 0,
492 'default' => [0]},
494 # The maximum number of patches in a patchset generated in patch
495 # view. Set this to 0 or undef to disable patch view, or to a
496 # negative number to remove any limit.
498 # To disable system wide have in $GITWEB_CONFIG
499 # $feature{'patches'}{'default'} = [0];
500 # To have project specific config enable override in $GITWEB_CONFIG
501 # $feature{'patches'}{'override'} = 1;
502 # and in project config gitweb.patches = 0|n;
503 # where n is the maximum number of patches allowed in a patchset.
504 'patches' => {
505 'sub' => \&feature_patches,
506 'override' => 0,
507 'default' => [16]},
509 # Avatar support. When this feature is enabled, views such as
510 # shortlog or commit will display an avatar associated with
511 # the email of the committer(s) and/or author(s).
513 # Currently available providers are gravatar and picon.
514 # If an unknown provider is specified, the feature is disabled.
516 # Gravatar depends on Digest::MD5.
517 # Picon currently relies on the indiana.edu database.
519 # To enable system wide have in $GITWEB_CONFIG
520 # $feature{'avatar'}{'default'} = ['<provider>'];
521 # where <provider> is either gravatar or picon.
522 # To have project specific config enable override in $GITWEB_CONFIG
523 # $feature{'avatar'}{'override'} = 1;
524 # and in project config gitweb.avatar = <provider>;
525 'avatar' => {
526 'sub' => \&feature_avatar,
527 'override' => 0,
528 'default' => ['']},
530 # Enable displaying how much time and how many git commands
531 # it took to generate and display page. Disabled by default.
532 # Project specific override is not supported.
533 'timed' => {
534 'override' => 0,
535 'default' => [0]},
537 # Enable turning some links into links to actions which require
538 # JavaScript to run (like 'blame_incremental'). Not enabled by
539 # default. Project specific override is currently not supported.
540 'javascript-actions' => {
541 'override' => 0,
542 'default' => [0]},
544 # Enable and configure ability to change common timezone for dates
545 # in gitweb output via JavaScript. Enabled by default.
546 # Project specific override is not supported.
547 'javascript-timezone' => {
548 'override' => 0,
549 'default' => [
550 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
551 # or undef to turn off this feature
552 'gitweb_tz', # name of cookie where to store selected timezone
553 'datetime', # CSS class used to mark up dates for manipulation
556 # Syntax highlighting support. This is based on Daniel Svensson's
557 # and Sham Chukoury's work in gitweb-xmms2.git.
558 # It requires the 'highlight' program present in $PATH,
559 # and therefore is disabled by default.
561 # To enable system wide have in $GITWEB_CONFIG
562 # $feature{'highlight'}{'default'} = [1];
564 'highlight' => {
565 'sub' => sub { feature_bool('highlight', @_) },
566 'override' => 0,
567 'default' => [0]},
569 # Enable displaying of remote heads in the heads list
571 # To enable system wide have in $GITWEB_CONFIG
572 # $feature{'remote_heads'}{'default'} = [1];
573 # To have project specific config enable override in $GITWEB_CONFIG
574 # $feature{'remote_heads'}{'override'} = 1;
575 # and in project config gitweb.remoteheads = 0|1;
576 'remote_heads' => {
577 'sub' => sub { feature_bool('remote_heads', @_) },
578 'override' => 0,
579 'default' => [0]},
581 # Enable showing branches under other refs in addition to heads
583 # To set system wide extra branch refs have in $GITWEB_CONFIG
584 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
585 # To have project specific config enable override in $GITWEB_CONFIG
586 # $feature{'extra-branch-refs'}{'override'} = 1;
587 # and in project config gitweb.extrabranchrefs = dirs of choice
588 # Every directory is separated with whitespace.
590 'extra-branch-refs' => {
591 'sub' => \&feature_extra_branch_refs,
592 'override' => 0,
593 'default' => []},
596 sub gitweb_get_feature {
597 my ($name) = @_;
598 return unless exists $feature{$name};
599 my ($sub, $override, @defaults) = (
600 $feature{$name}{'sub'},
601 $feature{$name}{'override'},
602 @{$feature{$name}{'default'}});
603 # project specific override is possible only if we have project
604 our $git_dir; # global variable, declared later
605 if (!$override || !defined $git_dir) {
606 return @defaults;
608 if (!defined $sub) {
609 warn "feature $name is not overridable";
610 return @defaults;
612 return $sub->(@defaults);
615 # A wrapper to check if a given feature is enabled.
616 # With this, you can say
618 # my $bool_feat = gitweb_check_feature('bool_feat');
619 # gitweb_check_feature('bool_feat') or somecode;
621 # instead of
623 # my ($bool_feat) = gitweb_get_feature('bool_feat');
624 # (gitweb_get_feature('bool_feat'))[0] or somecode;
626 sub gitweb_check_feature {
627 return (gitweb_get_feature(@_))[0];
631 sub feature_bool {
632 my $key = shift;
633 my ($val) = git_get_project_config($key, '--bool');
635 if (!defined $val) {
636 return ($_[0]);
637 } elsif ($val eq 'true') {
638 return (1);
639 } elsif ($val eq 'false') {
640 return (0);
644 sub feature_snapshot {
645 my (@fmts) = @_;
647 my ($val) = git_get_project_config('snapshot');
649 if ($val) {
650 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
653 return @fmts;
656 sub feature_patches {
657 my @val = (git_get_project_config('patches', '--int'));
659 if (@val) {
660 return @val;
663 return ($_[0]);
666 sub feature_avatar {
667 my @val = (git_get_project_config('avatar'));
669 return @val ? @val : @_;
672 sub feature_extra_branch_refs {
673 my (@branch_refs) = @_;
674 my $values = git_get_project_config('extrabranchrefs');
676 if ($values) {
677 $values = config_to_multi ($values);
678 @branch_refs = ();
679 foreach my $value (@{$values}) {
680 push @branch_refs, split /\s+/, $value;
684 return @branch_refs;
687 # checking HEAD file with -e is fragile if the repository was
688 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
689 # and then pruned.
690 sub check_head_link {
691 my ($dir) = @_;
692 my $headfile = "$dir/HEAD";
693 return ((-e $headfile) ||
694 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
697 sub check_export_ok {
698 my ($dir) = @_;
699 return (check_head_link($dir) &&
700 (!$export_ok || -e "$dir/$export_ok") &&
701 (!$export_auth_hook || $export_auth_hook->($dir)));
704 # process alternate names for backward compatibility
705 # filter out unsupported (unknown) snapshot formats
706 sub filter_snapshot_fmts {
707 my @fmts = @_;
709 @fmts = map {
710 exists $known_snapshot_format_aliases{$_} ?
711 $known_snapshot_format_aliases{$_} : $_} @fmts;
712 @fmts = grep {
713 exists $known_snapshot_formats{$_} &&
714 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
717 sub filter_and_validate_refs {
718 my @refs = @_;
719 my %unique_refs = ();
721 foreach my $ref (@refs) {
722 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
723 # 'heads' are added implicitly in get_branch_refs().
724 $unique_refs{$ref} = 1 if ($ref ne 'heads');
726 return sort keys %unique_refs;
729 # If it is set to code reference, it is code that it is to be run once per
730 # request, allowing updating configurations that change with each request,
731 # while running other code in config file only once.
733 # Otherwise, if it is false then gitweb would process config file only once;
734 # if it is true then gitweb config would be run for each request.
735 our $per_request_config = 1;
737 # read and parse gitweb config file given by its parameter.
738 # returns true on success, false on recoverable error, allowing
739 # to chain this subroutine, using first file that exists.
740 # dies on errors during parsing config file, as it is unrecoverable.
741 sub read_config_file {
742 my $filename = shift;
743 return unless defined $filename;
744 # die if there are errors parsing config file
745 if (-e $filename) {
746 do $filename;
747 die $@ if $@;
748 return 1;
750 return;
753 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
754 sub evaluate_gitweb_config {
755 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
756 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
757 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
759 # Protect against duplications of file names, to not read config twice.
760 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
761 # there possibility of duplication of filename there doesn't matter.
762 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
763 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
765 # Common system-wide settings for convenience.
766 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
767 read_config_file($GITWEB_CONFIG_COMMON);
769 # Use first config file that exists. This means use the per-instance
770 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
771 read_config_file($GITWEB_CONFIG) and return;
772 read_config_file($GITWEB_CONFIG_SYSTEM);
775 # Get loadavg of system, to compare against $maxload.
776 # Currently it requires '/proc/loadavg' present to get loadavg;
777 # if it is not present it returns 0, which means no load checking.
778 sub get_loadavg {
779 if( -e '/proc/loadavg' ){
780 open my $fd, '<', '/proc/loadavg'
781 or return 0;
782 my @load = split(/\s+/, scalar <$fd>);
783 close $fd;
785 # The first three columns measure CPU and IO utilization of the last one,
786 # five, and 10 minute periods. The fourth column shows the number of
787 # currently running processes and the total number of processes in the m/n
788 # format. The last column displays the last process ID used.
789 return $load[0] || 0;
791 # additional checks for load average should go here for things that don't export
792 # /proc/loadavg
794 return 0;
797 # version of the core git binary
798 our $git_version;
799 sub evaluate_git_version {
800 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
801 $number_of_git_cmds++;
804 sub check_loadavg {
805 if (defined $maxload && get_loadavg() > $maxload) {
806 die_error(503, "The load average on the server is too high");
810 # ======================================================================
811 # input validation and dispatch
813 # input parameters can be collected from a variety of sources (presently, CGI
814 # and PATH_INFO), so we define an %input_params hash that collects them all
815 # together during validation: this allows subsequent uses (e.g. href()) to be
816 # agnostic of the parameter origin
818 our %input_params = ();
820 # input parameters are stored with the long parameter name as key. This will
821 # also be used in the href subroutine to convert parameters to their CGI
822 # equivalent, and since the href() usage is the most frequent one, we store
823 # the name -> CGI key mapping here, instead of the reverse.
825 # XXX: Warning: If you touch this, check the search form for updating,
826 # too.
828 our @cgi_param_mapping = (
829 project => "p",
830 action => "a",
831 file_name => "f",
832 file_parent => "fp",
833 hash => "h",
834 hash_parent => "hp",
835 hash_base => "hb",
836 hash_parent_base => "hpb",
837 page => "pg",
838 order => "o",
839 searchtext => "s",
840 searchtype => "st",
841 snapshot_format => "sf",
842 ctag_filter => 't',
843 extra_options => "opt",
844 search_use_regexp => "sr",
845 ctag => "by_tag",
846 diff_style => "ds",
847 project_filter => "pf",
848 # this must be last entry (for manipulation from JavaScript)
849 javascript => "js"
851 our %cgi_param_mapping = @cgi_param_mapping;
853 # we will also need to know the possible actions, for validation
854 our %actions = (
855 "blame" => \&git_blame,
856 "blame_incremental" => \&git_blame_incremental,
857 "blame_data" => \&git_blame_data,
858 "blobdiff" => \&git_blobdiff,
859 "blobdiff_plain" => \&git_blobdiff_plain,
860 "blob" => \&git_blob,
861 "blob_plain" => \&git_blob_plain,
862 "commitdiff" => \&git_commitdiff,
863 "commitdiff_plain" => \&git_commitdiff_plain,
864 "commit" => \&git_commit,
865 "forks" => \&git_forks,
866 "heads" => \&git_heads,
867 "history" => \&git_history,
868 "log" => \&git_log,
869 "patch" => \&git_patch,
870 "patches" => \&git_patches,
871 "remotes" => \&git_remotes,
872 "rss" => \&git_rss,
873 "atom" => \&git_atom,
874 "search" => \&git_search,
875 "search_help" => \&git_search_help,
876 "shortlog" => \&git_shortlog,
877 "summary" => \&git_summary,
878 "tag" => \&git_tag,
879 "tags" => \&git_tags,
880 "tree" => \&git_tree,
881 "snapshot" => \&git_snapshot,
882 "object" => \&git_object,
883 # those below don't need $project
884 "opml" => \&git_opml,
885 "frontpage" => \&git_frontpage,
886 "project_list" => \&git_project_list,
887 "project_index" => \&git_project_index,
890 # finally, we have the hash of allowed extra_options for the commands that
891 # allow them
892 our %allowed_options = (
893 "--no-merges" => [ qw(rss atom log shortlog history) ],
896 # fill %input_params with the CGI parameters. All values except for 'opt'
897 # should be single values, but opt can be an array. We should probably
898 # build an array of parameters that can be multi-valued, but since for the time
899 # being it's only this one, we just single it out
900 sub evaluate_query_params {
901 our $cgi;
903 while (my ($name, $symbol) = each %cgi_param_mapping) {
904 if ($symbol eq 'opt') {
905 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
906 } else {
907 $input_params{$name} = decode_utf8($cgi->param($symbol));
911 # Backwards compatibility - by_tag= <=> t=
912 if ($input_params{'ctag'}) {
913 $input_params{'ctag_filter'} = $input_params{'ctag'};
917 # now read PATH_INFO and update the parameter list for missing parameters
918 sub evaluate_path_info {
919 return if defined $input_params{'project'};
920 return if !$path_info;
921 $path_info =~ s,^/+,,;
922 return if !$path_info;
924 # find which part of PATH_INFO is project
925 my $project = $path_info;
926 $project =~ s,/+$,,;
927 while ($project && !check_head_link("$projectroot/$project")) {
928 $project =~ s,/*[^/]*$,,;
930 return unless $project;
931 $input_params{'project'} = $project;
933 # do not change any parameters if an action is given using the query string
934 return if $input_params{'action'};
935 $path_info =~ s,^\Q$project\E/*,,;
937 # next, check if we have an action
938 my $action = $path_info;
939 $action =~ s,/.*$,,;
940 if (exists $actions{$action}) {
941 $path_info =~ s,^$action/*,,;
942 $input_params{'action'} = $action;
945 # list of actions that want hash_base instead of hash, but can have no
946 # pathname (f) parameter
947 my @wants_base = (
948 'tree',
949 'history',
952 # we want to catch, among others
953 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
954 my ($parentrefname, $parentpathname, $refname, $pathname) =
955 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
957 # first, analyze the 'current' part
958 if (defined $pathname) {
959 # we got "branch:filename" or "branch:dir/"
960 # we could use git_get_type(branch:pathname), but:
961 # - it needs $git_dir
962 # - it does a git() call
963 # - the convention of terminating directories with a slash
964 # makes it superfluous
965 # - embedding the action in the PATH_INFO would make it even
966 # more superfluous
967 $pathname =~ s,^/+,,;
968 if (!$pathname || substr($pathname, -1) eq "/") {
969 $input_params{'action'} ||= "tree";
970 $pathname =~ s,/$,,;
971 } else {
972 # the default action depends on whether we had parent info
973 # or not
974 if ($parentrefname) {
975 $input_params{'action'} ||= "blobdiff_plain";
976 } else {
977 $input_params{'action'} ||= "blob_plain";
980 $input_params{'hash_base'} ||= $refname;
981 $input_params{'file_name'} ||= $pathname;
982 } elsif (defined $refname) {
983 # we got "branch". In this case we have to choose if we have to
984 # set hash or hash_base.
986 # Most of the actions without a pathname only want hash to be
987 # set, except for the ones specified in @wants_base that want
988 # hash_base instead. It should also be noted that hand-crafted
989 # links having 'history' as an action and no pathname or hash
990 # set will fail, but that happens regardless of PATH_INFO.
991 if (defined $parentrefname) {
992 # if there is parent let the default be 'shortlog' action
993 # (for http://git.example.com/repo.git/A..B links); if there
994 # is no parent, dispatch will detect type of object and set
995 # action appropriately if required (if action is not set)
996 $input_params{'action'} ||= "shortlog";
998 if ($input_params{'action'} &&
999 grep { $_ eq $input_params{'action'} } @wants_base) {
1000 $input_params{'hash_base'} ||= $refname;
1001 } else {
1002 $input_params{'hash'} ||= $refname;
1006 # next, handle the 'parent' part, if present
1007 if (defined $parentrefname) {
1008 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1009 # someproject/blobdiff/oldrev..newrev:/filename
1010 if ($parentpathname) {
1011 $parentpathname =~ s,^/+,,;
1012 $parentpathname =~ s,/$,,;
1013 $input_params{'file_parent'} ||= $parentpathname;
1014 } else {
1015 $input_params{'file_parent'} ||= $input_params{'file_name'};
1017 # we assume that hash_parent_base is wanted if a path was specified,
1018 # or if the action wants hash_base instead of hash
1019 if (defined $input_params{'file_parent'} ||
1020 grep { $_ eq $input_params{'action'} } @wants_base) {
1021 $input_params{'hash_parent_base'} ||= $parentrefname;
1022 } else {
1023 $input_params{'hash_parent'} ||= $parentrefname;
1027 # for the snapshot action, we allow URLs in the form
1028 # $project/snapshot/$hash.ext
1029 # where .ext determines the snapshot and gets removed from the
1030 # passed $refname to provide the $hash.
1032 # To be able to tell that $refname includes the format extension, we
1033 # require the following two conditions to be satisfied:
1034 # - the hash input parameter MUST have been set from the $refname part
1035 # of the URL (i.e. they must be equal)
1036 # - the snapshot format MUST NOT have been defined already (e.g. from
1037 # CGI parameter sf)
1038 # It's also useless to try any matching unless $refname has a dot,
1039 # so we check for that too
1040 if (defined $input_params{'action'} &&
1041 $input_params{'action'} eq 'snapshot' &&
1042 defined $refname && index($refname, '.') != -1 &&
1043 $refname eq $input_params{'hash'} &&
1044 !defined $input_params{'snapshot_format'}) {
1045 # We loop over the known snapshot formats, checking for
1046 # extensions. Allowed extensions are both the defined suffix
1047 # (which includes the initial dot already) and the snapshot
1048 # format key itself, with a prepended dot
1049 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1050 my $hash = $refname;
1051 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1052 next;
1054 my $sfx = $1;
1055 # a valid suffix was found, so set the snapshot format
1056 # and reset the hash parameter
1057 $input_params{'snapshot_format'} = $fmt;
1058 $input_params{'hash'} = $hash;
1059 # we also set the format suffix to the one requested
1060 # in the URL: this way a request for e.g. .tgz returns
1061 # a .tgz instead of a .tar.gz
1062 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1063 last;
1068 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1069 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1070 $searchtext, $search_regexp, $project_filter);
1071 sub evaluate_and_validate_params {
1072 our $action = $input_params{'action'};
1073 if (defined $action) {
1074 if (!is_valid_action($action)) {
1075 die_error(400, "Invalid action parameter");
1079 # parameters which are pathnames
1080 our $project = $input_params{'project'};
1081 if (defined $project) {
1082 if (!is_valid_project($project)) {
1083 undef $project;
1084 die_error(404, "No such project");
1088 our $project_filter = $input_params{'project_filter'};
1089 if (defined $project_filter) {
1090 if (!is_valid_pathname($project_filter)) {
1091 die_error(404, "Invalid project_filter parameter");
1095 our $file_name = $input_params{'file_name'};
1096 if (defined $file_name) {
1097 if (!is_valid_pathname($file_name)) {
1098 die_error(400, "Invalid file parameter");
1102 our $file_parent = $input_params{'file_parent'};
1103 if (defined $file_parent) {
1104 if (!is_valid_pathname($file_parent)) {
1105 die_error(400, "Invalid file parent parameter");
1109 # parameters which are refnames
1110 our $hash = $input_params{'hash'};
1111 if (defined $hash) {
1112 if (!is_valid_refname($hash)) {
1113 die_error(400, "Invalid hash parameter");
1117 our $hash_parent = $input_params{'hash_parent'};
1118 if (defined $hash_parent) {
1119 if (!is_valid_refname($hash_parent)) {
1120 die_error(400, "Invalid hash parent parameter");
1124 our $hash_base = $input_params{'hash_base'};
1125 if (defined $hash_base) {
1126 if (!is_valid_refname($hash_base)) {
1127 die_error(400, "Invalid hash base parameter");
1131 our @extra_options = @{$input_params{'extra_options'}};
1132 # @extra_options is always defined, since it can only be (currently) set from
1133 # CGI, and $cgi->param() returns the empty array in array context if the param
1134 # is not set
1135 foreach my $opt (@extra_options) {
1136 if (not exists $allowed_options{$opt}) {
1137 die_error(400, "Invalid option parameter");
1139 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1140 die_error(400, "Invalid option parameter for this action");
1144 our $hash_parent_base = $input_params{'hash_parent_base'};
1145 if (defined $hash_parent_base) {
1146 if (!is_valid_refname($hash_parent_base)) {
1147 die_error(400, "Invalid hash parent base parameter");
1151 # other parameters
1152 our $page = $input_params{'page'};
1153 if (defined $page) {
1154 if ($page =~ m/[^0-9]/) {
1155 die_error(400, "Invalid page parameter");
1159 our $searchtype = $input_params{'searchtype'};
1160 if (defined $searchtype) {
1161 if ($searchtype =~ m/[^a-z]/) {
1162 die_error(400, "Invalid searchtype parameter");
1166 our $search_use_regexp = $input_params{'search_use_regexp'};
1168 our $searchtext = $input_params{'searchtext'};
1169 our $search_regexp = undef;
1170 if (defined $searchtext) {
1171 if (length($searchtext) < 2) {
1172 die_error(403, "At least two characters are required for search parameter");
1174 if ($search_use_regexp) {
1175 $search_regexp = $searchtext;
1176 if (!eval { qr/$search_regexp/; 1; }) {
1177 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1178 die_error(400, "Invalid search regexp '$search_regexp'",
1179 esc_html($error));
1181 } else {
1182 $search_regexp = quotemeta $searchtext;
1187 # path to the current git repository
1188 our $git_dir;
1189 sub evaluate_git_dir {
1190 our $git_dir = "$projectroot/$project" if $project;
1193 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1194 sub configure_gitweb_features {
1195 # list of supported snapshot formats
1196 our @snapshot_fmts = gitweb_get_feature('snapshot');
1197 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1199 # check that the avatar feature is set to a known provider name,
1200 # and for each provider check if the dependencies are satisfied.
1201 # if the provider name is invalid or the dependencies are not met,
1202 # reset $git_avatar to the empty string.
1203 our ($git_avatar) = gitweb_get_feature('avatar');
1204 if ($git_avatar eq 'gravatar') {
1205 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1206 } elsif ($git_avatar eq 'picon') {
1207 # no dependencies
1208 } else {
1209 $git_avatar = '';
1212 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1213 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1216 sub get_branch_refs {
1217 return ('heads', @extra_branch_refs);
1220 # custom error handler: 'die <message>' is Internal Server Error
1221 sub handle_errors_html {
1222 my $msg = shift; # it is already HTML escaped
1224 # to avoid infinite loop where error occurs in die_error,
1225 # change handler to default handler, disabling handle_errors_html
1226 set_message("Error occurred when inside die_error:\n$msg");
1228 # you cannot jump out of die_error when called as error handler;
1229 # the subroutine set via CGI::Carp::set_message is called _after_
1230 # HTTP headers are already written, so it cannot write them itself
1231 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1233 set_message(\&handle_errors_html);
1235 our $shown_stale_message = 0;
1237 # dispatch
1238 sub dispatch {
1239 $shown_stale_message = 0;
1240 if (!defined $action) {
1241 if (defined $hash) {
1242 $action = git_get_type($hash);
1243 $action or die_error(404, "Object does not exist");
1244 } elsif (defined $hash_base && defined $file_name) {
1245 $action = git_get_type("$hash_base:$file_name");
1246 $action or die_error(404, "File or directory does not exist");
1247 } elsif (defined $project) {
1248 $action = 'summary';
1249 } else {
1250 $action = 'frontpage';
1253 if (!defined($actions{$action})) {
1254 die_error(400, "Unknown action");
1256 if ($action !~ m/^(?:opml|frontpage|project_list|project_index)$/ &&
1257 !$project) {
1258 die_error(400, "Project needed");
1260 $actions{$action}->();
1263 sub reset_timer {
1264 our $t0 = [ gettimeofday() ]
1265 if defined $t0;
1266 our $number_of_git_cmds = 0;
1269 our $first_request = 1;
1270 sub run_request {
1271 reset_timer();
1273 evaluate_uri();
1274 if ($first_request) {
1275 evaluate_gitweb_config();
1276 evaluate_git_version();
1278 if ($per_request_config) {
1279 if (ref($per_request_config) eq 'CODE') {
1280 $per_request_config->();
1281 } elsif (!$first_request) {
1282 evaluate_gitweb_config();
1285 check_loadavg();
1287 # $projectroot and $projects_list might be set in gitweb config file
1288 $projects_list ||= $projectroot;
1290 evaluate_query_params();
1291 evaluate_path_info();
1292 evaluate_and_validate_params();
1293 evaluate_git_dir();
1295 configure_gitweb_features();
1297 dispatch();
1300 our $is_last_request = sub { 1 };
1301 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1302 our $CGI = 'CGI';
1303 our $cgi;
1304 sub configure_as_fcgi {
1305 require CGI::Fast;
1306 our $CGI = 'CGI::Fast';
1308 my $request_number = 0;
1309 # let each child service 100 requests
1310 our $is_last_request = sub { ++$request_number > 100 };
1312 sub evaluate_argv {
1313 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1314 configure_as_fcgi()
1315 if $script_name =~ /\.fcgi$/;
1317 return unless (@ARGV);
1319 require Getopt::Long;
1320 Getopt::Long::GetOptions(
1321 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1322 'nproc|n=i' => sub {
1323 my ($arg, $val) = @_;
1324 return unless eval { require FCGI::ProcManager; 1; };
1325 my $proc_manager = FCGI::ProcManager->new({
1326 n_processes => $val,
1328 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1329 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1330 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1335 sub run {
1336 evaluate_argv();
1338 $first_request = 1;
1339 $pre_listen_hook->()
1340 if $pre_listen_hook;
1342 REQUEST:
1343 while ($cgi = $CGI->new()) {
1344 $pre_dispatch_hook->()
1345 if $pre_dispatch_hook;
1347 run_request();
1349 $post_dispatch_hook->()
1350 if $post_dispatch_hook;
1351 $first_request = 0;
1353 last REQUEST if ($is_last_request->());
1356 DONE_GITWEB:
1360 run();
1362 if (defined caller) {
1363 # wrapped in a subroutine processing requests,
1364 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1365 return;
1366 } else {
1367 # pure CGI script, serving single request
1368 exit;
1371 ## ======================================================================
1372 ## action links
1374 # possible values of extra options
1375 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1376 # -replay => 1 - start from a current view (replay with modifications)
1377 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1378 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1379 sub href {
1380 my %params = @_;
1381 # default is to use -absolute url() i.e. $my_uri
1382 my $href = $params{-full} ? $my_url : $my_uri;
1384 # implicit -replay, must be first of implicit params
1385 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1387 $params{'project'} = $project unless exists $params{'project'};
1389 if ($params{-replay}) {
1390 while (my ($name, $symbol) = each %cgi_param_mapping) {
1391 if (!exists $params{$name}) {
1392 $params{$name} = $input_params{$name};
1397 my $use_pathinfo = gitweb_check_feature('pathinfo');
1398 if (defined $params{'project'} &&
1399 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1400 # try to put as many parameters as possible in PATH_INFO:
1401 # - project name
1402 # - action
1403 # - hash_parent or hash_parent_base:/file_parent
1404 # - hash or hash_base:/filename
1405 # - the snapshot_format as an appropriate suffix
1407 # When the script is the root DirectoryIndex for the domain,
1408 # $href here would be something like http://gitweb.example.com/
1409 # Thus, we strip any trailing / from $href, to spare us double
1410 # slashes in the final URL
1411 $href =~ s,/$,,;
1413 # Then add the project name, if present
1414 $href .= "/".esc_path_info($params{'project'});
1415 delete $params{'project'};
1417 # since we destructively absorb parameters, we keep this
1418 # boolean that remembers if we're handling a snapshot
1419 my $is_snapshot = $params{'action'} eq 'snapshot';
1421 # Summary just uses the project path URL, any other action is
1422 # added to the URL
1423 if (defined $params{'action'}) {
1424 $href .= "/".esc_path_info($params{'action'})
1425 unless $params{'action'} eq 'summary';
1426 delete $params{'action'};
1429 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1430 # stripping nonexistent or useless pieces
1431 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1432 || $params{'hash_parent'} || $params{'hash'});
1433 if (defined $params{'hash_base'}) {
1434 if (defined $params{'hash_parent_base'}) {
1435 $href .= esc_path_info($params{'hash_parent_base'});
1436 # skip the file_parent if it's the same as the file_name
1437 if (defined $params{'file_parent'}) {
1438 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1439 delete $params{'file_parent'};
1440 } elsif ($params{'file_parent'} !~ /\.\./) {
1441 $href .= ":/".esc_path_info($params{'file_parent'});
1442 delete $params{'file_parent'};
1445 $href .= "..";
1446 delete $params{'hash_parent'};
1447 delete $params{'hash_parent_base'};
1448 } elsif (defined $params{'hash_parent'}) {
1449 $href .= esc_path_info($params{'hash_parent'}). "..";
1450 delete $params{'hash_parent'};
1453 $href .= esc_path_info($params{'hash_base'});
1454 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1455 $href .= ":/".esc_path_info($params{'file_name'});
1456 delete $params{'file_name'};
1458 delete $params{'hash'};
1459 delete $params{'hash_base'};
1460 } elsif (defined $params{'hash'}) {
1461 $href .= esc_path_info($params{'hash'});
1462 delete $params{'hash'};
1465 # If the action was a snapshot, we can absorb the
1466 # snapshot_format parameter too
1467 if ($is_snapshot) {
1468 my $fmt = $params{'snapshot_format'};
1469 # snapshot_format should always be defined when href()
1470 # is called, but just in case some code forgets, we
1471 # fall back to the default
1472 $fmt ||= $snapshot_fmts[0];
1473 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1474 delete $params{'snapshot_format'};
1478 # now encode the parameters explicitly
1479 my @result = ();
1480 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1481 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1482 if (defined $params{$name}) {
1483 if (ref($params{$name}) eq "ARRAY") {
1484 foreach my $par (@{$params{$name}}) {
1485 push @result, $symbol . "=" . esc_param($par);
1487 } else {
1488 push @result, $symbol . "=" . esc_param($params{$name});
1492 $href .= "?" . join(';', @result) if scalar @result;
1494 # final transformation: trailing spaces must be escaped (URI-encoded)
1495 $href =~ s/(\s+)$/CGI::escape($1)/e;
1497 if ($params{-anchor}) {
1498 $href .= "#".esc_param($params{-anchor});
1501 return $href;
1505 ## ======================================================================
1506 ## validation, quoting/unquoting and escaping
1508 sub is_valid_action {
1509 my $input = shift;
1510 return undef unless exists $actions{$input};
1511 return 1;
1514 sub is_valid_project {
1515 my $input = shift;
1517 return unless defined $input;
1518 if (!is_valid_pathname($input) ||
1519 !(-d "$projectroot/$input") ||
1520 !check_export_ok("$projectroot/$input") ||
1521 ($strict_export && !project_in_list($input))) {
1522 return undef;
1523 } else {
1524 return 1;
1528 sub is_valid_pathname {
1529 my $input = shift;
1531 return undef unless defined $input;
1532 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1533 # at the beginning, at the end, and between slashes.
1534 # also this catches doubled slashes
1535 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1536 return undef;
1538 # no null characters
1539 if ($input =~ m!\0!) {
1540 return undef;
1542 return 1;
1545 sub is_valid_ref_format {
1546 my $input = shift;
1548 return undef unless defined $input;
1549 # restrictions on ref name according to git-check-ref-format
1550 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1551 return undef;
1553 return 1;
1556 sub is_valid_refname {
1557 my $input = shift;
1559 return undef unless defined $input;
1560 # textual hashes are O.K.
1561 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1562 return 1;
1564 # it must be correct pathname
1565 is_valid_pathname($input) or return undef;
1566 # check git-check-ref-format restrictions
1567 is_valid_ref_format($input) or return undef;
1568 return 1;
1571 # decode sequences of octets in utf8 into Perl's internal form,
1572 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1573 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1574 sub to_utf8 {
1575 my $str = shift;
1576 return undef unless defined $str;
1578 if (utf8::is_utf8($str) || utf8::decode($str)) {
1579 return $str;
1580 } else {
1581 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1585 # quote unsafe chars, but keep the slash, even when it's not
1586 # correct, but quoted slashes look too horrible in bookmarks
1587 sub esc_param {
1588 my $str = shift;
1589 return undef unless defined $str;
1590 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1591 $str =~ s/ /\+/g;
1592 return $str;
1595 # the quoting rules for path_info fragment are slightly different
1596 sub esc_path_info {
1597 my $str = shift;
1598 return undef unless defined $str;
1600 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1601 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1603 return $str;
1606 # quote unsafe chars in whole URL, so some characters cannot be quoted
1607 sub esc_url {
1608 my $str = shift;
1609 return undef unless defined $str;
1610 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1611 $str =~ s/ /\+/g;
1612 return $str;
1615 # quote unsafe characters in HTML attributes
1616 sub esc_attr {
1618 # for XHTML conformance escaping '"' to '&quot;' is not enough
1619 return esc_html(@_);
1622 # replace invalid utf8 character with SUBSTITUTION sequence
1623 sub esc_html {
1624 my $str = shift;
1625 my %opts = @_;
1627 return undef unless defined $str;
1629 $str = to_utf8($str);
1630 $str = $cgi->escapeHTML($str);
1631 if ($opts{'-nbsp'}) {
1632 $str =~ s/ /&nbsp;/g;
1634 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1635 return $str;
1638 # quote control characters and escape filename to HTML
1639 sub esc_path {
1640 my $str = shift;
1641 my %opts = @_;
1643 return undef unless defined $str;
1645 $str = to_utf8($str);
1646 $str = $cgi->escapeHTML($str);
1647 if ($opts{'-nbsp'}) {
1648 $str =~ s/ /&nbsp;/g;
1650 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1651 return $str;
1654 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1655 sub sanitize {
1656 my $str = shift;
1658 return undef unless defined $str;
1660 $str = to_utf8($str);
1661 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1662 return $str;
1665 # Make control characters "printable", using character escape codes (CEC)
1666 sub quot_cec {
1667 my $cntrl = shift;
1668 my %opts = @_;
1669 my %es = ( # character escape codes, aka escape sequences
1670 "\t" => '\t', # tab (HT)
1671 "\n" => '\n', # line feed (LF)
1672 "\r" => '\r', # carrige return (CR)
1673 "\f" => '\f', # form feed (FF)
1674 "\b" => '\b', # backspace (BS)
1675 "\a" => '\a', # alarm (bell) (BEL)
1676 "\e" => '\e', # escape (ESC)
1677 "\013" => '\v', # vertical tab (VT)
1678 "\000" => '\0', # nul character (NUL)
1680 my $chr = ( (exists $es{$cntrl})
1681 ? $es{$cntrl}
1682 : sprintf('\%2x', ord($cntrl)) );
1683 if ($opts{-nohtml}) {
1684 return $chr;
1685 } else {
1686 return "<span class=\"cntrl\">$chr</span>";
1690 # Alternatively use unicode control pictures codepoints,
1691 # Unicode "printable representation" (PR)
1692 sub quot_upr {
1693 my $cntrl = shift;
1694 my %opts = @_;
1696 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1697 if ($opts{-nohtml}) {
1698 return $chr;
1699 } else {
1700 return "<span class=\"cntrl\">$chr</span>";
1704 # git may return quoted and escaped filenames
1705 sub unquote {
1706 my $str = shift;
1708 sub unq {
1709 my $seq = shift;
1710 my %es = ( # character escape codes, aka escape sequences
1711 't' => "\t", # tab (HT, TAB)
1712 'n' => "\n", # newline (NL)
1713 'r' => "\r", # return (CR)
1714 'f' => "\f", # form feed (FF)
1715 'b' => "\b", # backspace (BS)
1716 'a' => "\a", # alarm (bell) (BEL)
1717 'e' => "\e", # escape (ESC)
1718 'v' => "\013", # vertical tab (VT)
1721 if ($seq =~ m/^[0-7]{1,3}$/) {
1722 # octal char sequence
1723 return chr(oct($seq));
1724 } elsif (exists $es{$seq}) {
1725 # C escape sequence, aka character escape code
1726 return $es{$seq};
1728 # quoted ordinary character
1729 return $seq;
1732 if ($str =~ m/^"(.*)"$/) {
1733 # needs unquoting
1734 $str = $1;
1735 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1737 return $str;
1740 # escape tabs (convert tabs to spaces)
1741 sub untabify {
1742 my $line = shift;
1744 while ((my $pos = index($line, "\t")) != -1) {
1745 if (my $count = (8 - ($pos % 8))) {
1746 my $spaces = ' ' x $count;
1747 $line =~ s/\t/$spaces/;
1751 return $line;
1754 sub project_in_list {
1755 my $project = shift;
1756 my @list = git_get_projects_list();
1757 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1760 ## ----------------------------------------------------------------------
1761 ## HTML aware string manipulation
1763 # Try to chop given string on a word boundary between position
1764 # $len and $len+$add_len. If there is no word boundary there,
1765 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1766 # (marking chopped part) would be longer than given string.
1767 sub chop_str {
1768 my $str = shift;
1769 my $len = shift;
1770 my $add_len = shift || 10;
1771 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1773 # Make sure perl knows it is utf8 encoded so we don't
1774 # cut in the middle of a utf8 multibyte char.
1775 $str = to_utf8($str);
1777 # allow only $len chars, but don't cut a word if it would fit in $add_len
1778 # if it doesn't fit, cut it if it's still longer than the dots we would add
1779 # remove chopped character entities entirely
1781 # when chopping in the middle, distribute $len into left and right part
1782 # return early if chopping wouldn't make string shorter
1783 if ($where eq 'center') {
1784 return $str if ($len + 5 >= length($str)); # filler is length 5
1785 $len = int($len/2);
1786 } else {
1787 return $str if ($len + 4 >= length($str)); # filler is length 4
1790 # regexps: ending and beginning with word part up to $add_len
1791 my $endre = qr/.{$len}\w{0,$add_len}/;
1792 my $begre = qr/\w{0,$add_len}.{$len}/;
1794 if ($where eq 'left') {
1795 $str =~ m/^(.*?)($begre)$/;
1796 my ($lead, $body) = ($1, $2);
1797 if (length($lead) > 4) {
1798 $lead = " ...";
1800 return "$lead$body";
1802 } elsif ($where eq 'center') {
1803 $str =~ m/^($endre)(.*)$/;
1804 my ($left, $str) = ($1, $2);
1805 $str =~ m/^(.*?)($begre)$/;
1806 my ($mid, $right) = ($1, $2);
1807 if (length($mid) > 5) {
1808 $mid = " ... ";
1810 return "$left$mid$right";
1812 } else {
1813 $str =~ m/^($endre)(.*)$/;
1814 my $body = $1;
1815 my $tail = $2;
1816 if (length($tail) > 4) {
1817 $tail = "... ";
1819 return "$body$tail";
1823 # takes the same arguments as chop_str, but also wraps a <span> around the
1824 # result with a title attribute if it does get chopped. Additionally, the
1825 # string is HTML-escaped.
1826 sub chop_and_escape_str {
1827 my ($str) = @_;
1829 my $chopped = chop_str(@_);
1830 $str = to_utf8($str);
1831 if ($chopped eq $str) {
1832 return esc_html($chopped);
1833 } else {
1834 $str =~ s/[[:cntrl:]]/?/g;
1835 return $cgi->span({-title=>$str}, esc_html($chopped));
1839 # Highlight selected fragments of string, using given CSS class,
1840 # and escape HTML. It is assumed that fragments do not overlap.
1841 # Regions are passed as list of pairs (array references).
1843 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1844 # '<span class="mark">foo</span>bar'
1845 sub esc_html_hl_regions {
1846 my ($str, $css_class, @sel) = @_;
1847 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1848 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1849 return esc_html($str, %opts) unless @sel;
1851 my $out = '';
1852 my $pos = 0;
1854 for my $s (@sel) {
1855 my ($begin, $end) = @$s;
1857 # Don't create empty <span> elements.
1858 next if $end <= $begin;
1860 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1861 %opts);
1863 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1864 if ($begin - $pos > 0);
1865 $out .= $cgi->span({-class => $css_class}, $escaped);
1867 $pos = $end;
1869 $out .= esc_html(substr($str, $pos), %opts)
1870 if ($pos < length($str));
1872 return $out;
1875 # return positions of beginning and end of each match
1876 sub matchpos_list {
1877 my ($str, $regexp) = @_;
1878 return unless (defined $str && defined $regexp);
1880 my @matches;
1881 while ($str =~ /$regexp/g) {
1882 push @matches, [$-[0], $+[0]];
1884 return @matches;
1887 # highlight match (if any), and escape HTML
1888 sub esc_html_match_hl {
1889 my ($str, $regexp) = @_;
1890 return esc_html($str) unless defined $regexp;
1892 my @matches = matchpos_list($str, $regexp);
1893 return esc_html($str) unless @matches;
1895 return esc_html_hl_regions($str, 'match', @matches);
1899 # highlight match (if any) of shortened string, and escape HTML
1900 sub esc_html_match_hl_chopped {
1901 my ($str, $chopped, $regexp) = @_;
1902 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1904 my @matches = matchpos_list($str, $regexp);
1905 return esc_html($chopped) unless @matches;
1907 # filter matches so that we mark chopped string
1908 my $tail = "... "; # see chop_str
1909 unless ($chopped =~ s/\Q$tail\E$//) {
1910 $tail = '';
1912 my $chop_len = length($chopped);
1913 my $tail_len = length($tail);
1914 my @filtered;
1916 for my $m (@matches) {
1917 if ($m->[0] > $chop_len) {
1918 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1919 last;
1920 } elsif ($m->[1] > $chop_len) {
1921 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1922 last;
1924 push @filtered, $m;
1927 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1930 ## ----------------------------------------------------------------------
1931 ## functions returning short strings
1933 # CSS class for given age value (in seconds)
1934 sub age_class {
1935 my $age = shift;
1937 if (!defined $age) {
1938 return "noage";
1939 } elsif ($age < 60*60*2) {
1940 return "age0";
1941 } elsif ($age < 60*60*24*2) {
1942 return "age1";
1943 } else {
1944 return "age2";
1948 # convert age in seconds to "nn units ago" string
1949 sub age_string {
1950 my $age = shift;
1951 my $age_str;
1953 if ($age > 60*60*24*365*2) {
1954 $age_str = (int $age/60/60/24/365);
1955 $age_str .= " years ago";
1956 } elsif ($age > 60*60*24*(365/12)*2) {
1957 $age_str = int $age/60/60/24/(365/12);
1958 $age_str .= " months ago";
1959 } elsif ($age > 60*60*24*7*2) {
1960 $age_str = int $age/60/60/24/7;
1961 $age_str .= " weeks ago";
1962 } elsif ($age > 60*60*24*2) {
1963 $age_str = int $age/60/60/24;
1964 $age_str .= " days ago";
1965 } elsif ($age > 60*60*2) {
1966 $age_str = int $age/60/60;
1967 $age_str .= " hours ago";
1968 } elsif ($age > 60*2) {
1969 $age_str = int $age/60;
1970 $age_str .= " min ago";
1971 } elsif ($age > 2) {
1972 $age_str = int $age;
1973 $age_str .= " sec ago";
1974 } else {
1975 $age_str .= " right now";
1977 return $age_str;
1980 use constant {
1981 S_IFINVALID => 0030000,
1982 S_IFGITLINK => 0160000,
1985 # submodule/subproject, a commit object reference
1986 sub S_ISGITLINK {
1987 my $mode = shift;
1989 return (($mode & S_IFMT) == S_IFGITLINK)
1992 # convert file mode in octal to symbolic file mode string
1993 sub mode_str {
1994 my $mode = oct shift;
1996 if (S_ISGITLINK($mode)) {
1997 return 'm---------';
1998 } elsif (S_ISDIR($mode & S_IFMT)) {
1999 return 'drwxr-xr-x';
2000 } elsif (S_ISLNK($mode)) {
2001 return 'lrwxrwxrwx';
2002 } elsif (S_ISREG($mode)) {
2003 # git cares only about the executable bit
2004 if ($mode & S_IXUSR) {
2005 return '-rwxr-xr-x';
2006 } else {
2007 return '-rw-r--r--';
2009 } else {
2010 return '----------';
2014 # convert file mode in octal to file type string
2015 sub file_type {
2016 my $mode = shift;
2018 if ($mode !~ m/^[0-7]+$/) {
2019 return $mode;
2020 } else {
2021 $mode = oct $mode;
2024 if (S_ISGITLINK($mode)) {
2025 return "submodule";
2026 } elsif (S_ISDIR($mode & S_IFMT)) {
2027 return "directory";
2028 } elsif (S_ISLNK($mode)) {
2029 return "symlink";
2030 } elsif (S_ISREG($mode)) {
2031 return "file";
2032 } else {
2033 return "unknown";
2037 # convert file mode in octal to file type description string
2038 sub file_type_long {
2039 my $mode = shift;
2041 if ($mode !~ m/^[0-7]+$/) {
2042 return $mode;
2043 } else {
2044 $mode = oct $mode;
2047 if (S_ISGITLINK($mode)) {
2048 return "submodule";
2049 } elsif (S_ISDIR($mode & S_IFMT)) {
2050 return "directory";
2051 } elsif (S_ISLNK($mode)) {
2052 return "symlink";
2053 } elsif (S_ISREG($mode)) {
2054 if ($mode & S_IXUSR) {
2055 return "executable";
2056 } else {
2057 return "file";
2059 } else {
2060 return "unknown";
2065 ## ----------------------------------------------------------------------
2066 ## functions returning short HTML fragments, or transforming HTML fragments
2067 ## which don't belong to other sections
2069 # format line of commit message.
2070 sub format_log_line_html {
2071 my $line = shift;
2073 $line = esc_html($line, -nbsp=>1);
2074 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2075 $cgi->a({-href => href(action=>"object", hash=>$1),
2076 -class => "text"}, $1);
2077 }eg;
2079 return $line;
2082 # format marker of refs pointing to given object
2084 # the destination action is chosen based on object type and current context:
2085 # - for annotated tags, we choose the tag view unless it's the current view
2086 # already, in which case we go to shortlog view
2087 # - for other refs, we keep the current view if we're in history, shortlog or
2088 # log view, and select shortlog otherwise
2089 sub format_ref_marker {
2090 my ($refs, $id) = @_;
2091 my $markers = '';
2093 if (defined $refs->{$id}) {
2094 foreach my $ref (@{$refs->{$id}}) {
2095 # this code exploits the fact that non-lightweight tags are the
2096 # only indirect objects, and that they are the only objects for which
2097 # we want to use tag instead of shortlog as action
2098 my ($type, $name) = qw();
2099 my $indirect = ($ref =~ s/\^\{\}$//);
2100 # e.g. tags/v2.6.11 or heads/next
2101 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2102 $type = $1;
2103 $name = $2;
2104 } else {
2105 $type = "ref";
2106 $name = $ref;
2109 my $class = $type;
2110 $class .= " indirect" if $indirect;
2112 my $dest_action = "shortlog";
2114 if ($indirect) {
2115 $dest_action = "tag" unless $action eq "tag";
2116 } elsif ($action =~ /^(history|(short)?log)$/) {
2117 $dest_action = $action;
2120 my $dest = "";
2121 $dest .= "refs/" unless $ref =~ m!^refs/!;
2122 $dest .= $ref;
2124 my $link = $cgi->a({
2125 -href => href(
2126 action=>$dest_action,
2127 hash=>$dest
2128 )}, $name);
2130 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2131 $link . "</span>";
2135 if ($markers) {
2136 return ' <span class="refs">'. $markers . '</span>';
2137 } else {
2138 return "";
2142 # format, perhaps shortened and with markers, title line
2143 sub format_subject_html {
2144 my ($long, $short, $href, $extra) = @_;
2145 $extra = '' unless defined($extra);
2147 if (length($short) < length($long)) {
2148 $long =~ s/[[:cntrl:]]/?/g;
2149 return $cgi->a({-href => $href, -class => "list subject",
2150 -title => to_utf8($long)},
2151 esc_html($short)) . $extra;
2152 } else {
2153 return $cgi->a({-href => $href, -class => "list subject"},
2154 esc_html($long)) . $extra;
2158 # Rather than recomputing the url for an email multiple times, we cache it
2159 # after the first hit. This gives a visible benefit in views where the avatar
2160 # for the same email is used repeatedly (e.g. shortlog).
2161 # The cache is shared by all avatar engines (currently gravatar only), which
2162 # are free to use it as preferred. Since only one avatar engine is used for any
2163 # given page, there's no risk for cache conflicts.
2164 our %avatar_cache = ();
2166 # Compute the picon url for a given email, by using the picon search service over at
2167 # http://www.cs.indiana.edu/picons/search.html
2168 sub picon_url {
2169 my $email = lc shift;
2170 if (!$avatar_cache{$email}) {
2171 my ($user, $domain) = split('@', $email);
2172 $avatar_cache{$email} =
2173 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2174 "$domain/$user/" .
2175 "users+domains+unknown/up/single";
2177 return $avatar_cache{$email};
2180 # Compute the gravatar url for a given email, if it's not in the cache already.
2181 # Gravatar stores only the part of the URL before the size, since that's the
2182 # one computationally more expensive. This also allows reuse of the cache for
2183 # different sizes (for this particular engine).
2184 sub gravatar_url {
2185 my $email = lc shift;
2186 my $size = shift;
2187 $avatar_cache{$email} ||=
2188 "//www.gravatar.com/avatar/" .
2189 Digest::MD5::md5_hex($email) . "?s=";
2190 return $avatar_cache{$email} . $size;
2193 # Insert an avatar for the given $email at the given $size if the feature
2194 # is enabled.
2195 sub git_get_avatar {
2196 my ($email, %opts) = @_;
2197 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2198 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2199 $opts{-size} ||= 'default';
2200 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2201 my $url = "";
2202 if ($git_avatar eq 'gravatar') {
2203 $url = gravatar_url($email, $size);
2204 } elsif ($git_avatar eq 'picon') {
2205 $url = picon_url($email);
2207 # Other providers can be added by extending the if chain, defining $url
2208 # as needed. If no variant puts something in $url, we assume avatars
2209 # are completely disabled/unavailable.
2210 if ($url) {
2211 return $pre_white .
2212 "<img width=\"$size\" " .
2213 "class=\"avatar\" " .
2214 "src=\"".esc_url($url)."\" " .
2215 "alt=\"\" " .
2216 "/>" . $post_white;
2217 } else {
2218 return "";
2222 sub format_search_author {
2223 my ($author, $searchtype, $displaytext) = @_;
2224 my $have_search = gitweb_check_feature('search');
2226 if ($have_search) {
2227 my $performed = "";
2228 if ($searchtype eq 'author') {
2229 $performed = "authored";
2230 } elsif ($searchtype eq 'committer') {
2231 $performed = "committed";
2234 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2235 searchtext=>$author,
2236 searchtype=>$searchtype), class=>"list",
2237 title=>"Search for commits $performed by $author"},
2238 $displaytext);
2240 } else {
2241 return $displaytext;
2245 # format the author name of the given commit with the given tag
2246 # the author name is chopped and escaped according to the other
2247 # optional parameters (see chop_str).
2248 sub format_author_html {
2249 my $tag = shift;
2250 my $co = shift;
2251 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2252 return "<$tag class=\"author\">" .
2253 format_search_author($co->{'author_name'}, "author",
2254 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2255 $author) .
2256 "</$tag>";
2259 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2260 sub format_git_diff_header_line {
2261 my $line = shift;
2262 my $diffinfo = shift;
2263 my ($from, $to) = @_;
2265 if ($diffinfo->{'nparents'}) {
2266 # combined diff
2267 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2268 if ($to->{'href'}) {
2269 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2270 esc_path($to->{'file'}));
2271 } else { # file was deleted (no href)
2272 $line .= esc_path($to->{'file'});
2274 } else {
2275 # "ordinary" diff
2276 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2277 if ($from->{'href'}) {
2278 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2279 'a/' . esc_path($from->{'file'}));
2280 } else { # file was added (no href)
2281 $line .= 'a/' . esc_path($from->{'file'});
2283 $line .= ' ';
2284 if ($to->{'href'}) {
2285 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2286 'b/' . esc_path($to->{'file'}));
2287 } else { # file was deleted
2288 $line .= 'b/' . esc_path($to->{'file'});
2292 return "<div class=\"diff header\">$line</div>\n";
2295 # format extended diff header line, before patch itself
2296 sub format_extended_diff_header_line {
2297 my $line = shift;
2298 my $diffinfo = shift;
2299 my ($from, $to) = @_;
2301 # match <path>
2302 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2303 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2304 esc_path($from->{'file'}));
2306 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2307 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2308 esc_path($to->{'file'}));
2310 # match single <mode>
2311 if ($line =~ m/\s(\d{6})$/) {
2312 $line .= '<span class="info"> (' .
2313 file_type_long($1) .
2314 ')</span>';
2316 # match <hash>
2317 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2318 # can match only for combined diff
2319 $line = 'index ';
2320 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2321 if ($from->{'href'}[$i]) {
2322 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2323 -class=>"hash"},
2324 substr($diffinfo->{'from_id'}[$i],0,7));
2325 } else {
2326 $line .= '0' x 7;
2328 # separator
2329 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2331 $line .= '..';
2332 if ($to->{'href'}) {
2333 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2334 substr($diffinfo->{'to_id'},0,7));
2335 } else {
2336 $line .= '0' x 7;
2339 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2340 # can match only for ordinary diff
2341 my ($from_link, $to_link);
2342 if ($from->{'href'}) {
2343 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2344 substr($diffinfo->{'from_id'},0,7));
2345 } else {
2346 $from_link = '0' x 7;
2348 if ($to->{'href'}) {
2349 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2350 substr($diffinfo->{'to_id'},0,7));
2351 } else {
2352 $to_link = '0' x 7;
2354 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2355 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2358 return $line . "<br/>\n";
2361 # format from-file/to-file diff header
2362 sub format_diff_from_to_header {
2363 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2364 my $line;
2365 my $result = '';
2367 $line = $from_line;
2368 #assert($line =~ m/^---/) if DEBUG;
2369 # no extra formatting for "^--- /dev/null"
2370 if (! $diffinfo->{'nparents'}) {
2371 # ordinary (single parent) diff
2372 if ($line =~ m!^--- "?a/!) {
2373 if ($from->{'href'}) {
2374 $line = '--- a/' .
2375 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2376 esc_path($from->{'file'}));
2377 } else {
2378 $line = '--- a/' .
2379 esc_path($from->{'file'});
2382 $result .= qq!<div class="diff from_file">$line</div>\n!;
2384 } else {
2385 # combined diff (merge commit)
2386 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2387 if ($from->{'href'}[$i]) {
2388 $line = '--- ' .
2389 $cgi->a({-href=>href(action=>"blobdiff",
2390 hash_parent=>$diffinfo->{'from_id'}[$i],
2391 hash_parent_base=>$parents[$i],
2392 file_parent=>$from->{'file'}[$i],
2393 hash=>$diffinfo->{'to_id'},
2394 hash_base=>$hash,
2395 file_name=>$to->{'file'}),
2396 -class=>"path",
2397 -title=>"diff" . ($i+1)},
2398 $i+1) .
2399 '/' .
2400 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2401 esc_path($from->{'file'}[$i]));
2402 } else {
2403 $line = '--- /dev/null';
2405 $result .= qq!<div class="diff from_file">$line</div>\n!;
2409 $line = $to_line;
2410 #assert($line =~ m/^\+\+\+/) if DEBUG;
2411 # no extra formatting for "^+++ /dev/null"
2412 if ($line =~ m!^\+\+\+ "?b/!) {
2413 if ($to->{'href'}) {
2414 $line = '+++ b/' .
2415 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2416 esc_path($to->{'file'}));
2417 } else {
2418 $line = '+++ b/' .
2419 esc_path($to->{'file'});
2422 $result .= qq!<div class="diff to_file">$line</div>\n!;
2424 return $result;
2427 # create note for patch simplified by combined diff
2428 sub format_diff_cc_simplified {
2429 my ($diffinfo, @parents) = @_;
2430 my $result = '';
2432 $result .= "<div class=\"diff header\">" .
2433 "diff --cc ";
2434 if (!is_deleted($diffinfo)) {
2435 $result .= $cgi->a({-href => href(action=>"blob",
2436 hash_base=>$hash,
2437 hash=>$diffinfo->{'to_id'},
2438 file_name=>$diffinfo->{'to_file'}),
2439 -class => "path"},
2440 esc_path($diffinfo->{'to_file'}));
2441 } else {
2442 $result .= esc_path($diffinfo->{'to_file'});
2444 $result .= "</div>\n" . # class="diff header"
2445 "<div class=\"diff nodifferences\">" .
2446 "Simple merge" .
2447 "</div>\n"; # class="diff nodifferences"
2449 return $result;
2452 sub diff_line_class {
2453 my ($line, $from, $to) = @_;
2455 # ordinary diff
2456 my $num_sign = 1;
2457 # combined diff
2458 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2459 $num_sign = scalar @{$from->{'href'}};
2462 my @diff_line_classifier = (
2463 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2464 { regexp => qr/^\\/, class => "incomplete" },
2465 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2466 # classifier for context must come before classifier add/rem,
2467 # or we would have to use more complicated regexp, for example
2468 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2469 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2470 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2472 for my $clsfy (@diff_line_classifier) {
2473 return $clsfy->{'class'}
2474 if ($line =~ $clsfy->{'regexp'});
2477 # fallback
2478 return "";
2481 # assumes that $from and $to are defined and correctly filled,
2482 # and that $line holds a line of chunk header for unified diff
2483 sub format_unidiff_chunk_header {
2484 my ($line, $from, $to) = @_;
2486 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2487 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2489 $from_lines = 0 unless defined $from_lines;
2490 $to_lines = 0 unless defined $to_lines;
2492 if ($from->{'href'}) {
2493 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2494 -class=>"list"}, $from_text);
2496 if ($to->{'href'}) {
2497 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2498 -class=>"list"}, $to_text);
2500 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2501 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2502 return $line;
2505 # assumes that $from and $to are defined and correctly filled,
2506 # and that $line holds a line of chunk header for combined diff
2507 sub format_cc_diff_chunk_header {
2508 my ($line, $from, $to) = @_;
2510 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2511 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2513 @from_text = split(' ', $ranges);
2514 for (my $i = 0; $i < @from_text; ++$i) {
2515 ($from_start[$i], $from_nlines[$i]) =
2516 (split(',', substr($from_text[$i], 1)), 0);
2519 $to_text = pop @from_text;
2520 $to_start = pop @from_start;
2521 $to_nlines = pop @from_nlines;
2523 $line = "<span class=\"chunk_info\">$prefix ";
2524 for (my $i = 0; $i < @from_text; ++$i) {
2525 if ($from->{'href'}[$i]) {
2526 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2527 -class=>"list"}, $from_text[$i]);
2528 } else {
2529 $line .= $from_text[$i];
2531 $line .= " ";
2533 if ($to->{'href'}) {
2534 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2535 -class=>"list"}, $to_text);
2536 } else {
2537 $line .= $to_text;
2539 $line .= " $prefix</span>" .
2540 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2541 return $line;
2544 # process patch (diff) line (not to be used for diff headers),
2545 # returning HTML-formatted (but not wrapped) line.
2546 # If the line is passed as a reference, it is treated as HTML and not
2547 # esc_html()'ed.
2548 sub format_diff_line {
2549 my ($line, $diff_class, $from, $to) = @_;
2551 if (ref($line)) {
2552 $line = $$line;
2553 } else {
2554 chomp $line;
2555 $line = untabify($line);
2557 if ($from && $to && $line =~ m/^\@{2} /) {
2558 $line = format_unidiff_chunk_header($line, $from, $to);
2559 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2560 $line = format_cc_diff_chunk_header($line, $from, $to);
2561 } else {
2562 $line = esc_html($line, -nbsp=>1);
2566 my $diff_classes = "diff";
2567 $diff_classes .= " $diff_class" if ($diff_class);
2568 $line = "<div class=\"$diff_classes\">$line</div>\n";
2570 return $line;
2573 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2574 # linked. Pass the hash of the tree/commit to snapshot.
2575 sub format_snapshot_links {
2576 my ($hash) = @_;
2577 my $num_fmts = @snapshot_fmts;
2578 if ($num_fmts > 1) {
2579 # A parenthesized list of links bearing format names.
2580 # e.g. "snapshot (_tar.gz_ _zip_)"
2581 return "snapshot (" . join(' ', map
2582 $cgi->a({
2583 -href => href(
2584 action=>"snapshot",
2585 hash=>$hash,
2586 snapshot_format=>$_
2588 }, $known_snapshot_formats{$_}{'display'})
2589 , @snapshot_fmts) . ")";
2590 } elsif ($num_fmts == 1) {
2591 # A single "snapshot" link whose tooltip bears the format name.
2592 # i.e. "_snapshot_"
2593 my ($fmt) = @snapshot_fmts;
2594 return
2595 $cgi->a({
2596 -href => href(
2597 action=>"snapshot",
2598 hash=>$hash,
2599 snapshot_format=>$fmt
2601 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2602 }, "snapshot");
2603 } else { # $num_fmts == 0
2604 return undef;
2608 ## ......................................................................
2609 ## functions returning values to be passed, perhaps after some
2610 ## transformation, to other functions; e.g. returning arguments to href()
2612 # returns hash to be passed to href to generate gitweb URL
2613 # in -title key it returns description of link
2614 sub get_feed_info {
2615 my $format = shift || 'Atom';
2616 my %res = (action => lc($format));
2617 my $matched_ref = 0;
2619 # feed links are possible only for project views
2620 return unless (defined $project);
2621 # some views should link to OPML, or to generic project feed,
2622 # or don't have specific feed yet (so they should use generic)
2623 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2625 my $branch = undef;
2626 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2627 # (fullname) to differentiate from tag links; this also makes
2628 # possible to detect branch links
2629 for my $ref (get_branch_refs()) {
2630 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2631 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2632 $branch = $1;
2633 $matched_ref = $ref;
2634 last;
2637 # find log type for feed description (title)
2638 my $type = 'log';
2639 if (defined $file_name) {
2640 $type = "history of $file_name";
2641 $type .= "/" if ($action eq 'tree');
2642 $type .= " on '$branch'" if (defined $branch);
2643 } else {
2644 $type = "log of $branch" if (defined $branch);
2647 $res{-title} = $type;
2648 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2649 $res{'file_name'} = $file_name;
2651 return %res;
2654 ## ----------------------------------------------------------------------
2655 ## git utility subroutines, invoking git commands
2657 # returns path to the core git executable and the --git-dir parameter as list
2658 sub git_cmd {
2659 $number_of_git_cmds++;
2660 return $GIT, '--git-dir='.$git_dir;
2663 # quote the given arguments for passing them to the shell
2664 # quote_command("command", "arg 1", "arg with ' and ! characters")
2665 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2666 # Try to avoid using this function wherever possible.
2667 sub quote_command {
2668 return join(' ',
2669 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2672 # get HEAD ref of given project as hash
2673 sub git_get_head_hash {
2674 return git_get_full_hash(shift, 'HEAD');
2677 sub git_get_full_hash {
2678 return git_get_hash(@_);
2681 sub git_get_short_hash {
2682 return git_get_hash(@_, '--short=7');
2685 sub git_get_hash {
2686 my ($project, $hash, @options) = @_;
2687 my $o_git_dir = $git_dir;
2688 my $retval = undef;
2689 $git_dir = "$projectroot/$project";
2690 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2691 '--verify', '-q', @options, $hash) {
2692 $retval = <$fd>;
2693 chomp $retval if defined $retval;
2694 close $fd;
2696 if (defined $o_git_dir) {
2697 $git_dir = $o_git_dir;
2699 return $retval;
2702 # get type of given object
2703 sub git_get_type {
2704 my $hash = shift;
2706 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2707 my $type = <$fd>;
2708 close $fd or return;
2709 chomp $type;
2710 return $type;
2713 # repository configuration
2714 our $config_file = '';
2715 our %config;
2717 # store multiple values for single key as anonymous array reference
2718 # single values stored directly in the hash, not as [ <value> ]
2719 sub hash_set_multi {
2720 my ($hash, $key, $value) = @_;
2722 if (!exists $hash->{$key}) {
2723 $hash->{$key} = $value;
2724 } elsif (!ref $hash->{$key}) {
2725 $hash->{$key} = [ $hash->{$key}, $value ];
2726 } else {
2727 push @{$hash->{$key}}, $value;
2731 # return hash of git project configuration
2732 # optionally limited to some section, e.g. 'gitweb'
2733 sub git_parse_project_config {
2734 my $section_regexp = shift;
2735 my %config;
2737 local $/ = "\0";
2739 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2740 or return;
2742 while (my $keyval = <$fh>) {
2743 chomp $keyval;
2744 my ($key, $value) = split(/\n/, $keyval, 2);
2746 hash_set_multi(\%config, $key, $value)
2747 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2749 close $fh;
2751 return %config;
2754 # convert config value to boolean: 'true' or 'false'
2755 # no value, number > 0, 'true' and 'yes' values are true
2756 # rest of values are treated as false (never as error)
2757 sub config_to_bool {
2758 my $val = shift;
2760 return 1 if !defined $val; # section.key
2762 # strip leading and trailing whitespace
2763 $val =~ s/^\s+//;
2764 $val =~ s/\s+$//;
2766 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2767 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2770 # convert config value to simple decimal number
2771 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2772 # to be multiplied by 1024, 1048576, or 1073741824
2773 sub config_to_int {
2774 my $val = shift;
2776 # strip leading and trailing whitespace
2777 $val =~ s/^\s+//;
2778 $val =~ s/\s+$//;
2780 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2781 $unit = lc($unit);
2782 # unknown unit is treated as 1
2783 return $num * ($unit eq 'g' ? 1073741824 :
2784 $unit eq 'm' ? 1048576 :
2785 $unit eq 'k' ? 1024 : 1);
2787 return $val;
2790 # convert config value to array reference, if needed
2791 sub config_to_multi {
2792 my $val = shift;
2794 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2797 sub git_get_project_config {
2798 my ($key, $type) = @_;
2800 return unless defined $git_dir;
2802 # key sanity check
2803 return unless ($key);
2804 # only subsection, if exists, is case sensitive,
2805 # and not lowercased by 'git config -z -l'
2806 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2807 $lo =~ s/_//g;
2808 $key = join(".", lc($hi), $mi, lc($lo));
2809 return if ($lo =~ /\W/ || $hi =~ /\W/);
2810 } else {
2811 $key = lc($key);
2812 $key =~ s/_//g;
2813 return if ($key =~ /\W/);
2815 $key =~ s/^gitweb\.//;
2817 # type sanity check
2818 if (defined $type) {
2819 $type =~ s/^--//;
2820 $type = undef
2821 unless ($type eq 'bool' || $type eq 'int');
2824 # get config
2825 if (!defined $config_file ||
2826 $config_file ne "$git_dir/config") {
2827 %config = git_parse_project_config('gitweb');
2828 $config_file = "$git_dir/config";
2831 # check if config variable (key) exists
2832 return unless exists $config{"gitweb.$key"};
2834 # ensure given type
2835 if (!defined $type) {
2836 return $config{"gitweb.$key"};
2837 } elsif ($type eq 'bool') {
2838 # backward compatibility: 'git config --bool' returns true/false
2839 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2840 } elsif ($type eq 'int') {
2841 return config_to_int($config{"gitweb.$key"});
2843 return $config{"gitweb.$key"};
2846 # get hash of given path at given ref
2847 sub git_get_hash_by_path {
2848 my $base = shift;
2849 my $path = shift || return undef;
2850 my $type = shift;
2852 $path =~ s,/+$,,;
2854 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2855 or die_error(500, "Open git-ls-tree failed");
2856 my $line = <$fd>;
2857 close $fd or return undef;
2859 if (!defined $line) {
2860 # there is no tree or hash given by $path at $base
2861 return undef;
2864 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2865 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2866 if (defined $type && $type ne $2) {
2867 # type doesn't match
2868 return undef;
2870 return $3;
2873 # get path of entry with given hash at given tree-ish (ref)
2874 # used to get 'from' filename for combined diff (merge commit) for renames
2875 sub git_get_path_by_hash {
2876 my $base = shift || return;
2877 my $hash = shift || return;
2879 local $/ = "\0";
2881 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2882 or return undef;
2883 while (my $line = <$fd>) {
2884 chomp $line;
2886 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2887 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2888 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2889 close $fd;
2890 return $1;
2893 close $fd;
2894 return undef;
2897 ## ......................................................................
2898 ## git utility functions, directly accessing git repository
2900 # get the value of config variable either from file named as the variable
2901 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2902 # configuration variable in the repository config file.
2903 sub git_get_file_or_project_config {
2904 my ($path, $name) = @_;
2906 $git_dir = "$projectroot/$path";
2907 open my $fd, '<', "$git_dir/$name"
2908 or return git_get_project_config($name);
2909 my $conf = <$fd>;
2910 close $fd;
2911 if (defined $conf) {
2912 chomp $conf;
2914 return $conf;
2917 sub git_get_project_description {
2918 my $path = shift;
2919 return git_get_file_or_project_config($path, 'description');
2922 sub git_get_project_category {
2923 my $path = shift;
2924 return git_get_file_or_project_config($path, 'category');
2928 # supported formats:
2929 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2930 # - if its contents is a number, use it as tag weight,
2931 # - otherwise add a tag with weight 1
2932 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2933 # the same value multiple times increases tag weight
2934 # * `gitweb.ctag' multi-valued repo config variable
2935 sub git_get_project_ctags {
2936 my $project = shift;
2937 my $ctags = {};
2939 $git_dir = "$projectroot/$project";
2940 if (opendir my $dh, "$git_dir/ctags") {
2941 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2942 foreach my $tagfile (@files) {
2943 open my $ct, '<', $tagfile
2944 or next;
2945 my $val = <$ct>;
2946 chomp $val if $val;
2947 close $ct;
2949 (my $ctag = $tagfile) =~ s#.*/##;
2950 if ($val =~ /^\d+$/) {
2951 $ctags->{$ctag} = $val;
2952 } else {
2953 $ctags->{$ctag} = 1;
2956 closedir $dh;
2958 } elsif (open my $fh, '<', "$git_dir/ctags") {
2959 while (my $line = <$fh>) {
2960 chomp $line;
2961 $ctags->{$line}++ if $line;
2963 close $fh;
2965 } else {
2966 my $taglist = config_to_multi(git_get_project_config('ctag'));
2967 foreach my $tag (@$taglist) {
2968 $ctags->{$tag}++;
2972 return $ctags;
2975 # return hash, where keys are content tags ('ctags'),
2976 # and values are sum of weights of given tag in every project
2977 sub git_gather_all_ctags {
2978 my $projects = shift;
2979 my $ctags = {};
2981 foreach my $p (@$projects) {
2982 foreach my $ct (keys %{$p->{'ctags'}}) {
2983 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2987 return $ctags;
2990 sub git_populate_project_tagcloud {
2991 my ($ctags, $action) = @_;
2993 # First, merge different-cased tags; tags vote on casing
2994 my %ctags_lc;
2995 foreach (keys %$ctags) {
2996 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2997 if (not $ctags_lc{lc $_}->{topcount}
2998 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2999 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
3000 $ctags_lc{lc $_}->{topname} = $_;
3004 my $cloud;
3005 my $matched = $input_params{'ctag_filter'};
3006 if (eval { require HTML::TagCloud; 1; }) {
3007 $cloud = HTML::TagCloud->new;
3008 foreach my $ctag (sort keys %ctags_lc) {
3009 # Pad the title with spaces so that the cloud looks
3010 # less crammed.
3011 my $title = esc_html($ctags_lc{$ctag}->{topname});
3012 $title =~ s/ /&nbsp;/g;
3013 $title =~ s/^/&nbsp;/g;
3014 $title =~ s/$/&nbsp;/g;
3015 if (defined $matched && $matched eq $ctag) {
3016 $title = qq(<span class="match">$title</span>);
3018 $cloud->add($title, href(-replay=>1, action=>$action, ctag_filter=>$ctag),
3019 $ctags_lc{$ctag}->{count});
3021 } else {
3022 $cloud = {};
3023 foreach my $ctag (keys %ctags_lc) {
3024 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3025 if (defined $matched && $matched eq $ctag) {
3026 $title = qq(<span class="match">$title</span>);
3028 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3029 $cloud->{$ctag}{ctag} =
3030 $cgi->a({-href=>href(-replay=>1, action=>$action, ctag_filter=>$ctag)}, $title);
3033 return $cloud;
3036 sub git_show_project_tagcloud {
3037 my ($cloud, $count) = @_;
3038 if (ref $cloud eq 'HTML::TagCloud') {
3039 return $cloud->html_and_css($count);
3040 } else {
3041 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3042 return
3043 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3044 join (', ', map {
3045 $cloud->{$_}->{'ctag'}
3046 } splice(@tags, 0, $count)) .
3047 '</div>';
3051 sub git_get_project_url_list {
3052 my $path = shift;
3054 $git_dir = "$projectroot/$path";
3055 open my $fd, '<', "$git_dir/cloneurl"
3056 or return wantarray ?
3057 @{ config_to_multi(git_get_project_config('url')) } :
3058 config_to_multi(git_get_project_config('url'));
3059 my @git_project_url_list = map { chomp; $_ } <$fd>;
3060 close $fd;
3062 return wantarray ? @git_project_url_list : \@git_project_url_list;
3065 sub git_get_projects_list {
3066 my $filter = shift || '';
3067 my $paranoid = shift;
3068 my @list;
3070 if (-d $projects_list) {
3071 # search in directory
3072 my $dir = $projects_list;
3073 # remove the trailing "/"
3074 $dir =~ s!/+$!!;
3075 my $pfxlen = length("$dir");
3076 my $pfxdepth = ($dir =~ tr!/!!);
3077 # when filtering, search only given subdirectory
3078 if ($filter && !$paranoid) {
3079 $dir .= "/$filter";
3080 $dir =~ s!/+$!!;
3083 File::Find::find({
3084 follow_fast => 1, # follow symbolic links
3085 follow_skip => 2, # ignore duplicates
3086 dangling_symlinks => 0, # ignore dangling symlinks, silently
3087 wanted => sub {
3088 # global variables
3089 our $project_maxdepth;
3090 our $projectroot;
3091 # skip project-list toplevel, if we get it.
3092 return if (m!^[/.]$!);
3093 # only directories can be git repositories
3094 return unless (-d $_);
3095 # don't traverse too deep (Find is super slow on os x)
3096 # $project_maxdepth excludes depth of $projectroot
3097 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3098 $File::Find::prune = 1;
3099 return;
3102 my $path = substr($File::Find::name, $pfxlen + 1);
3103 # paranoidly only filter here
3104 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3105 next;
3107 # we check related file in $projectroot
3108 if (check_export_ok("$projectroot/$path")) {
3109 push @list, { path => $path };
3110 $File::Find::prune = 1;
3113 }, "$dir");
3115 } elsif (-f $projects_list) {
3116 # read from file(url-encoded):
3117 # 'git%2Fgit.git Linus+Torvalds'
3118 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3119 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3120 open my $fd, '<', $projects_list or return;
3121 PROJECT:
3122 while (my $line = <$fd>) {
3123 chomp $line;
3124 my ($path, $owner) = split ' ', $line;
3125 $path = unescape($path);
3126 $owner = unescape($owner);
3127 if (!defined $path) {
3128 next;
3130 # if $filter is rpovided, check if $path begins with $filter
3131 if ($filter && $path !~ m!^\Q$filter\E/!) {
3132 next;
3134 if (check_export_ok("$projectroot/$path")) {
3135 my $pr = {
3136 path => $path
3138 if ($owner) {
3139 $pr->{'owner'} = to_utf8($owner);
3141 push @list, $pr;
3144 close $fd;
3146 return @list;
3149 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3150 # as side effects it sets 'forks' field to list of forks for forked projects
3151 sub filter_forks_from_projects_list {
3152 my $projects = shift;
3154 my %trie; # prefix tree of directories (path components)
3155 # generate trie out of those directories that might contain forks
3156 foreach my $pr (@$projects) {
3157 my $path = $pr->{'path'};
3158 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3159 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3160 next unless ($path); # skip '.git' repository: tests, git-instaweb
3161 next unless (-d "$projectroot/$path"); # containing directory exists
3162 $pr->{'forks'} = []; # there can be 0 or more forks of project
3164 # add to trie
3165 my @dirs = split('/', $path);
3166 # walk the trie, until either runs out of components or out of trie
3167 my $ref = \%trie;
3168 while (scalar @dirs &&
3169 exists($ref->{$dirs[0]})) {
3170 $ref = $ref->{shift @dirs};
3172 # create rest of trie structure from rest of components
3173 foreach my $dir (@dirs) {
3174 $ref = $ref->{$dir} = {};
3176 # create end marker, store $pr as a data
3177 $ref->{''} = $pr if (!exists $ref->{''});
3180 # filter out forks, by finding shortest prefix match for paths
3181 my @filtered;
3182 PROJECT:
3183 foreach my $pr (@$projects) {
3184 # trie lookup
3185 my $ref = \%trie;
3186 DIR:
3187 foreach my $dir (split('/', $pr->{'path'})) {
3188 if (exists $ref->{''}) {
3189 # found [shortest] prefix, is a fork - skip it
3190 push @{$ref->{''}{'forks'}}, $pr;
3191 next PROJECT;
3193 if (!exists $ref->{$dir}) {
3194 # not in trie, cannot have prefix, not a fork
3195 push @filtered, $pr;
3196 next PROJECT;
3198 # If the dir is there, we just walk one step down the trie.
3199 $ref = $ref->{$dir};
3201 # we ran out of trie
3202 # (shouldn't happen: it's either no match, or end marker)
3203 push @filtered, $pr;
3206 return @filtered;
3209 # note: fill_project_list_info must be run first,
3210 # for 'descr_long' and 'ctags' to be filled
3211 sub search_projects_list {
3212 my ($projlist, %opts) = @_;
3213 my $tagfilter = $opts{'tagfilter'};
3214 my $search_re = $opts{'search_regexp'};
3216 return @$projlist
3217 unless ($tagfilter || $search_re);
3219 # searching projects require filling to be run before it;
3220 fill_project_list_info($projlist,
3221 $tagfilter ? 'ctags' : (),
3222 $search_re ? ('path', 'descr') : ());
3223 my @projects;
3224 PROJECT:
3225 foreach my $pr (@$projlist) {
3227 if ($tagfilter) {
3228 next unless ref($pr->{'ctags'}) eq 'HASH';
3229 next unless
3230 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3233 if ($search_re) {
3234 next unless
3235 $pr->{'path'} =~ /$search_re/ ||
3236 $pr->{'descr_long'} =~ /$search_re/;
3239 push @projects, $pr;
3242 return @projects;
3245 our $gitweb_project_owner = undef;
3246 sub git_get_project_list_from_file {
3248 return if (defined $gitweb_project_owner);
3250 $gitweb_project_owner = {};
3251 # read from file (url-encoded):
3252 # 'git%2Fgit.git Linus+Torvalds'
3253 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3254 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3255 if (-f $projects_list) {
3256 open(my $fd, '<', $projects_list);
3257 while (my $line = <$fd>) {
3258 chomp $line;
3259 my ($pr, $ow) = split ' ', $line;
3260 $pr = unescape($pr);
3261 $ow = unescape($ow);
3262 $gitweb_project_owner->{$pr} = to_utf8($ow);
3264 close $fd;
3268 sub git_get_project_owner {
3269 my $project = shift;
3270 my $owner;
3272 return undef unless $project;
3273 $git_dir = "$projectroot/$project";
3275 if (!defined $gitweb_project_owner) {
3276 git_get_project_list_from_file();
3279 if (exists $gitweb_project_owner->{$project}) {
3280 $owner = $gitweb_project_owner->{$project};
3282 if (!defined $owner){
3283 $owner = git_get_project_config('owner');
3285 if (!defined $owner) {
3286 $owner = get_file_owner("$git_dir");
3289 return $owner;
3292 sub git_get_last_activity {
3293 my ($path) = @_;
3294 my $fd;
3296 $git_dir = "$projectroot/$path";
3297 open($fd, "-|", git_cmd(), 'for-each-ref',
3298 '--format=%(committer)',
3299 '--sort=-committerdate',
3300 '--count=1',
3301 map { "refs/$_" } get_branch_refs ()) or return;
3302 my $most_recent = <$fd>;
3303 close $fd or return;
3304 if (defined $most_recent &&
3305 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3306 my $timestamp = $1;
3307 my $age = time - $timestamp;
3308 return ($age, age_string($age));
3310 return (undef, undef);
3313 # Implementation note: when a single remote is wanted, we cannot use 'git
3314 # remote show -n' because that command always work (assuming it's a remote URL
3315 # if it's not defined), and we cannot use 'git remote show' because that would
3316 # try to make a network roundtrip. So the only way to find if that particular
3317 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3318 # and when we find what we want.
3319 sub git_get_remotes_list {
3320 my $wanted = shift;
3321 my %remotes = ();
3323 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3324 return unless $fd;
3325 while (my $remote = <$fd>) {
3326 chomp $remote;
3327 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3328 next if $wanted and not $remote eq $wanted;
3329 my ($url, $key) = ($1, $2);
3331 $remotes{$remote} ||= { 'heads' => () };
3332 $remotes{$remote}{$key} = $url;
3334 close $fd or return;
3335 return wantarray ? %remotes : \%remotes;
3338 # Takes a hash of remotes as first parameter and fills it by adding the
3339 # available remote heads for each of the indicated remotes.
3340 sub fill_remote_heads {
3341 my $remotes = shift;
3342 my @heads = map { "remotes/$_" } keys %$remotes;
3343 my @remoteheads = git_get_heads_list(undef, @heads);
3344 foreach my $remote (keys %$remotes) {
3345 $remotes->{$remote}{'heads'} = [ grep {
3346 $_->{'name'} =~ s!^$remote/!!
3347 } @remoteheads ];
3351 sub git_get_references {
3352 my $type = shift || "";
3353 my %refs;
3354 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3355 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3356 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3357 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3358 or return;
3360 while (my $line = <$fd>) {
3361 chomp $line;
3362 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3363 if (defined $refs{$1}) {
3364 push @{$refs{$1}}, $2;
3365 } else {
3366 $refs{$1} = [ $2 ];
3370 close $fd or return;
3371 return \%refs;
3374 sub git_get_rev_name_tags {
3375 my $hash = shift || return undef;
3377 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3378 or return;
3379 my $name_rev = <$fd>;
3380 close $fd;
3382 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3383 return $1;
3384 } else {
3385 # catches also '$hash undefined' output
3386 return undef;
3390 ## ----------------------------------------------------------------------
3391 ## parse to hash functions
3393 sub parse_date {
3394 my $epoch = shift;
3395 my $tz = shift || "-0000";
3397 my %date;
3398 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3399 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3400 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3401 $date{'hour'} = $hour;
3402 $date{'minute'} = $min;
3403 $date{'mday'} = $mday;
3404 $date{'day'} = $days[$wday];
3405 $date{'month'} = $months[$mon];
3406 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3407 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3408 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3409 $mday, $months[$mon], $hour ,$min;
3410 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3411 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3413 my ($tz_sign, $tz_hour, $tz_min) =
3414 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3415 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3416 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3417 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3418 $date{'hour_local'} = $hour;
3419 $date{'minute_local'} = $min;
3420 $date{'tz_local'} = $tz;
3421 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3422 1900+$year, $mon+1, $mday,
3423 $hour, $min, $sec, $tz);
3424 return %date;
3427 sub parse_tag {
3428 my $tag_id = shift;
3429 my %tag;
3430 my @comment;
3432 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3433 $tag{'id'} = $tag_id;
3434 while (my $line = <$fd>) {
3435 chomp $line;
3436 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3437 $tag{'object'} = $1;
3438 } elsif ($line =~ m/^type (.+)$/) {
3439 $tag{'type'} = $1;
3440 } elsif ($line =~ m/^tag (.+)$/) {
3441 $tag{'name'} = $1;
3442 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3443 $tag{'author'} = $1;
3444 $tag{'author_epoch'} = $2;
3445 $tag{'author_tz'} = $3;
3446 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3447 $tag{'author_name'} = $1;
3448 $tag{'author_email'} = $2;
3449 } else {
3450 $tag{'author_name'} = $tag{'author'};
3452 } elsif ($line =~ m/--BEGIN/) {
3453 push @comment, $line;
3454 last;
3455 } elsif ($line eq "") {
3456 last;
3459 push @comment, <$fd>;
3460 $tag{'comment'} = \@comment;
3461 close $fd or return;
3462 if (!defined $tag{'name'}) {
3463 return
3465 return %tag
3468 sub parse_commit_text {
3469 my ($commit_text, $withparents) = @_;
3470 my @commit_lines = split '\n', $commit_text;
3471 my %co;
3473 pop @commit_lines; # Remove '\0'
3475 if (! @commit_lines) {
3476 return;
3479 my $header = shift @commit_lines;
3480 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3481 return;
3483 ($co{'id'}, my @parents) = split ' ', $header;
3484 while (my $line = shift @commit_lines) {
3485 last if $line eq "\n";
3486 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3487 $co{'tree'} = $1;
3488 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3489 push @parents, $1;
3490 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3491 $co{'author'} = to_utf8($1);
3492 $co{'author_epoch'} = $2;
3493 $co{'author_tz'} = $3;
3494 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3495 $co{'author_name'} = $1;
3496 $co{'author_email'} = $2;
3497 } else {
3498 $co{'author_name'} = $co{'author'};
3500 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3501 $co{'committer'} = to_utf8($1);
3502 $co{'committer_epoch'} = $2;
3503 $co{'committer_tz'} = $3;
3504 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3505 $co{'committer_name'} = $1;
3506 $co{'committer_email'} = $2;
3507 } else {
3508 $co{'committer_name'} = $co{'committer'};
3512 if (!defined $co{'tree'}) {
3513 return;
3515 $co{'parents'} = \@parents;
3516 $co{'parent'} = $parents[0];
3518 foreach my $title (@commit_lines) {
3519 $title =~ s/^ //;
3520 if ($title ne "") {
3521 $co{'title'} = chop_str($title, 80, 5);
3522 # remove leading stuff of merges to make the interesting part visible
3523 if (length($title) > 50) {
3524 $title =~ s/^Automatic //;
3525 $title =~ s/^merge (of|with) /Merge ... /i;
3526 if (length($title) > 50) {
3527 $title =~ s/(http|rsync):\/\///;
3529 if (length($title) > 50) {
3530 $title =~ s/(master|www|rsync)\.//;
3532 if (length($title) > 50) {
3533 $title =~ s/kernel.org:?//;
3535 if (length($title) > 50) {
3536 $title =~ s/\/pub\/scm//;
3539 $co{'title_short'} = chop_str($title, 50, 5);
3540 last;
3543 if (! defined $co{'title'} || $co{'title'} eq "") {
3544 $co{'title'} = $co{'title_short'} = '(no commit message)';
3546 # remove added spaces
3547 foreach my $line (@commit_lines) {
3548 $line =~ s/^ //;
3550 $co{'comment'} = \@commit_lines;
3552 my $age = time - $co{'committer_epoch'};
3553 $co{'age'} = $age;
3554 $co{'age_string'} = age_string($age);
3555 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3556 if ($age > 60*60*24*7*2) {
3557 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3558 $co{'age_string_age'} = $co{'age_string'};
3559 } else {
3560 $co{'age_string_date'} = $co{'age_string'};
3561 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3563 return %co;
3566 sub parse_commit {
3567 my ($commit_id) = @_;
3568 my %co;
3570 local $/ = "\0";
3572 open my $fd, "-|", git_cmd(), "rev-list",
3573 "--parents",
3574 "--header",
3575 "--max-count=1",
3576 $commit_id,
3577 "--",
3578 or die_error(500, "Open git-rev-list failed");
3579 %co = parse_commit_text(<$fd>, 1);
3580 close $fd;
3582 return %co;
3585 sub parse_commits {
3586 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3587 my @cos;
3589 $maxcount ||= 1;
3590 $skip ||= 0;
3592 local $/ = "\0";
3594 open my $fd, "-|", git_cmd(), "rev-list",
3595 "--header",
3596 @args,
3597 ("--max-count=" . $maxcount),
3598 ("--skip=" . $skip),
3599 @extra_options,
3600 $commit_id,
3601 "--",
3602 ($filename ? ($filename) : ())
3603 or die_error(500, "Open git-rev-list failed");
3604 while (my $line = <$fd>) {
3605 my %co = parse_commit_text($line);
3606 push @cos, \%co;
3608 close $fd;
3610 return wantarray ? @cos : \@cos;
3613 # parse line of git-diff-tree "raw" output
3614 sub parse_difftree_raw_line {
3615 my $line = shift;
3616 my %res;
3618 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3619 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3620 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3621 $res{'from_mode'} = $1;
3622 $res{'to_mode'} = $2;
3623 $res{'from_id'} = $3;
3624 $res{'to_id'} = $4;
3625 $res{'status'} = $5;
3626 $res{'similarity'} = $6;
3627 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3628 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3629 } else {
3630 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3633 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3634 # combined diff (for merge commit)
3635 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3636 $res{'nparents'} = length($1);
3637 $res{'from_mode'} = [ split(' ', $2) ];
3638 $res{'to_mode'} = pop @{$res{'from_mode'}};
3639 $res{'from_id'} = [ split(' ', $3) ];
3640 $res{'to_id'} = pop @{$res{'from_id'}};
3641 $res{'status'} = [ split('', $4) ];
3642 $res{'to_file'} = unquote($5);
3644 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3645 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3646 $res{'commit'} = $1;
3649 return wantarray ? %res : \%res;
3652 # wrapper: return parsed line of git-diff-tree "raw" output
3653 # (the argument might be raw line, or parsed info)
3654 sub parsed_difftree_line {
3655 my $line_or_ref = shift;
3657 if (ref($line_or_ref) eq "HASH") {
3658 # pre-parsed (or generated by hand)
3659 return $line_or_ref;
3660 } else {
3661 return parse_difftree_raw_line($line_or_ref);
3665 # parse line of git-ls-tree output
3666 sub parse_ls_tree_line {
3667 my $line = shift;
3668 my %opts = @_;
3669 my %res;
3671 if ($opts{'-l'}) {
3672 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3673 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3675 $res{'mode'} = $1;
3676 $res{'type'} = $2;
3677 $res{'hash'} = $3;
3678 $res{'size'} = $4;
3679 if ($opts{'-z'}) {
3680 $res{'name'} = $5;
3681 } else {
3682 $res{'name'} = unquote($5);
3684 } else {
3685 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3686 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3688 $res{'mode'} = $1;
3689 $res{'type'} = $2;
3690 $res{'hash'} = $3;
3691 if ($opts{'-z'}) {
3692 $res{'name'} = $4;
3693 } else {
3694 $res{'name'} = unquote($4);
3698 return wantarray ? %res : \%res;
3701 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3702 sub parse_from_to_diffinfo {
3703 my ($diffinfo, $from, $to, @parents) = @_;
3705 if ($diffinfo->{'nparents'}) {
3706 # combined diff
3707 $from->{'file'} = [];
3708 $from->{'href'} = [];
3709 fill_from_file_info($diffinfo, @parents)
3710 unless exists $diffinfo->{'from_file'};
3711 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3712 $from->{'file'}[$i] =
3713 defined $diffinfo->{'from_file'}[$i] ?
3714 $diffinfo->{'from_file'}[$i] :
3715 $diffinfo->{'to_file'};
3716 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3717 $from->{'href'}[$i] = href(action=>"blob",
3718 hash_base=>$parents[$i],
3719 hash=>$diffinfo->{'from_id'}[$i],
3720 file_name=>$from->{'file'}[$i]);
3721 } else {
3722 $from->{'href'}[$i] = undef;
3725 } else {
3726 # ordinary (not combined) diff
3727 $from->{'file'} = $diffinfo->{'from_file'};
3728 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3729 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3730 hash=>$diffinfo->{'from_id'},
3731 file_name=>$from->{'file'});
3732 } else {
3733 delete $from->{'href'};
3737 $to->{'file'} = $diffinfo->{'to_file'};
3738 if (!is_deleted($diffinfo)) { # file exists in result
3739 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3740 hash=>$diffinfo->{'to_id'},
3741 file_name=>$to->{'file'});
3742 } else {
3743 delete $to->{'href'};
3747 ## ......................................................................
3748 ## parse to array of hashes functions
3750 sub git_get_heads_list {
3751 my ($limit, @classes) = @_;
3752 @classes = get_branch_refs() unless @classes;
3753 my @patterns = map { "refs/$_" } @classes;
3754 my @headslist;
3756 open my $fd, '-|', git_cmd(), 'for-each-ref',
3757 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3758 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3759 @patterns
3760 or return;
3761 while (my $line = <$fd>) {
3762 my %ref_item;
3764 chomp $line;
3765 my ($refinfo, $committerinfo) = split(/\0/, $line);
3766 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3767 my ($committer, $epoch, $tz) =
3768 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3769 $ref_item{'fullname'} = $name;
3770 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3771 $name =~ s!^refs/($strip_refs|remotes)/!!;
3772 $ref_item{'name'} = $name;
3773 # for refs neither in 'heads' nor 'remotes' we want to
3774 # show their ref dir
3775 my $ref_dir = (defined $1) ? $1 : '';
3776 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3777 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3780 $ref_item{'id'} = $hash;
3781 $ref_item{'title'} = $title || '(no commit message)';
3782 $ref_item{'epoch'} = $epoch;
3783 if ($epoch) {
3784 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3785 } else {
3786 $ref_item{'age'} = "unknown";
3789 push @headslist, \%ref_item;
3791 close $fd;
3793 return wantarray ? @headslist : \@headslist;
3796 sub git_get_tags_list {
3797 my $limit = shift;
3798 my @tagslist;
3800 open my $fd, '-|', git_cmd(), 'for-each-ref',
3801 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3802 '--format=%(objectname) %(objecttype) %(refname) '.
3803 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3804 'refs/tags'
3805 or return;
3806 while (my $line = <$fd>) {
3807 my %ref_item;
3809 chomp $line;
3810 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3811 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3812 my ($creator, $epoch, $tz) =
3813 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3814 $ref_item{'fullname'} = $name;
3815 $name =~ s!^refs/tags/!!;
3817 $ref_item{'type'} = $type;
3818 $ref_item{'id'} = $id;
3819 $ref_item{'name'} = $name;
3820 if ($type eq "tag") {
3821 $ref_item{'subject'} = $title;
3822 $ref_item{'reftype'} = $reftype;
3823 $ref_item{'refid'} = $refid;
3824 } else {
3825 $ref_item{'reftype'} = $type;
3826 $ref_item{'refid'} = $id;
3829 if ($type eq "tag" || $type eq "commit") {
3830 $ref_item{'epoch'} = $epoch;
3831 if ($epoch) {
3832 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3833 } else {
3834 $ref_item{'age'} = "unknown";
3838 push @tagslist, \%ref_item;
3840 close $fd;
3842 return wantarray ? @tagslist : \@tagslist;
3845 ## ----------------------------------------------------------------------
3846 ## filesystem-related functions
3848 sub get_file_owner {
3849 my $path = shift;
3851 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3852 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3853 if (!defined $gcos) {
3854 return undef;
3856 my $owner = $gcos;
3857 $owner =~ s/[,;].*$//;
3858 return to_utf8($owner);
3861 # assume that file exists
3862 sub insert_file {
3863 my $filename = shift;
3865 open my $fd, '<', $filename;
3866 print map { to_utf8($_) } <$fd>;
3867 close $fd;
3870 ## ......................................................................
3871 ## mimetype related functions
3873 sub mimetype_guess_file {
3874 my $filename = shift;
3875 my $mimemap = shift;
3876 -r $mimemap or return undef;
3878 my %mimemap;
3879 open(my $mh, '<', $mimemap) or return undef;
3880 while (<$mh>) {
3881 next if m/^#/; # skip comments
3882 my ($mimetype, @exts) = split(/\s+/);
3883 foreach my $ext (@exts) {
3884 $mimemap{$ext} = $mimetype;
3887 close($mh);
3889 $filename =~ /\.([^.]*)$/;
3890 return $mimemap{$1};
3893 sub mimetype_guess {
3894 my $filename = shift;
3895 my $mime;
3896 $filename =~ /\./ or return undef;
3898 if ($mimetypes_file) {
3899 my $file = $mimetypes_file;
3900 if ($file !~ m!^/!) { # if it is relative path
3901 # it is relative to project
3902 $file = "$projectroot/$project/$file";
3904 $mime = mimetype_guess_file($filename, $file);
3906 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3907 return $mime;
3910 sub blob_mimetype {
3911 my $fd = shift;
3912 my $filename = shift;
3914 if ($filename) {
3915 my $mime = mimetype_guess($filename);
3916 $mime and return $mime;
3919 # just in case
3920 return $default_blob_plain_mimetype unless $fd;
3922 if (-T $fd) {
3923 return 'text/plain';
3924 } elsif (! $filename) {
3925 return 'application/octet-stream';
3926 } elsif ($filename =~ m/\.png$/i) {
3927 return 'image/png';
3928 } elsif ($filename =~ m/\.gif$/i) {
3929 return 'image/gif';
3930 } elsif ($filename =~ m/\.jpe?g$/i) {
3931 return 'image/jpeg';
3932 } else {
3933 return 'application/octet-stream';
3937 sub blob_contenttype {
3938 my ($fd, $file_name, $type) = @_;
3940 $type ||= blob_mimetype($fd, $file_name);
3941 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3942 $type .= "; charset=$default_text_plain_charset";
3945 return $type;
3948 # guess file syntax for syntax highlighting; return undef if no highlighting
3949 # the name of syntax can (in the future) depend on syntax highlighter used
3950 sub guess_file_syntax {
3951 my ($highlight, $mimetype, $file_name) = @_;
3952 return undef unless ($highlight && defined $file_name);
3953 my $basename = basename($file_name, '.in');
3954 return $highlight_basename{$basename}
3955 if exists $highlight_basename{$basename};
3957 $basename =~ /\.([^.]*)$/;
3958 my $ext = $1 or return undef;
3959 return $highlight_ext{$ext}
3960 if exists $highlight_ext{$ext};
3962 return undef;
3965 # run highlighter and return FD of its output,
3966 # or return original FD if no highlighting
3967 sub run_highlighter {
3968 my ($fd, $highlight, $syntax) = @_;
3969 return $fd unless ($highlight && defined $syntax);
3971 close $fd;
3972 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3973 quote_command($highlight_bin).
3974 " --replace-tabs=8 --fragment --syntax $syntax |"
3975 or die_error(500, "Couldn't open file or run syntax highlighter");
3976 return $fd;
3979 ## ======================================================================
3980 ## functions printing HTML: header, footer, error page
3982 sub get_page_title {
3983 my $title = to_utf8($site_name);
3985 unless (defined $project) {
3986 if (defined $project_filter) {
3987 $title .= " - projects in '" . esc_path($project_filter) . "'";
3989 return $title;
3991 $title .= " - " . to_utf8($project);
3993 return $title unless (defined $action);
3994 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3996 return $title unless (defined $file_name);
3997 $title .= " - " . esc_path($file_name);
3998 if ($action eq "tree" && $file_name !~ m|/$|) {
3999 $title .= "/";
4002 return $title;
4005 sub get_content_type_html {
4006 # require explicit support from the UA if we are to send the page as
4007 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4008 # we have to do this because MSIE sometimes globs '*/*', pretending to
4009 # support xhtml+xml but choking when it gets what it asked for.
4010 if (defined $cgi->http('HTTP_ACCEPT') &&
4011 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4012 $cgi->Accept('application/xhtml+xml') != 0) {
4013 return 'application/xhtml+xml';
4014 } else {
4015 return 'text/html';
4019 sub print_feed_meta {
4020 if (defined $project) {
4021 my %href_params = get_feed_info();
4022 if (!exists $href_params{'-title'}) {
4023 $href_params{'-title'} = 'log';
4026 foreach my $format (qw(RSS Atom)) {
4027 my $type = lc($format);
4028 my %link_attr = (
4029 '-rel' => 'alternate',
4030 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4031 '-type' => "application/$type+xml"
4034 $href_params{'extra_options'} = undef;
4035 $href_params{'action'} = $type;
4036 $link_attr{'-href'} = href(%href_params);
4037 print "<link ".
4038 "rel=\"$link_attr{'-rel'}\" ".
4039 "title=\"$link_attr{'-title'}\" ".
4040 "href=\"$link_attr{'-href'}\" ".
4041 "type=\"$link_attr{'-type'}\" ".
4042 "/>\n";
4044 $href_params{'extra_options'} = '--no-merges';
4045 $link_attr{'-href'} = href(%href_params);
4046 $link_attr{'-title'} .= ' (no merges)';
4047 print "<link ".
4048 "rel=\"$link_attr{'-rel'}\" ".
4049 "title=\"$link_attr{'-title'}\" ".
4050 "href=\"$link_attr{'-href'}\" ".
4051 "type=\"$link_attr{'-type'}\" ".
4052 "/>\n";
4055 } else {
4056 printf('<link rel="alternate" title="%s projects list" '.
4057 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4058 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4059 printf('<link rel="alternate" title="%s projects feeds" '.
4060 'href="%s" type="text/x-opml" />'."\n",
4061 esc_attr($site_name), href(project=>undef, action=>"opml"));
4065 sub print_header_links {
4066 my $status = shift;
4068 # print out each stylesheet that exist, providing backwards capability
4069 # for those people who defined $stylesheet in a config file
4070 if (defined $stylesheet) {
4071 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4072 } else {
4073 foreach my $stylesheet (@stylesheets) {
4074 next unless $stylesheet;
4075 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4078 print_feed_meta()
4079 if ($status eq '200 OK');
4080 if (defined $favicon) {
4081 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4085 sub print_nav_breadcrumbs_path {
4086 my $dirprefix = undef;
4087 while (my $part = shift) {
4088 $dirprefix .= "/" if defined $dirprefix;
4089 $dirprefix .= $part;
4090 print $cgi->a({-href => href(project => undef,
4091 project_filter => $dirprefix,
4092 action => "project_list")},
4093 esc_html($part)) . " / ";
4097 sub print_nav_breadcrumbs {
4098 my %opts = @_;
4100 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4101 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4103 if (defined $project) {
4104 my @dirname = split '/', $project;
4105 my $projectbasename = pop @dirname;
4106 print_nav_breadcrumbs_path(@dirname);
4107 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4108 if (defined $action) {
4109 my $action_print = $action ;
4110 if (defined $opts{-action_extra}) {
4111 $action_print = $cgi->a({-href => href(action=>$action)},
4112 $action);
4114 print " / $action_print";
4116 if (defined $opts{-action_extra}) {
4117 print " / $opts{-action_extra}";
4119 print "\n";
4120 } elsif (defined $project_filter) {
4121 print_nav_breadcrumbs_path(split '/', $project_filter);
4125 sub print_search_form {
4126 if (!defined $searchtext) {
4127 $searchtext = "";
4129 my $search_hash;
4130 if (defined $hash_base) {
4131 $search_hash = $hash_base;
4132 } elsif (defined $hash) {
4133 $search_hash = $hash;
4134 } else {
4135 $search_hash = "HEAD";
4137 my $action = $my_uri;
4138 my $use_pathinfo = gitweb_check_feature('pathinfo');
4139 if ($use_pathinfo) {
4140 $action .= "/".esc_url($project);
4142 print $cgi->start_form(-method => "get", -action => $action) .
4143 "<div class=\"search\">\n" .
4144 (!$use_pathinfo &&
4145 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4146 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4147 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4148 $cgi->popup_menu(-name => 'st', -default => 'commit',
4149 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4150 " " . $cgi->a({-href => href(action=>"search_help"),
4151 -title => "search help" }, "?") . " search:\n",
4152 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4153 "<span title=\"Extended regular expression\">" .
4154 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4155 -checked => $search_use_regexp) .
4156 "</span>" .
4157 "</div>" .
4158 $cgi->end_form() . "\n";
4161 sub git_header_html {
4162 my $status = shift || "200 OK";
4163 my $expires = shift;
4164 my %opts = @_;
4166 my $title = get_page_title();
4167 my $content_type = get_content_type_html();
4168 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4169 -status=> $status, -expires => $expires)
4170 unless ($opts{'-no_http_header'});
4171 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4172 print <<EOF;
4173 <?xml version="1.0" encoding="utf-8"?>
4174 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4175 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4176 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4177 <!-- git core binaries version $git_version -->
4178 <head>
4179 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4180 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4181 <meta name="robots" content="index, nofollow"/>
4182 <title>$title</title>
4184 # the stylesheet, favicon etc urls won't work correctly with path_info
4185 # unless we set the appropriate base URL
4186 if ($ENV{'PATH_INFO'}) {
4187 print "<base href=\"".esc_url($base_url)."\" />\n";
4189 print_header_links($status);
4191 if (defined $site_html_head_string) {
4192 print to_utf8($site_html_head_string);
4195 print "</head>\n" .
4196 "<body>\n";
4198 if (defined $site_header && -f $site_header) {
4199 insert_file($site_header);
4202 print "<div class=\"page_header\">\n";
4203 if (defined $logo) {
4204 print $cgi->a({-href => esc_url($logo_url),
4205 -title => $logo_label},
4206 $cgi->img({-src => esc_url($logo),
4207 -width => 72, -height => 27,
4208 -alt => "git",
4209 -class => "logo"}));
4211 print_nav_breadcrumbs(%opts);
4212 print "</div>\n";
4214 my $have_search = gitweb_check_feature('search');
4215 if (defined $project && $have_search) {
4216 print_search_form();
4220 sub git_footer_html {
4221 my $feed_class = 'rss_logo';
4223 print "<div class=\"page_footer\">\n";
4224 if (defined $project) {
4225 my $descr = git_get_project_description($project);
4226 if (defined $descr) {
4227 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4230 my %href_params = get_feed_info();
4231 if (!%href_params) {
4232 $feed_class .= ' generic';
4234 $href_params{'-title'} ||= 'log';
4236 foreach my $format (qw(RSS Atom)) {
4237 $href_params{'action'} = lc($format);
4238 print $cgi->a({-href => href(%href_params),
4239 -title => "$href_params{'-title'} $format feed",
4240 -class => $feed_class}, $format)."\n";
4243 } else {
4244 print $cgi->a({-href => href(project=>undef, action=>"opml",
4245 project_filter => $project_filter),
4246 -class => $feed_class}, "OPML") . " ";
4247 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4248 project_filter => $project_filter),
4249 -class => $feed_class}, "TXT") . "\n";
4251 print "</div>\n"; # class="page_footer"
4253 if (defined $t0 && gitweb_check_feature('timed')) {
4254 print "<div id=\"generating_info\">\n";
4255 print 'This page took '.
4256 '<span id="generating_time" class="time_span">'.
4257 tv_interval($t0, [ gettimeofday() ]).
4258 ' seconds </span>'.
4259 ' and '.
4260 '<span id="generating_cmd">'.
4261 $number_of_git_cmds.
4262 '</span> git commands '.
4263 " to generate.\n";
4264 print "</div>\n"; # class="page_footer"
4267 if (defined $site_footer && -f $site_footer) {
4268 insert_file($site_footer);
4271 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4272 if (defined $action &&
4273 $action eq 'blame_incremental') {
4274 print qq!<script type="text/javascript">\n!.
4275 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4276 qq! "!. href() .qq!");\n!.
4277 qq!</script>\n!;
4278 } else {
4279 my ($jstimezone, $tz_cookie, $datetime_class) =
4280 gitweb_get_feature('javascript-timezone');
4282 print qq!<script type="text/javascript">\n!.
4283 qq!window.onload = function () {\n!;
4284 if (gitweb_check_feature('javascript-actions')) {
4285 print qq! fixLinks();\n!;
4287 if ($jstimezone && $tz_cookie && $datetime_class) {
4288 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4289 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4291 print qq!};\n!.
4292 qq!</script>\n!;
4295 print "</body>\n" .
4296 "</html>";
4299 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4300 # Example: die_error(404, 'Hash not found')
4301 # By convention, use the following status codes (as defined in RFC 2616):
4302 # 400: Invalid or missing CGI parameters, or
4303 # requested object exists but has wrong type.
4304 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4305 # this server or project.
4306 # 404: Requested object/revision/project doesn't exist.
4307 # 500: The server isn't configured properly, or
4308 # an internal error occurred (e.g. failed assertions caused by bugs), or
4309 # an unknown error occurred (e.g. the git binary died unexpectedly).
4310 # 503: The server is currently unavailable (because it is overloaded,
4311 # or down for maintenance). Generally, this is a temporary state.
4312 sub die_error {
4313 my $status = shift || 500;
4314 my $error = esc_html(shift) || "Internal Server Error";
4315 my $extra = shift;
4316 my %opts = @_;
4318 my %http_responses = (
4319 400 => '400 Bad Request',
4320 403 => '403 Forbidden',
4321 404 => '404 Not Found',
4322 500 => '500 Internal Server Error',
4323 503 => '503 Service Unavailable',
4325 git_header_html($http_responses{$status}, undef, %opts);
4326 print <<EOF;
4327 <div class="page_body">
4328 <br /><br />
4329 $status - $error
4330 <br />
4332 if (defined $extra) {
4333 print "<hr />\n" .
4334 "$extra\n";
4336 print "</div>\n";
4338 git_footer_html();
4339 goto DONE_GITWEB
4340 unless ($opts{'-error_handler'});
4343 ## ----------------------------------------------------------------------
4344 ## functions printing or outputting HTML: navigation
4346 sub git_print_page_nav {
4347 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4348 $extra = '' if !defined $extra; # pager or formats
4350 my @navs = qw(summary shortlog log commit commitdiff tree);
4351 if ($suppress) {
4352 @navs = grep { $_ ne $suppress } @navs;
4355 my %arg = map { $_ => {action=>$_} } @navs;
4356 if (defined $head) {
4357 for (qw(commit commitdiff)) {
4358 $arg{$_}{'hash'} = $head;
4360 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4361 for (qw(shortlog log)) {
4362 $arg{$_}{'hash'} = $head;
4367 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4368 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4370 my @actions = gitweb_get_feature('actions');
4371 my %repl = (
4372 '%' => '%',
4373 'n' => $project, # project name
4374 'f' => $git_dir, # project path within filesystem
4375 'h' => $treehead || '', # current hash ('h' parameter)
4376 'b' => $treebase || '', # hash base ('hb' parameter)
4378 while (@actions) {
4379 my ($label, $link, $pos) = splice(@actions,0,3);
4380 # insert
4381 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4382 # munch munch
4383 $link =~ s/%([%nfhb])/$repl{$1}/g;
4384 $arg{$label}{'_href'} = $link;
4387 print "<div class=\"page_nav\">\n" .
4388 (join " | ",
4389 map { $_ eq $current ?
4390 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4391 } @navs);
4392 print "<br/>\n$extra<br/>\n" .
4393 "</div>\n";
4396 # returns a submenu for the nagivation of the refs views (tags, heads,
4397 # remotes) with the current view disabled and the remotes view only
4398 # available if the feature is enabled
4399 sub format_ref_views {
4400 my ($current) = @_;
4401 my @ref_views = qw{tags heads};
4402 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4403 return join " | ", map {
4404 $_ eq $current ? $_ :
4405 $cgi->a({-href => href(action=>$_)}, $_)
4406 } @ref_views
4409 sub format_paging_nav {
4410 my ($action, $page, $has_next_link) = @_;
4411 my $paging_nav;
4414 if ($page > 0) {
4415 $paging_nav .=
4416 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4417 " &sdot; " .
4418 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4419 -accesskey => "p", -title => "Alt-p"}, "prev");
4420 } else {
4421 $paging_nav .= "first &sdot; prev";
4424 if ($has_next_link) {
4425 $paging_nav .= " &sdot; " .
4426 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4427 -accesskey => "n", -title => "Alt-n"}, "next");
4428 } else {
4429 $paging_nav .= " &sdot; next";
4432 return $paging_nav;
4435 ## ......................................................................
4436 ## functions printing or outputting HTML: div
4438 sub git_print_header_div {
4439 my ($action, $title, $hash, $hash_base) = @_;
4440 my %args = ();
4442 $args{'action'} = $action;
4443 $args{'hash'} = $hash if $hash;
4444 $args{'hash_base'} = $hash_base if $hash_base;
4446 print "<div class=\"header\">\n" .
4447 $cgi->a({-href => href(%args), -class => "title"},
4448 $title ? $title : $action) .
4449 "\n</div>\n";
4452 sub format_repo_url {
4453 my ($name, $url) = @_;
4454 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4457 # Group output by placing it in a DIV element and adding a header.
4458 # Options for start_div() can be provided by passing a hash reference as the
4459 # first parameter to the function.
4460 # Options to git_print_header_div() can be provided by passing an array
4461 # reference. This must follow the options to start_div if they are present.
4462 # The content can be a scalar, which is output as-is, a scalar reference, which
4463 # is output after html escaping, an IO handle passed either as *handle or
4464 # *handle{IO}, or a function reference. In the latter case all following
4465 # parameters will be taken as argument to the content function call.
4466 sub git_print_section {
4467 my ($div_args, $header_args, $content);
4468 my $arg = shift;
4469 if (ref($arg) eq 'HASH') {
4470 $div_args = $arg;
4471 $arg = shift;
4473 if (ref($arg) eq 'ARRAY') {
4474 $header_args = $arg;
4475 $arg = shift;
4477 $content = $arg;
4479 print $cgi->start_div($div_args);
4480 git_print_header_div(@$header_args);
4482 if (ref($content) eq 'CODE') {
4483 $content->(@_);
4484 } elsif (ref($content) eq 'SCALAR') {
4485 print esc_html($$content);
4486 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4487 print <$content>;
4488 } elsif (!ref($content) && defined($content)) {
4489 print $content;
4492 print $cgi->end_div;
4495 sub format_timestamp_html {
4496 my $date = shift;
4497 my $strtime = $date->{'rfc2822'};
4499 my (undef, undef, $datetime_class) =
4500 gitweb_get_feature('javascript-timezone');
4501 if ($datetime_class) {
4502 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4505 my $localtime_format = '(%02d:%02d %s)';
4506 if ($date->{'hour_local'} < 6) {
4507 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4509 $strtime .= ' ' .
4510 sprintf($localtime_format,
4511 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4513 return $strtime;
4516 # Outputs the author name and date in long form
4517 sub git_print_authorship {
4518 my $co = shift;
4519 my %opts = @_;
4520 my $tag = $opts{-tag} || 'div';
4521 my $author = $co->{'author_name'};
4523 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4524 print "<$tag class=\"author_date\">" .
4525 format_search_author($author, "author", esc_html($author)) .
4526 " [".format_timestamp_html(\%ad)."]".
4527 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4528 "</$tag>\n";
4531 # Outputs table rows containing the full author or committer information,
4532 # in the format expected for 'commit' view (& similar).
4533 # Parameters are a commit hash reference, followed by the list of people
4534 # to output information for. If the list is empty it defaults to both
4535 # author and committer.
4536 sub git_print_authorship_rows {
4537 my $co = shift;
4538 # too bad we can't use @people = @_ || ('author', 'committer')
4539 my @people = @_;
4540 @people = ('author', 'committer') unless @people;
4541 foreach my $who (@people) {
4542 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4543 print "<tr><td>$who</td><td>" .
4544 format_search_author($co->{"${who}_name"}, $who,
4545 esc_html($co->{"${who}_name"})) . " " .
4546 format_search_author($co->{"${who}_email"}, $who,
4547 esc_html("<" . $co->{"${who}_email"} . ">")) .
4548 "</td><td rowspan=\"2\">" .
4549 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4550 "</td></tr>\n" .
4551 "<tr>" .
4552 "<td></td><td>" .
4553 format_timestamp_html(\%wd) .
4554 "</td>" .
4555 "</tr>\n";
4559 sub git_print_page_path {
4560 my $name = shift;
4561 my $type = shift;
4562 my $hb = shift;
4565 print "<div class=\"page_path\">";
4566 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4567 -title => 'tree root'}, to_utf8("[$project]"));
4568 print " / ";
4569 if (defined $name) {
4570 my @dirname = split '/', $name;
4571 my $basename = pop @dirname;
4572 my $fullname = '';
4574 foreach my $dir (@dirname) {
4575 $fullname .= ($fullname ? '/' : '') . $dir;
4576 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4577 hash_base=>$hb),
4578 -title => $fullname}, esc_path($dir));
4579 print " / ";
4581 if (defined $type && $type eq 'blob') {
4582 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4583 hash_base=>$hb),
4584 -title => $name}, esc_path($basename));
4585 } elsif (defined $type && $type eq 'tree') {
4586 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4587 hash_base=>$hb),
4588 -title => $name}, esc_path($basename));
4589 print " / ";
4590 } else {
4591 print esc_path($basename);
4594 print "<br/></div>\n";
4597 sub git_print_log {
4598 my $log = shift;
4599 my %opts = @_;
4601 if ($opts{'-remove_title'}) {
4602 # remove title, i.e. first line of log
4603 shift @$log;
4605 # remove leading empty lines
4606 while (defined $log->[0] && $log->[0] eq "") {
4607 shift @$log;
4610 # print log
4611 my $skip_blank_line = 0;
4612 foreach my $line (@$log) {
4613 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4614 if (! $opts{'-remove_signoff'}) {
4615 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4616 $skip_blank_line = 1;
4618 next;
4621 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4622 if (! $opts{'-remove_signoff'}) {
4623 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4624 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4625 "</span><br/>\n";
4626 $skip_blank_line = 1;
4628 next;
4631 # print only one empty line
4632 # do not print empty line after signoff
4633 if ($line eq "") {
4634 next if ($skip_blank_line);
4635 $skip_blank_line = 1;
4636 } else {
4637 $skip_blank_line = 0;
4640 print format_log_line_html($line) . "<br/>\n";
4643 if ($opts{'-final_empty_line'}) {
4644 # end with single empty line
4645 print "<br/>\n" unless $skip_blank_line;
4649 # return link target (what link points to)
4650 sub git_get_link_target {
4651 my $hash = shift;
4652 my $link_target;
4654 # read link
4655 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4656 or return;
4658 local $/ = undef;
4659 $link_target = <$fd>;
4661 close $fd
4662 or return;
4664 return $link_target;
4667 # given link target, and the directory (basedir) the link is in,
4668 # return target of link relative to top directory (top tree);
4669 # return undef if it is not possible (including absolute links).
4670 sub normalize_link_target {
4671 my ($link_target, $basedir) = @_;
4673 # absolute symlinks (beginning with '/') cannot be normalized
4674 return if (substr($link_target, 0, 1) eq '/');
4676 # normalize link target to path from top (root) tree (dir)
4677 my $path;
4678 if ($basedir) {
4679 $path = $basedir . '/' . $link_target;
4680 } else {
4681 # we are in top (root) tree (dir)
4682 $path = $link_target;
4685 # remove //, /./, and /../
4686 my @path_parts;
4687 foreach my $part (split('/', $path)) {
4688 # discard '.' and ''
4689 next if (!$part || $part eq '.');
4690 # handle '..'
4691 if ($part eq '..') {
4692 if (@path_parts) {
4693 pop @path_parts;
4694 } else {
4695 # link leads outside repository (outside top dir)
4696 return;
4698 } else {
4699 push @path_parts, $part;
4702 $path = join('/', @path_parts);
4704 return $path;
4707 # print tree entry (row of git_tree), but without encompassing <tr> element
4708 sub git_print_tree_entry {
4709 my ($t, $basedir, $hash_base, $have_blame) = @_;
4711 my %base_key = ();
4712 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4714 # The format of a table row is: mode list link. Where mode is
4715 # the mode of the entry, list is the name of the entry, an href,
4716 # and link is the action links of the entry.
4718 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4719 if (exists $t->{'size'}) {
4720 print "<td class=\"size\">$t->{'size'}</td>\n";
4722 if ($t->{'type'} eq "blob") {
4723 print "<td class=\"list\">" .
4724 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4725 file_name=>"$basedir$t->{'name'}", %base_key),
4726 -class => "list"}, esc_path($t->{'name'}));
4727 if (S_ISLNK(oct $t->{'mode'})) {
4728 my $link_target = git_get_link_target($t->{'hash'});
4729 if ($link_target) {
4730 my $norm_target = normalize_link_target($link_target, $basedir);
4731 if (defined $norm_target) {
4732 print " -> " .
4733 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4734 file_name=>$norm_target),
4735 -title => $norm_target}, esc_path($link_target));
4736 } else {
4737 print " -> " . esc_path($link_target);
4741 print "</td>\n";
4742 print "<td class=\"link\">";
4743 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4744 file_name=>"$basedir$t->{'name'}", %base_key)},
4745 "blob");
4746 if ($have_blame) {
4747 print " | " .
4748 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4749 file_name=>"$basedir$t->{'name'}", %base_key)},
4750 "blame");
4752 if (defined $hash_base) {
4753 print " | " .
4754 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4755 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4756 "history");
4758 print " | " .
4759 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4760 file_name=>"$basedir$t->{'name'}")},
4761 "raw");
4762 print "</td>\n";
4764 } elsif ($t->{'type'} eq "tree") {
4765 print "<td class=\"list\">";
4766 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4767 file_name=>"$basedir$t->{'name'}",
4768 %base_key)},
4769 esc_path($t->{'name'}));
4770 print "</td>\n";
4771 print "<td class=\"link\">";
4772 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4773 file_name=>"$basedir$t->{'name'}",
4774 %base_key)},
4775 "tree");
4776 if (defined $hash_base) {
4777 print " | " .
4778 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4779 file_name=>"$basedir$t->{'name'}")},
4780 "history");
4782 print "</td>\n";
4783 } else {
4784 # unknown object: we can only present history for it
4785 # (this includes 'commit' object, i.e. submodule support)
4786 print "<td class=\"list\">" .
4787 esc_path($t->{'name'}) .
4788 "</td>\n";
4789 print "<td class=\"link\">";
4790 if (defined $hash_base) {
4791 print $cgi->a({-href => href(action=>"history",
4792 hash_base=>$hash_base,
4793 file_name=>"$basedir$t->{'name'}")},
4794 "history");
4796 print "</td>\n";
4800 ## ......................................................................
4801 ## functions printing large fragments of HTML
4803 # get pre-image filenames for merge (combined) diff
4804 sub fill_from_file_info {
4805 my ($diff, @parents) = @_;
4807 $diff->{'from_file'} = [ ];
4808 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4809 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4810 if ($diff->{'status'}[$i] eq 'R' ||
4811 $diff->{'status'}[$i] eq 'C') {
4812 $diff->{'from_file'}[$i] =
4813 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4817 return $diff;
4820 # is current raw difftree line of file deletion
4821 sub is_deleted {
4822 my $diffinfo = shift;
4824 return $diffinfo->{'to_id'} eq ('0' x 40);
4827 # does patch correspond to [previous] difftree raw line
4828 # $diffinfo - hashref of parsed raw diff format
4829 # $patchinfo - hashref of parsed patch diff format
4830 # (the same keys as in $diffinfo)
4831 sub is_patch_split {
4832 my ($diffinfo, $patchinfo) = @_;
4834 return defined $diffinfo && defined $patchinfo
4835 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4839 sub git_difftree_body {
4840 my ($difftree, $hash, @parents) = @_;
4841 my ($parent) = $parents[0];
4842 my $have_blame = gitweb_check_feature('blame');
4843 print "<div class=\"list_head\">\n";
4844 if ($#{$difftree} > 10) {
4845 print(($#{$difftree} + 1) . " files changed:\n");
4847 print "</div>\n";
4849 print "<table class=\"" .
4850 (@parents > 1 ? "combined " : "") .
4851 "diff_tree\">\n";
4853 # header only for combined diff in 'commitdiff' view
4854 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4855 if ($has_header) {
4856 # table header
4857 print "<thead><tr>\n" .
4858 "<th></th><th></th>\n"; # filename, patchN link
4859 for (my $i = 0; $i < @parents; $i++) {
4860 my $par = $parents[$i];
4861 print "<th>" .
4862 $cgi->a({-href => href(action=>"commitdiff",
4863 hash=>$hash, hash_parent=>$par),
4864 -title => 'commitdiff to parent number ' .
4865 ($i+1) . ': ' . substr($par,0,7)},
4866 $i+1) .
4867 "&nbsp;</th>\n";
4869 print "</tr></thead>\n<tbody>\n";
4872 my $alternate = 1;
4873 my $patchno = 0;
4874 foreach my $line (@{$difftree}) {
4875 my $diff = parsed_difftree_line($line);
4877 if ($alternate) {
4878 print "<tr class=\"dark\">\n";
4879 } else {
4880 print "<tr class=\"light\">\n";
4882 $alternate ^= 1;
4884 if (exists $diff->{'nparents'}) { # combined diff
4886 fill_from_file_info($diff, @parents)
4887 unless exists $diff->{'from_file'};
4889 if (!is_deleted($diff)) {
4890 # file exists in the result (child) commit
4891 print "<td>" .
4892 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4893 file_name=>$diff->{'to_file'},
4894 hash_base=>$hash),
4895 -class => "list"}, esc_path($diff->{'to_file'})) .
4896 "</td>\n";
4897 } else {
4898 print "<td>" .
4899 esc_path($diff->{'to_file'}) .
4900 "</td>\n";
4903 if ($action eq 'commitdiff') {
4904 # link to patch
4905 $patchno++;
4906 print "<td class=\"link\">" .
4907 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4908 "patch") .
4909 " | " .
4910 "</td>\n";
4913 my $has_history = 0;
4914 my $not_deleted = 0;
4915 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4916 my $hash_parent = $parents[$i];
4917 my $from_hash = $diff->{'from_id'}[$i];
4918 my $from_path = $diff->{'from_file'}[$i];
4919 my $status = $diff->{'status'}[$i];
4921 $has_history ||= ($status ne 'A');
4922 $not_deleted ||= ($status ne 'D');
4924 if ($status eq 'A') {
4925 print "<td class=\"link\" align=\"right\"> | </td>\n";
4926 } elsif ($status eq 'D') {
4927 print "<td class=\"link\">" .
4928 $cgi->a({-href => href(action=>"blob",
4929 hash_base=>$hash,
4930 hash=>$from_hash,
4931 file_name=>$from_path)},
4932 "blob" . ($i+1)) .
4933 " | </td>\n";
4934 } else {
4935 if ($diff->{'to_id'} eq $from_hash) {
4936 print "<td class=\"link nochange\">";
4937 } else {
4938 print "<td class=\"link\">";
4940 print $cgi->a({-href => href(action=>"blobdiff",
4941 hash=>$diff->{'to_id'},
4942 hash_parent=>$from_hash,
4943 hash_base=>$hash,
4944 hash_parent_base=>$hash_parent,
4945 file_name=>$diff->{'to_file'},
4946 file_parent=>$from_path)},
4947 "diff" . ($i+1)) .
4948 " | </td>\n";
4952 print "<td class=\"link\">";
4953 if ($not_deleted) {
4954 print $cgi->a({-href => href(action=>"blob",
4955 hash=>$diff->{'to_id'},
4956 file_name=>$diff->{'to_file'},
4957 hash_base=>$hash)},
4958 "blob");
4959 print " | " if ($has_history);
4961 if ($has_history) {
4962 print $cgi->a({-href => href(action=>"history",
4963 file_name=>$diff->{'to_file'},
4964 hash_base=>$hash)},
4965 "history");
4967 print "</td>\n";
4969 print "</tr>\n";
4970 next; # instead of 'else' clause, to avoid extra indent
4972 # else ordinary diff
4974 my ($to_mode_oct, $to_mode_str, $to_file_type);
4975 my ($from_mode_oct, $from_mode_str, $from_file_type);
4976 if ($diff->{'to_mode'} ne ('0' x 6)) {
4977 $to_mode_oct = oct $diff->{'to_mode'};
4978 if (S_ISREG($to_mode_oct)) { # only for regular file
4979 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4981 $to_file_type = file_type($diff->{'to_mode'});
4983 if ($diff->{'from_mode'} ne ('0' x 6)) {
4984 $from_mode_oct = oct $diff->{'from_mode'};
4985 if (S_ISREG($from_mode_oct)) { # only for regular file
4986 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4988 $from_file_type = file_type($diff->{'from_mode'});
4991 if ($diff->{'status'} eq "A") { # created
4992 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4993 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4994 $mode_chng .= "]</span>";
4995 print "<td>";
4996 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4997 hash_base=>$hash, file_name=>$diff->{'file'}),
4998 -class => "list"}, esc_path($diff->{'file'}));
4999 print "</td>\n";
5000 print "<td>$mode_chng</td>\n";
5001 print "<td class=\"link\">";
5002 if ($action eq 'commitdiff') {
5003 # link to patch
5004 $patchno++;
5005 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5006 "patch") .
5007 " | ";
5009 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5010 hash_base=>$hash, file_name=>$diff->{'file'})},
5011 "blob");
5012 print "</td>\n";
5014 } elsif ($diff->{'status'} eq "D") { # deleted
5015 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5016 print "<td>";
5017 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5018 hash_base=>$parent, file_name=>$diff->{'file'}),
5019 -class => "list"}, esc_path($diff->{'file'}));
5020 print "</td>\n";
5021 print "<td>$mode_chng</td>\n";
5022 print "<td class=\"link\">";
5023 if ($action eq 'commitdiff') {
5024 # link to patch
5025 $patchno++;
5026 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5027 "patch") .
5028 " | ";
5030 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5031 hash_base=>$parent, file_name=>$diff->{'file'})},
5032 "blob") . " | ";
5033 if ($have_blame) {
5034 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5035 file_name=>$diff->{'file'})},
5036 "blame") . " | ";
5038 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5039 file_name=>$diff->{'file'})},
5040 "history");
5041 print "</td>\n";
5043 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5044 my $mode_chnge = "";
5045 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5046 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5047 if ($from_file_type ne $to_file_type) {
5048 $mode_chnge .= " from $from_file_type to $to_file_type";
5050 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5051 if ($from_mode_str && $to_mode_str) {
5052 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5053 } elsif ($to_mode_str) {
5054 $mode_chnge .= " mode: $to_mode_str";
5057 $mode_chnge .= "]</span>\n";
5059 print "<td>";
5060 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5061 hash_base=>$hash, file_name=>$diff->{'file'}),
5062 -class => "list"}, esc_path($diff->{'file'}));
5063 print "</td>\n";
5064 print "<td>$mode_chnge</td>\n";
5065 print "<td class=\"link\">";
5066 if ($action eq 'commitdiff') {
5067 # link to patch
5068 $patchno++;
5069 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5070 "patch") .
5071 " | ";
5072 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5073 # "commit" view and modified file (not onlu mode changed)
5074 print $cgi->a({-href => href(action=>"blobdiff",
5075 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5076 hash_base=>$hash, hash_parent_base=>$parent,
5077 file_name=>$diff->{'file'})},
5078 "diff") .
5079 " | ";
5081 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5082 hash_base=>$hash, file_name=>$diff->{'file'})},
5083 "blob") . " | ";
5084 if ($have_blame) {
5085 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5086 file_name=>$diff->{'file'})},
5087 "blame") . " | ";
5089 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5090 file_name=>$diff->{'file'})},
5091 "history");
5092 print "</td>\n";
5094 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5095 my %status_name = ('R' => 'moved', 'C' => 'copied');
5096 my $nstatus = $status_name{$diff->{'status'}};
5097 my $mode_chng = "";
5098 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5099 # mode also for directories, so we cannot use $to_mode_str
5100 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5102 print "<td>" .
5103 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5104 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5105 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5106 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5107 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5108 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5109 -class => "list"}, esc_path($diff->{'from_file'})) .
5110 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5111 "<td class=\"link\">";
5112 if ($action eq 'commitdiff') {
5113 # link to patch
5114 $patchno++;
5115 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5116 "patch") .
5117 " | ";
5118 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5119 # "commit" view and modified file (not only pure rename or copy)
5120 print $cgi->a({-href => href(action=>"blobdiff",
5121 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5122 hash_base=>$hash, hash_parent_base=>$parent,
5123 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5124 "diff") .
5125 " | ";
5127 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5128 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5129 "blob") . " | ";
5130 if ($have_blame) {
5131 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5132 file_name=>$diff->{'to_file'})},
5133 "blame") . " | ";
5135 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5136 file_name=>$diff->{'to_file'})},
5137 "history");
5138 print "</td>\n";
5140 } # we should not encounter Unmerged (U) or Unknown (X) status
5141 print "</tr>\n";
5143 print "</tbody>" if $has_header;
5144 print "</table>\n";
5147 # Print context lines and then rem/add lines in a side-by-side manner.
5148 sub print_sidebyside_diff_lines {
5149 my ($ctx, $rem, $add) = @_;
5151 # print context block before add/rem block
5152 if (@$ctx) {
5153 print join '',
5154 '<div class="chunk_block ctx">',
5155 '<div class="old">',
5156 @$ctx,
5157 '</div>',
5158 '<div class="new">',
5159 @$ctx,
5160 '</div>',
5161 '</div>';
5164 if (!@$add) {
5165 # pure removal
5166 print join '',
5167 '<div class="chunk_block rem">',
5168 '<div class="old">',
5169 @$rem,
5170 '</div>',
5171 '</div>';
5172 } elsif (!@$rem) {
5173 # pure addition
5174 print join '',
5175 '<div class="chunk_block add">',
5176 '<div class="new">',
5177 @$add,
5178 '</div>',
5179 '</div>';
5180 } else {
5181 print join '',
5182 '<div class="chunk_block chg">',
5183 '<div class="old">',
5184 @$rem,
5185 '</div>',
5186 '<div class="new">',
5187 @$add,
5188 '</div>',
5189 '</div>';
5193 # Print context lines and then rem/add lines in inline manner.
5194 sub print_inline_diff_lines {
5195 my ($ctx, $rem, $add) = @_;
5197 print @$ctx, @$rem, @$add;
5200 # Format removed and added line, mark changed part and HTML-format them.
5201 # Implementation is based on contrib/diff-highlight
5202 sub format_rem_add_lines_pair {
5203 my ($rem, $add, $num_parents) = @_;
5205 # We need to untabify lines before split()'ing them;
5206 # otherwise offsets would be invalid.
5207 chomp $rem;
5208 chomp $add;
5209 $rem = untabify($rem);
5210 $add = untabify($add);
5212 my @rem = split(//, $rem);
5213 my @add = split(//, $add);
5214 my ($esc_rem, $esc_add);
5215 # Ignore leading +/- characters for each parent.
5216 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5217 my ($prefix_has_nonspace, $suffix_has_nonspace);
5219 my $shorter = (@rem < @add) ? @rem : @add;
5220 while ($prefix_len < $shorter) {
5221 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5223 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5224 $prefix_len++;
5227 while ($prefix_len + $suffix_len < $shorter) {
5228 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5230 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5231 $suffix_len++;
5234 # Mark lines that are different from each other, but have some common
5235 # part that isn't whitespace. If lines are completely different, don't
5236 # mark them because that would make output unreadable, especially if
5237 # diff consists of multiple lines.
5238 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5239 $esc_rem = esc_html_hl_regions($rem, 'marked',
5240 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5241 $esc_add = esc_html_hl_regions($add, 'marked',
5242 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5243 } else {
5244 $esc_rem = esc_html($rem, -nbsp=>1);
5245 $esc_add = esc_html($add, -nbsp=>1);
5248 return format_diff_line(\$esc_rem, 'rem'),
5249 format_diff_line(\$esc_add, 'add');
5252 # HTML-format diff context, removed and added lines.
5253 sub format_ctx_rem_add_lines {
5254 my ($ctx, $rem, $add, $num_parents) = @_;
5255 my (@new_ctx, @new_rem, @new_add);
5256 my $can_highlight = 0;
5257 my $is_combined = ($num_parents > 1);
5259 # Highlight if every removed line has a corresponding added line.
5260 if (@$add > 0 && @$add == @$rem) {
5261 $can_highlight = 1;
5263 # Highlight lines in combined diff only if the chunk contains
5264 # diff between the same version, e.g.
5266 # - a
5267 # - b
5268 # + c
5269 # + d
5271 # Otherwise the highlightling would be confusing.
5272 if ($is_combined) {
5273 for (my $i = 0; $i < @$add; $i++) {
5274 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5275 my $prefix_add = substr($add->[$i], 0, $num_parents);
5277 $prefix_rem =~ s/-/+/g;
5279 if ($prefix_rem ne $prefix_add) {
5280 $can_highlight = 0;
5281 last;
5287 if ($can_highlight) {
5288 for (my $i = 0; $i < @$add; $i++) {
5289 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5290 $rem->[$i], $add->[$i], $num_parents);
5291 push @new_rem, $line_rem;
5292 push @new_add, $line_add;
5294 } else {
5295 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5296 @new_add = map { format_diff_line($_, 'add') } @$add;
5299 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5301 return (\@new_ctx, \@new_rem, \@new_add);
5304 # Print context lines and then rem/add lines.
5305 sub print_diff_lines {
5306 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5307 my $is_combined = $num_parents > 1;
5309 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5310 $num_parents);
5312 if ($diff_style eq 'sidebyside' && !$is_combined) {
5313 print_sidebyside_diff_lines($ctx, $rem, $add);
5314 } else {
5315 # default 'inline' style and unknown styles
5316 print_inline_diff_lines($ctx, $rem, $add);
5320 sub print_diff_chunk {
5321 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5322 my (@ctx, @rem, @add);
5324 # The class of the previous line.
5325 my $prev_class = '';
5327 return unless @chunk;
5329 # incomplete last line might be among removed or added lines,
5330 # or both, or among context lines: find which
5331 for (my $i = 1; $i < @chunk; $i++) {
5332 if ($chunk[$i][0] eq 'incomplete') {
5333 $chunk[$i][0] = $chunk[$i-1][0];
5337 # guardian
5338 push @chunk, ["", ""];
5340 foreach my $line_info (@chunk) {
5341 my ($class, $line) = @$line_info;
5343 # print chunk headers
5344 if ($class && $class eq 'chunk_header') {
5345 print format_diff_line($line, $class, $from, $to);
5346 next;
5349 ## print from accumulator when have some add/rem lines or end
5350 # of chunk (flush context lines), or when have add and rem
5351 # lines and new block is reached (otherwise add/rem lines could
5352 # be reordered)
5353 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5354 (@rem && @add && $class ne $prev_class)) {
5355 print_diff_lines(\@ctx, \@rem, \@add,
5356 $diff_style, $num_parents);
5357 @ctx = @rem = @add = ();
5360 ## adding lines to accumulator
5361 # guardian value
5362 last unless $line;
5363 # rem, add or change
5364 if ($class eq 'rem') {
5365 push @rem, $line;
5366 } elsif ($class eq 'add') {
5367 push @add, $line;
5369 # context line
5370 if ($class eq 'ctx') {
5371 push @ctx, $line;
5374 $prev_class = $class;
5378 sub git_patchset_body {
5379 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5380 my ($hash_parent) = $hash_parents[0];
5382 my $is_combined = (@hash_parents > 1);
5383 my $patch_idx = 0;
5384 my $patch_number = 0;
5385 my $patch_line;
5386 my $diffinfo;
5387 my $to_name;
5388 my (%from, %to);
5389 my @chunk; # for side-by-side diff
5391 print "<div class=\"patchset\">\n";
5393 # skip to first patch
5394 while ($patch_line = <$fd>) {
5395 chomp $patch_line;
5397 last if ($patch_line =~ m/^diff /);
5400 PATCH:
5401 while ($patch_line) {
5403 # parse "git diff" header line
5404 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5405 # $1 is from_name, which we do not use
5406 $to_name = unquote($2);
5407 $to_name =~ s!^b/!!;
5408 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5409 # $1 is 'cc' or 'combined', which we do not use
5410 $to_name = unquote($2);
5411 } else {
5412 $to_name = undef;
5415 # check if current patch belong to current raw line
5416 # and parse raw git-diff line if needed
5417 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5418 # this is continuation of a split patch
5419 print "<div class=\"patch cont\">\n";
5420 } else {
5421 # advance raw git-diff output if needed
5422 $patch_idx++ if defined $diffinfo;
5424 # read and prepare patch information
5425 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5427 # compact combined diff output can have some patches skipped
5428 # find which patch (using pathname of result) we are at now;
5429 if ($is_combined) {
5430 while ($to_name ne $diffinfo->{'to_file'}) {
5431 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5432 format_diff_cc_simplified($diffinfo, @hash_parents) .
5433 "</div>\n"; # class="patch"
5435 $patch_idx++;
5436 $patch_number++;
5438 last if $patch_idx > $#$difftree;
5439 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5443 # modifies %from, %to hashes
5444 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5446 # this is first patch for raw difftree line with $patch_idx index
5447 # we index @$difftree array from 0, but number patches from 1
5448 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5451 # git diff header
5452 #assert($patch_line =~ m/^diff /) if DEBUG;
5453 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5454 $patch_number++;
5455 # print "git diff" header
5456 print format_git_diff_header_line($patch_line, $diffinfo,
5457 \%from, \%to);
5459 # print extended diff header
5460 print "<div class=\"diff extended_header\">\n";
5461 EXTENDED_HEADER:
5462 while ($patch_line = <$fd>) {
5463 chomp $patch_line;
5465 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5467 print format_extended_diff_header_line($patch_line, $diffinfo,
5468 \%from, \%to);
5470 print "</div>\n"; # class="diff extended_header"
5472 # from-file/to-file diff header
5473 if (! $patch_line) {
5474 print "</div>\n"; # class="patch"
5475 last PATCH;
5477 next PATCH if ($patch_line =~ m/^diff /);
5478 #assert($patch_line =~ m/^---/) if DEBUG;
5480 my $last_patch_line = $patch_line;
5481 $patch_line = <$fd>;
5482 chomp $patch_line;
5483 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5485 print format_diff_from_to_header($last_patch_line, $patch_line,
5486 $diffinfo, \%from, \%to,
5487 @hash_parents);
5489 # the patch itself
5490 LINE:
5491 while ($patch_line = <$fd>) {
5492 chomp $patch_line;
5494 next PATCH if ($patch_line =~ m/^diff /);
5496 my $class = diff_line_class($patch_line, \%from, \%to);
5498 if ($class eq 'chunk_header') {
5499 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5500 @chunk = ();
5503 push @chunk, [ $class, $patch_line ];
5506 } continue {
5507 if (@chunk) {
5508 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5509 @chunk = ();
5511 print "</div>\n"; # class="patch"
5514 # for compact combined (--cc) format, with chunk and patch simplification
5515 # the patchset might be empty, but there might be unprocessed raw lines
5516 for (++$patch_idx if $patch_number > 0;
5517 $patch_idx < @$difftree;
5518 ++$patch_idx) {
5519 # read and prepare patch information
5520 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5522 # generate anchor for "patch" links in difftree / whatchanged part
5523 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5524 format_diff_cc_simplified($diffinfo, @hash_parents) .
5525 "</div>\n"; # class="patch"
5527 $patch_number++;
5530 if ($patch_number == 0) {
5531 if (@hash_parents > 1) {
5532 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5533 } else {
5534 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5538 print "</div>\n"; # class="patchset"
5541 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5543 sub git_project_search_form {
5544 my ($searchtext, $search_use_regexp) = @_;
5546 my $limit = '';
5547 if ($project_filter) {
5548 $limit = " in '$project_filter/'";
5551 print "<div class=\"projsearch\">\n";
5552 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5553 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5554 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5555 if (defined $project_filter);
5556 print $cgi->textfield(-name => 's', -value => $searchtext,
5557 -title => "Search project by name and description$limit",
5558 -size => 60) . "\n" .
5559 "<span title=\"Extended regular expression\">" .
5560 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5561 -checked => $search_use_regexp) .
5562 "</span>\n" .
5563 $cgi->submit(-name => 'btnS', -value => 'Search') .
5564 $cgi->end_form() . "\n" .
5565 "<span class=\"projectlist_link\">" .
5566 $cgi->a({-href => href(project => undef, searchtext => undef,
5567 action => 'project_list',
5568 project_filter => $project_filter)},
5569 esc_html("List all projects$limit")) . "</span>\n";
5570 print "</div>\n";
5573 # entry for given @keys needs filling if at least one of keys in list
5574 # is not present in %$project_info
5575 sub project_info_needs_filling {
5576 my ($project_info, @keys) = @_;
5578 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5579 foreach my $key (@keys) {
5580 if (!exists $project_info->{$key}) {
5581 return 1;
5584 return;
5587 sub git_cache_file_format {
5588 return GITWEB_CACHE_FORMAT .
5589 (gitweb_check_feature('forks') ? " (forks)" : "");
5592 sub git_retrieve_cache_file {
5593 my $cache_file = shift;
5595 use Storable qw(retrieve);
5597 if ((my $dump = eval { retrieve($cache_file) })) {
5598 return $$dump[1] if
5599 ref($dump) eq 'ARRAY' &&
5600 @$dump == 2 &&
5601 ref($$dump[1]) eq 'ARRAY' &&
5602 $$dump[0] eq git_cache_file_format();
5605 return undef;
5608 sub git_store_cache_file {
5609 my ($cache_file, $projlist) = @_;
5611 use File::Basename qw(dirname);
5612 use POSIX qw(:fcntl_h);
5613 use Storable qw(store_fd);
5615 my $cache_d = dirname($cache_file);
5616 my $mask = umask();
5617 umask($mask & ~0070) if $cache_grpshared;
5618 if ((-d $cache_d || mkdir($cache_d, $cache_grpshared ? 0770 : 0700)) &&
5619 sysopen(my $fd, "$cache_file.lock", O_WRONLY|O_CREAT|O_EXCL, $cache_grpshared ? 0660 : 0600)) {
5620 store_fd([git_cache_file_format(), $projlist], $fd);
5621 close $fd;
5622 rename "$cache_file.lock", $cache_file;
5624 umask($mask) if $cache_grpshared;
5627 sub git_filter_cached_projects {
5628 my ($cache, $projlist) = @_;
5629 my %selected = map { ( $_->{'path'} => 1 ) } @$projlist;
5630 return grep { $selected{$_->{'path'}} } @$cache;
5633 # fills project list info (age, description, owner, category, forks, etc.)
5634 # for each project in the list, removing invalid projects from
5635 # returned list, or fill only specified info.
5637 # Invalid projects are removed from the returned list if and only if you
5638 # ask 'age' or 'age_string' to be filled, because they are the only fields
5639 # that run unconditionally git command that requires repository, and
5640 # therefore do always check if project repository is invalid.
5642 # USAGE:
5643 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5644 # ensures that 'descr_long' and 'ctags' fields are filled
5645 # * @project_list = fill_project_list_info(\@project_list)
5646 # ensures that all fields are filled (and invalid projects removed)
5648 # NOTE: modifies $projlist, but does not remove entries from it
5649 sub fill_project_list_info {
5650 my ($projlist, @wanted_keys) = @_;
5652 use File::stat;
5654 my $cache_file = "$cache_dir/$projlist_cache_name";
5656 my @projects;
5657 my $stale = 0;
5658 my $now = time();
5659 my $cache_mtime;
5660 if ($projlist_cache_lifetime && -f $cache_file) {
5661 $cache_mtime = stat($cache_file)->mtime;
5663 if (defined $cache_mtime && # caching is on and $cache_file exists
5664 $cache_mtime + $projlist_cache_lifetime*60 > $now &&
5665 (my $dump = git_retrieve_cache_file($cache_file))) {
5666 # Cache hit.
5667 $stale = $now - $cache_mtime;
5668 @projects = git_filter_cached_projects($dump, $projlist);
5670 } else { # Cache miss.
5671 if (defined $cache_mtime) {
5672 # Postpone timeout by two minutes so that we get
5673 # enough time to do our job, or to be more exact
5674 # make cache expire after two minutes from now.
5675 my $time = $now - $projlist_cache_lifetime*60 + 120;
5676 utime $time, $time, $cache_file;
5678 if ($projlist_cache_lifetime) {
5679 my @all_projects = git_get_projects_list();
5680 my %all_projects_filled = map { ($_->{'path'} = $_) }
5681 fill_project_list_info_uncached(\@all_projects);
5682 map { %all_projects_filled{$_->{'path'}} = $_ }
5683 filter_forks_from_projects_list([values(%all_projects_filled)])
5684 if gitweb_check_feature('forks');
5685 my @all_projects_values = values(%all_projects_filled);
5686 git_store_cache_file($cache_file, \@all_projects_values);
5687 @projects = git_filter_cached_projects(\@all_projects_values, $projlist);
5688 } else {
5689 @projects = fill_project_list_info_uncached($projlist, @wanted_keys);
5693 if ($projlist_cache_lifetime && $stale > 0) {
5694 print "<div class=\"stale_info\">Cached version (${stale}s old)</div>\n"
5695 unless $shown_stale_message;
5696 $shown_stale_message = 1;
5699 return @projects;
5702 sub fill_project_list_info_uncached {
5703 my ($projlist, @wanted_keys) = @_;
5704 my @projects;
5705 my $filter_set = sub { return @_; };
5706 if (@wanted_keys) {
5707 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5708 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5711 my $show_ctags = gitweb_check_feature('ctags');
5712 PROJECT:
5713 foreach my $pr (@$projlist) {
5714 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5715 my (@activity) = git_get_last_activity($pr->{'path'});
5716 unless (@activity) {
5717 next PROJECT;
5719 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5721 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5722 my $descr = git_get_project_description($pr->{'path'}) || "";
5723 $descr = to_utf8($descr);
5724 $pr->{'descr_long'} = $descr;
5725 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5727 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5728 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5730 if ($show_ctags &&
5731 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5732 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5734 if ($projects_list_group_categories &&
5735 project_info_needs_filling($pr, $filter_set->('category'))) {
5736 my $cat = git_get_project_category($pr->{'path'}) ||
5737 $project_list_default_category;
5738 $pr->{'category'} = to_utf8($cat);
5741 push @projects, $pr;
5744 return @projects;
5747 sub sort_projects_list {
5748 my ($projlist, $order) = @_;
5750 sub order_str {
5751 my $key = shift;
5752 return sub { $a->{$key} cmp $b->{$key} };
5755 sub order_num_then_undef {
5756 my $key = shift;
5757 return sub {
5758 defined $a->{$key} ?
5759 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5760 (defined $b->{$key} ? 1 : 0)
5764 my %orderings = (
5765 project => order_str('path'),
5766 descr => order_str('descr_long'),
5767 owner => order_str('owner'),
5768 age => order_num_then_undef('age'),
5771 my $ordering = $orderings{$order};
5772 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5775 # returns a hash of categories, containing the list of project
5776 # belonging to each category
5777 sub build_projlist_by_category {
5778 my ($projlist, $from, $to) = @_;
5779 my %categories;
5781 $from = 0 unless defined $from;
5782 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5784 for (my $i = $from; $i <= $to; $i++) {
5785 my $pr = $projlist->[$i];
5786 push @{$categories{ $pr->{'category'} }}, $pr;
5789 return wantarray ? %categories : \%categories;
5792 # print 'sort by' <th> element, generating 'sort by $name' replay link
5793 # if that order is not selected
5794 sub print_sort_th {
5795 print format_sort_th(@_);
5798 sub format_sort_th {
5799 my ($name, $order, $header) = @_;
5800 my $sort_th = "";
5801 $header ||= ucfirst($name);
5803 if ($order eq $name) {
5804 $sort_th .= "<th>$header</th>\n";
5805 } else {
5806 $sort_th .= "<th>" .
5807 $cgi->a({-href => href(-replay=>1, order=>$name),
5808 -class => "header"}, $header) .
5809 "</th>\n";
5812 return $sort_th;
5815 sub git_project_list_rows {
5816 my ($projlist, $from, $to, $check_forks) = @_;
5818 $from = 0 unless defined $from;
5819 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5821 my $alternate = 1;
5822 for (my $i = $from; $i <= $to; $i++) {
5823 my $pr = $projlist->[$i];
5825 if ($alternate) {
5826 print "<tr class=\"dark\">\n";
5827 } else {
5828 print "<tr class=\"light\">\n";
5830 $alternate ^= 1;
5832 if ($check_forks) {
5833 print "<td>";
5834 if ($pr->{'forks'}) {
5835 my $nforks = scalar @{$pr->{'forks'}};
5836 if ($nforks > 0) {
5837 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5838 -title => "$nforks forks"}, "+");
5839 } else {
5840 print $cgi->span({-title => "$nforks forks"}, "+");
5843 print "</td>\n";
5845 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5846 -class => "list"},
5847 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5848 "</td>\n" .
5849 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5850 -class => "list",
5851 -title => $pr->{'descr_long'}},
5852 $search_regexp
5853 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5854 $pr->{'descr'}, $search_regexp)
5855 : esc_html($pr->{'descr'})) .
5856 "</td>\n";
5857 unless ($omit_owner) {
5858 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5860 unless ($omit_age_column) {
5861 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5862 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5864 print"<td class=\"link\">" .
5865 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5866 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5867 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5868 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5869 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5870 "</td>\n" .
5871 "</tr>\n";
5875 sub git_project_list_body {
5876 # actually uses global variable $project
5877 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action) = @_;
5878 my @projects = @$projlist;
5880 my $check_forks = gitweb_check_feature('forks');
5881 my $show_ctags = gitweb_check_feature('ctags');
5882 my $tagfilter = $show_ctags ? $input_params{'ctag_filter'} : undef;
5883 $check_forks = undef
5884 if ($tagfilter || $search_regexp);
5886 # filtering out forks before filling info allows to do less work
5887 @projects = filter_forks_from_projects_list(\@projects)
5888 if ($check_forks);
5889 # search_projects_list pre-fills required info
5890 @projects = search_projects_list(\@projects,
5891 'search_regexp' => $search_regexp,
5892 'tagfilter' => $tagfilter)
5893 if ($tagfilter || $search_regexp);
5894 # fill the rest
5895 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5896 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5897 push @all_fields, 'owner' unless($omit_owner);
5898 @projects = fill_project_list_info(\@projects, @all_fields);
5900 $order ||= $default_projects_order;
5901 $from = 0 unless defined $from;
5902 $to = $#projects if (!defined $to || $#projects < $to);
5904 # short circuit
5905 if ($from > $to) {
5906 print "<center>\n".
5907 "<b>No such projects found</b><br />\n".
5908 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5909 "</center>\n<br />\n";
5910 return;
5913 @projects = sort_projects_list(\@projects, $order);
5915 if ($show_ctags) {
5916 my $ctags = git_gather_all_ctags(\@projects);
5917 my $cloud = git_populate_project_tagcloud($ctags, $ctags_action||'project_list');
5918 print git_show_project_tagcloud($cloud, 64);
5921 print "<table class=\"project_list\">\n";
5922 unless ($no_header) {
5923 print "<tr>\n";
5924 if ($check_forks) {
5925 print "<th></th>\n";
5927 print_sort_th('project', $order, 'Project');
5928 print_sort_th('descr', $order, 'Description');
5929 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5930 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5931 print "<th></th>\n" . # for links
5932 "</tr>\n";
5935 if ($projects_list_group_categories) {
5936 # only display categories with projects in the $from-$to window
5937 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5938 my %categories = build_projlist_by_category(\@projects, $from, $to);
5939 foreach my $cat (sort keys %categories) {
5940 unless ($cat eq "") {
5941 print "<tr>\n";
5942 if ($check_forks) {
5943 print "<td></td>\n";
5945 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5946 print "</tr>\n";
5949 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5951 } else {
5952 git_project_list_rows(\@projects, $from, $to, $check_forks);
5955 if (defined $extra) {
5956 print "<tr>\n";
5957 if ($check_forks) {
5958 print "<td></td>\n";
5960 print "<td colspan=\"5\">$extra</td>\n" .
5961 "</tr>\n";
5963 print "</table>\n";
5966 sub git_log_body {
5967 # uses global variable $project
5968 my ($commitlist, $from, $to, $refs, $extra) = @_;
5970 $from = 0 unless defined $from;
5971 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5973 for (my $i = 0; $i <= $to; $i++) {
5974 my %co = %{$commitlist->[$i]};
5975 next if !%co;
5976 my $commit = $co{'id'};
5977 my $ref = format_ref_marker($refs, $commit);
5978 git_print_header_div('commit',
5979 "<span class=\"age\">$co{'age_string'}</span>" .
5980 esc_html($co{'title'}) . $ref,
5981 $commit);
5982 print "<div class=\"title_text\">\n" .
5983 "<div class=\"log_link\">\n" .
5984 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5985 " | " .
5986 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5987 " | " .
5988 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5989 "<br/>\n" .
5990 "</div>\n";
5991 git_print_authorship(\%co, -tag => 'span');
5992 print "<br/>\n</div>\n";
5994 print "<div class=\"log_body\">\n";
5995 git_print_log($co{'comment'}, -final_empty_line=> 1);
5996 print "</div>\n";
5998 if ($extra) {
5999 print "<div class=\"page_nav\">\n";
6000 print "$extra\n";
6001 print "</div>\n";
6005 sub git_shortlog_body {
6006 # uses global variable $project
6007 my ($commitlist, $from, $to, $refs, $extra) = @_;
6009 $from = 0 unless defined $from;
6010 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6012 print "<table class=\"shortlog\">\n";
6013 my $alternate = 1;
6014 for (my $i = $from; $i <= $to; $i++) {
6015 my %co = %{$commitlist->[$i]};
6016 my $commit = $co{'id'};
6017 my $ref = format_ref_marker($refs, $commit);
6018 if ($alternate) {
6019 print "<tr class=\"dark\">\n";
6020 } else {
6021 print "<tr class=\"light\">\n";
6023 $alternate ^= 1;
6024 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
6025 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6026 format_author_html('td', \%co, 10) . "<td>";
6027 print format_subject_html($co{'title'}, $co{'title_short'},
6028 href(action=>"commit", hash=>$commit), $ref);
6029 print "</td>\n" .
6030 "<td class=\"link\">" .
6031 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
6032 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
6033 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
6034 my $snapshot_links = format_snapshot_links($commit);
6035 if (defined $snapshot_links) {
6036 print " | " . $snapshot_links;
6038 print "</td>\n" .
6039 "</tr>\n";
6041 if (defined $extra) {
6042 print "<tr>\n" .
6043 "<td colspan=\"4\">$extra</td>\n" .
6044 "</tr>\n";
6046 print "</table>\n";
6049 sub git_history_body {
6050 # Warning: assumes constant type (blob or tree) during history
6051 my ($commitlist, $from, $to, $refs, $extra,
6052 $file_name, $file_hash, $ftype) = @_;
6054 $from = 0 unless defined $from;
6055 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
6057 print "<table class=\"history\">\n";
6058 my $alternate = 1;
6059 for (my $i = $from; $i <= $to; $i++) {
6060 my %co = %{$commitlist->[$i]};
6061 if (!%co) {
6062 next;
6064 my $commit = $co{'id'};
6066 my $ref = format_ref_marker($refs, $commit);
6068 if ($alternate) {
6069 print "<tr class=\"dark\">\n";
6070 } else {
6071 print "<tr class=\"light\">\n";
6073 $alternate ^= 1;
6074 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6075 # shortlog: format_author_html('td', \%co, 10)
6076 format_author_html('td', \%co, 15, 3) . "<td>";
6077 # originally git_history used chop_str($co{'title'}, 50)
6078 print format_subject_html($co{'title'}, $co{'title_short'},
6079 href(action=>"commit", hash=>$commit), $ref);
6080 print "</td>\n" .
6081 "<td class=\"link\">" .
6082 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
6083 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
6085 if ($ftype eq 'blob') {
6086 my $blob_current = $file_hash;
6087 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6088 if (defined $blob_current && defined $blob_parent &&
6089 $blob_current ne $blob_parent) {
6090 print " | " .
6091 $cgi->a({-href => href(action=>"blobdiff",
6092 hash=>$blob_current, hash_parent=>$blob_parent,
6093 hash_base=>$hash_base, hash_parent_base=>$commit,
6094 file_name=>$file_name)},
6095 "diff to current");
6098 print "</td>\n" .
6099 "</tr>\n";
6101 if (defined $extra) {
6102 print "<tr>\n" .
6103 "<td colspan=\"4\">$extra</td>\n" .
6104 "</tr>\n";
6106 print "</table>\n";
6109 sub git_tags_body {
6110 # uses global variable $project
6111 my ($taglist, $from, $to, $extra) = @_;
6112 $from = 0 unless defined $from;
6113 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6115 print "<table class=\"tags\">\n";
6116 my $alternate = 1;
6117 for (my $i = $from; $i <= $to; $i++) {
6118 my $entry = $taglist->[$i];
6119 my %tag = %$entry;
6120 my $comment = $tag{'subject'};
6121 my $comment_short;
6122 if (defined $comment) {
6123 $comment_short = chop_str($comment, 30, 5);
6125 if ($alternate) {
6126 print "<tr class=\"dark\">\n";
6127 } else {
6128 print "<tr class=\"light\">\n";
6130 $alternate ^= 1;
6131 if (defined $tag{'age'}) {
6132 print "<td><i>$tag{'age'}</i></td>\n";
6133 } else {
6134 print "<td></td>\n";
6136 print "<td>" .
6137 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6138 -class => "list name"}, esc_html($tag{'name'})) .
6139 "</td>\n" .
6140 "<td>";
6141 if (defined $comment) {
6142 print format_subject_html($comment, $comment_short,
6143 href(action=>"tag", hash=>$tag{'id'}));
6145 print "</td>\n" .
6146 "<td class=\"selflink\">";
6147 if ($tag{'type'} eq "tag") {
6148 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6149 } else {
6150 print "&nbsp;";
6152 print "</td>\n" .
6153 "<td class=\"link\">" . " | " .
6154 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6155 if ($tag{'reftype'} eq "commit") {
6156 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6157 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6158 } elsif ($tag{'reftype'} eq "blob") {
6159 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6161 print "</td>\n" .
6162 "</tr>";
6164 if (defined $extra) {
6165 print "<tr>\n" .
6166 "<td colspan=\"5\">$extra</td>\n" .
6167 "</tr>\n";
6169 print "</table>\n";
6172 sub git_heads_body {
6173 # uses global variable $project
6174 my ($headlist, $head_at, $from, $to, $extra) = @_;
6175 $from = 0 unless defined $from;
6176 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6178 print "<table class=\"heads\">\n";
6179 my $alternate = 1;
6180 for (my $i = $from; $i <= $to; $i++) {
6181 my $entry = $headlist->[$i];
6182 my %ref = %$entry;
6183 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6184 if ($alternate) {
6185 print "<tr class=\"dark\">\n";
6186 } else {
6187 print "<tr class=\"light\">\n";
6189 $alternate ^= 1;
6190 print "<td><i>$ref{'age'}</i></td>\n" .
6191 ($curr ? "<td class=\"current_head\">" : "<td>") .
6192 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6193 -class => "list name"},esc_html($ref{'name'})) .
6194 "</td>\n" .
6195 "<td class=\"link\">" .
6196 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6197 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6198 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6199 "</td>\n" .
6200 "</tr>";
6202 if (defined $extra) {
6203 print "<tr>\n" .
6204 "<td colspan=\"3\">$extra</td>\n" .
6205 "</tr>\n";
6207 print "</table>\n";
6210 # Display a single remote block
6211 sub git_remote_block {
6212 my ($remote, $rdata, $limit, $head) = @_;
6214 my $heads = $rdata->{'heads'};
6215 my $fetch = $rdata->{'fetch'};
6216 my $push = $rdata->{'push'};
6218 my $urls_table = "<table class=\"projects_list\">\n" ;
6220 if (defined $fetch) {
6221 if ($fetch eq $push) {
6222 $urls_table .= format_repo_url("URL", $fetch);
6223 } else {
6224 $urls_table .= format_repo_url("Fetch URL", $fetch);
6225 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6227 } elsif (defined $push) {
6228 $urls_table .= format_repo_url("Push URL", $push);
6229 } else {
6230 $urls_table .= format_repo_url("", "No remote URL");
6233 $urls_table .= "</table>\n";
6235 my $dots;
6236 if (defined $limit && $limit < @$heads) {
6237 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6240 print $urls_table;
6241 git_heads_body($heads, $head, 0, $limit, $dots);
6244 # Display a list of remote names with the respective fetch and push URLs
6245 sub git_remotes_list {
6246 my ($remotedata, $limit) = @_;
6247 print "<table class=\"heads\">\n";
6248 my $alternate = 1;
6249 my @remotes = sort keys %$remotedata;
6251 my $limited = $limit && $limit < @remotes;
6253 $#remotes = $limit - 1 if $limited;
6255 while (my $remote = shift @remotes) {
6256 my $rdata = $remotedata->{$remote};
6257 my $fetch = $rdata->{'fetch'};
6258 my $push = $rdata->{'push'};
6259 if ($alternate) {
6260 print "<tr class=\"dark\">\n";
6261 } else {
6262 print "<tr class=\"light\">\n";
6264 $alternate ^= 1;
6265 print "<td>" .
6266 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6267 -class=> "list name"},esc_html($remote)) .
6268 "</td>";
6269 print "<td class=\"link\">" .
6270 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6271 " | " .
6272 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6273 "</td>";
6275 print "</tr>\n";
6278 if ($limited) {
6279 print "<tr>\n" .
6280 "<td colspan=\"3\">" .
6281 $cgi->a({-href => href(action=>"remotes")}, "...") .
6282 "</td>\n" . "</tr>\n";
6285 print "</table>";
6288 # Display remote heads grouped by remote, unless there are too many
6289 # remotes, in which case we only display the remote names
6290 sub git_remotes_body {
6291 my ($remotedata, $limit, $head) = @_;
6292 if ($limit and $limit < keys %$remotedata) {
6293 git_remotes_list($remotedata, $limit);
6294 } else {
6295 fill_remote_heads($remotedata);
6296 while (my ($remote, $rdata) = each %$remotedata) {
6297 git_print_section({-class=>"remote", -id=>$remote},
6298 ["remotes", $remote, $remote], sub {
6299 git_remote_block($remote, $rdata, $limit, $head);
6305 sub git_search_message {
6306 my %co = @_;
6308 my $greptype;
6309 if ($searchtype eq 'commit') {
6310 $greptype = "--grep=";
6311 } elsif ($searchtype eq 'author') {
6312 $greptype = "--author=";
6313 } elsif ($searchtype eq 'committer') {
6314 $greptype = "--committer=";
6316 $greptype .= $searchtext;
6317 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6318 $greptype, '--regexp-ignore-case',
6319 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6321 my $paging_nav = '';
6322 if ($page > 0) {
6323 $paging_nav .=
6324 $cgi->a({-href => href(-replay=>1, page=>undef)},
6325 "first") .
6326 " &sdot; " .
6327 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6328 -accesskey => "p", -title => "Alt-p"}, "prev");
6329 } else {
6330 $paging_nav .= "first &sdot; prev";
6332 my $next_link = '';
6333 if ($#commitlist >= 100) {
6334 $next_link =
6335 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6336 -accesskey => "n", -title => "Alt-n"}, "next");
6337 $paging_nav .= " &sdot; $next_link";
6338 } else {
6339 $paging_nav .= " &sdot; next";
6342 git_header_html();
6344 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6345 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6346 if ($page == 0 && !@commitlist) {
6347 print "<p>No match.</p>\n";
6348 } else {
6349 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6352 git_footer_html();
6355 sub git_search_changes {
6356 my %co = @_;
6358 local $/ = "\n";
6359 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6360 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6361 ($search_use_regexp ? '--pickaxe-regex' : ())
6362 or die_error(500, "Open git-log failed");
6364 git_header_html();
6366 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6367 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6369 print "<table class=\"pickaxe search\">\n";
6370 my $alternate = 1;
6371 undef %co;
6372 my @files;
6373 while (my $line = <$fd>) {
6374 chomp $line;
6375 next unless $line;
6377 my %set = parse_difftree_raw_line($line);
6378 if (defined $set{'commit'}) {
6379 # finish previous commit
6380 if (%co) {
6381 print "</td>\n" .
6382 "<td class=\"link\">" .
6383 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6384 "commit") .
6385 " | " .
6386 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6387 hash_base=>$co{'id'})},
6388 "tree") .
6389 "</td>\n" .
6390 "</tr>\n";
6393 if ($alternate) {
6394 print "<tr class=\"dark\">\n";
6395 } else {
6396 print "<tr class=\"light\">\n";
6398 $alternate ^= 1;
6399 %co = parse_commit($set{'commit'});
6400 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6401 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6402 "<td><i>$author</i></td>\n" .
6403 "<td>" .
6404 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6405 -class => "list subject"},
6406 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6407 } elsif (defined $set{'to_id'}) {
6408 next if ($set{'to_id'} =~ m/^0{40}$/);
6410 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6411 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6412 -class => "list"},
6413 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6414 "<br/>\n";
6417 close $fd;
6419 # finish last commit (warning: repetition!)
6420 if (%co) {
6421 print "</td>\n" .
6422 "<td class=\"link\">" .
6423 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6424 "commit") .
6425 " | " .
6426 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6427 hash_base=>$co{'id'})},
6428 "tree") .
6429 "</td>\n" .
6430 "</tr>\n";
6433 print "</table>\n";
6435 git_footer_html();
6438 sub git_search_files {
6439 my %co = @_;
6441 local $/ = "\n";
6442 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6443 $search_use_regexp ? ('-E', '-i') : '-F',
6444 $searchtext, $co{'tree'}
6445 or die_error(500, "Open git-grep failed");
6447 git_header_html();
6449 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6450 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6452 print "<table class=\"grep_search\">\n";
6453 my $alternate = 1;
6454 my $matches = 0;
6455 my $lastfile = '';
6456 my $file_href;
6457 while (my $line = <$fd>) {
6458 chomp $line;
6459 my ($file, $lno, $ltext, $binary);
6460 last if ($matches++ > 1000);
6461 if ($line =~ /^Binary file (.+) matches$/) {
6462 $file = $1;
6463 $binary = 1;
6464 } else {
6465 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6466 $file =~ s/^$co{'tree'}://;
6468 if ($file ne $lastfile) {
6469 $lastfile and print "</td></tr>\n";
6470 if ($alternate++) {
6471 print "<tr class=\"dark\">\n";
6472 } else {
6473 print "<tr class=\"light\">\n";
6475 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6476 file_name=>$file);
6477 print "<td class=\"list\">".
6478 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6479 print "</td><td>\n";
6480 $lastfile = $file;
6482 if ($binary) {
6483 print "<div class=\"binary\">Binary file</div>\n";
6484 } else {
6485 $ltext = untabify($ltext);
6486 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6487 $ltext = esc_html($1, -nbsp=>1);
6488 $ltext .= '<span class="match">';
6489 $ltext .= esc_html($2, -nbsp=>1);
6490 $ltext .= '</span>';
6491 $ltext .= esc_html($3, -nbsp=>1);
6492 } else {
6493 $ltext = esc_html($ltext, -nbsp=>1);
6495 print "<div class=\"pre\">" .
6496 $cgi->a({-href => $file_href.'#l'.$lno,
6497 -class => "linenr"}, sprintf('%4i', $lno)) .
6498 ' ' . $ltext . "</div>\n";
6501 if ($lastfile) {
6502 print "</td></tr>\n";
6503 if ($matches > 1000) {
6504 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6506 } else {
6507 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6509 close $fd;
6511 print "</table>\n";
6513 git_footer_html();
6516 sub git_search_grep_body {
6517 my ($commitlist, $from, $to, $extra) = @_;
6518 $from = 0 unless defined $from;
6519 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6521 print "<table class=\"commit_search\">\n";
6522 my $alternate = 1;
6523 for (my $i = $from; $i <= $to; $i++) {
6524 my %co = %{$commitlist->[$i]};
6525 if (!%co) {
6526 next;
6528 my $commit = $co{'id'};
6529 if ($alternate) {
6530 print "<tr class=\"dark\">\n";
6531 } else {
6532 print "<tr class=\"light\">\n";
6534 $alternate ^= 1;
6535 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6536 format_author_html('td', \%co, 15, 5) .
6537 "<td>" .
6538 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6539 -class => "list subject"},
6540 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6541 my $comment = $co{'comment'};
6542 foreach my $line (@$comment) {
6543 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6544 my ($lead, $match, $trail) = ($1, $2, $3);
6545 $match = chop_str($match, 70, 5, 'center');
6546 my $contextlen = int((80 - length($match))/2);
6547 $contextlen = 30 if ($contextlen > 30);
6548 $lead = chop_str($lead, $contextlen, 10, 'left');
6549 $trail = chop_str($trail, $contextlen, 10, 'right');
6551 $lead = esc_html($lead);
6552 $match = esc_html($match);
6553 $trail = esc_html($trail);
6555 print "$lead<span class=\"match\">$match</span>$trail<br />";
6558 print "</td>\n" .
6559 "<td class=\"link\">" .
6560 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6561 " | " .
6562 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6563 " | " .
6564 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6565 print "</td>\n" .
6566 "</tr>\n";
6568 if (defined $extra) {
6569 print "<tr>\n" .
6570 "<td colspan=\"3\">$extra</td>\n" .
6571 "</tr>\n";
6573 print "</table>\n";
6576 ## ======================================================================
6577 ## ======================================================================
6578 ## actions
6580 sub git_project_list_load {
6581 my $empty_list_ok = shift;
6582 my $order = $input_params{'order'};
6583 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6584 die_error(400, "Unknown order parameter");
6587 my @list = git_get_projects_list($project_filter, $strict_export);
6588 if (!@list) {
6589 die_error(404, "No projects found") unless $empty_list_ok;
6592 return (\@list, $order);
6595 sub git_frontpage {
6596 my ($projlist, $order);
6598 if ($frontpage_no_project_list) {
6599 $project = undef;
6600 $project_filter = undef;
6601 } else {
6602 ($projlist, $order) = git_project_list_load(1);
6604 git_header_html();
6605 if (defined $home_text && -f $home_text) {
6606 print "<div class=\"index_include\">\n";
6607 insert_file($home_text);
6608 print "</div>\n";
6610 git_project_search_form($searchtext, $search_use_regexp);
6611 if ($frontpage_no_project_list) {
6612 my $show_ctags = gitweb_check_feature('ctags');
6613 if ($frontpage_no_project_list == 1 and $show_ctags) {
6614 my @projects = git_get_projects_list($project_filter, $strict_export);
6615 @projects = filter_forks_from_projects_list(\@projects) if gitweb_check_feature('forks');
6616 @projects = fill_project_list_info(\@projects, 'ctags');
6617 my $ctags = git_gather_all_ctags(\@projects);
6618 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6619 print git_show_project_tagcloud($cloud, 64);
6621 } else {
6622 git_project_list_body($projlist, $order);
6624 git_footer_html();
6627 sub git_project_list {
6628 my ($projlist, $order) = git_project_list_load();
6629 git_header_html();
6630 if (not $frontpage_no_project_list && defined $home_text && -f $home_text) {
6631 print "<div class=\"index_include\">\n";
6632 insert_file($home_text);
6633 print "</div>\n";
6635 git_project_search_form();
6636 git_project_list_body($projlist, $order);
6637 git_footer_html();
6640 sub git_forks {
6641 my $order = $input_params{'order'};
6642 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6643 die_error(400, "Unknown order parameter");
6646 my $filter = $project;
6647 $filter =~ s/\.git$//;
6648 my @list = git_get_projects_list($filter);
6649 if (!@list) {
6650 die_error(404, "No forks found");
6653 git_header_html();
6654 git_print_page_nav('','');
6655 git_print_header_div('summary', "$project forks");
6656 git_project_list_body(\@list, $order, undef, undef, undef, undef, 'forks');
6657 git_footer_html();
6660 sub git_project_index {
6661 my @projects = git_get_projects_list($project_filter, $strict_export);
6662 if (!@projects) {
6663 die_error(404, "No projects found");
6666 print $cgi->header(
6667 -type => 'text/plain',
6668 -charset => 'utf-8',
6669 -content_disposition => 'inline; filename="index.aux"');
6671 foreach my $pr (@projects) {
6672 if (!exists $pr->{'owner'}) {
6673 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6676 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6677 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6678 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6679 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6680 $path =~ s/ /\+/g;
6681 $owner =~ s/ /\+/g;
6683 print "$path $owner\n";
6687 sub git_summary {
6688 my $descr = git_get_project_description($project) || "none";
6689 my %co = parse_commit("HEAD");
6690 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6691 my $head = $co{'id'};
6692 my $remote_heads = gitweb_check_feature('remote_heads');
6694 my $owner = git_get_project_owner($project);
6696 my $refs = git_get_references();
6697 # These get_*_list functions return one more to allow us to see if
6698 # there are more ...
6699 my @taglist = git_get_tags_list(16);
6700 my @headlist = git_get_heads_list(16);
6701 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6702 my @forklist;
6703 my $check_forks = gitweb_check_feature('forks');
6705 if ($check_forks) {
6706 # find forks of a project
6707 my $filter = $project;
6708 $filter =~ s/\.git$//;
6709 @forklist = git_get_projects_list($filter);
6710 # filter out forks of forks
6711 @forklist = filter_forks_from_projects_list(\@forklist)
6712 if (@forklist);
6715 git_header_html();
6716 git_print_page_nav('summary','', $head);
6718 print "<div class=\"title\">&nbsp;</div>\n";
6719 print "<table class=\"projects_list\">\n" .
6720 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6721 if ($owner and not $omit_owner) {
6722 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6724 if (defined $cd{'rfc2822'}) {
6725 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6726 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6729 # use per project git URL list in $projectroot/$project/cloneurl
6730 # or make project git URL from git base URL and project name
6731 my $url_tag = "URL";
6732 my @url_list = git_get_project_url_list($project);
6733 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6734 foreach my $git_url (@url_list) {
6735 next unless $git_url;
6736 print format_repo_url($url_tag, $git_url);
6737 $url_tag = "";
6740 # Tag cloud
6741 my $show_ctags = gitweb_check_feature('ctags');
6742 if ($show_ctags) {
6743 my $ctags = git_get_project_ctags($project);
6744 if (%$ctags || $show_ctags !~ /^\d+$/) {
6745 # without ability to add tags, don't show if there are none
6746 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6747 print "<tr id=\"metadata_ctags\">" .
6748 "<td style=\"vertical-align:middle\">content tags<br />";
6749 print "</td>\n<td>" unless %$ctags;
6750 print "<form action=\"$show_ctags\" method=\"post\">" .
6751 "<input type=\"hidden\" name=\"p\" value=\"$project\"/>" .
6752 "add: <input type=\"text\" name=\"t\" size=\"10\" /></form>"
6753 unless $show_ctags =~ /^\d+$/;
6754 print "</td>\n<td>" if %$ctags;
6755 print git_show_project_tagcloud($cloud, 48)."</td>" .
6756 "</tr>\n";
6760 print "</table>\n";
6762 # If XSS prevention is on, we don't include README.html.
6763 # TODO: Allow a readme in some safe format.
6764 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6765 print "<div class=\"title\">readme</div>\n" .
6766 "<div class=\"readme\">\n";
6767 insert_file("$projectroot/$project/README.html");
6768 print "\n</div>\n"; # class="readme"
6771 # we need to request one more than 16 (0..15) to check if
6772 # those 16 are all
6773 my @commitlist = $head ? parse_commits($head, 17) : ();
6774 if (@commitlist) {
6775 git_print_header_div('shortlog');
6776 git_shortlog_body(\@commitlist, 0, 15, $refs,
6777 $#commitlist <= 15 ? undef :
6778 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6781 if (@taglist) {
6782 git_print_header_div('tags');
6783 git_tags_body(\@taglist, 0, 15,
6784 $#taglist <= 15 ? undef :
6785 $cgi->a({-href => href(action=>"tags")}, "..."));
6788 if (@headlist) {
6789 git_print_header_div('heads');
6790 git_heads_body(\@headlist, $head, 0, 15,
6791 $#headlist <= 15 ? undef :
6792 $cgi->a({-href => href(action=>"heads")}, "..."));
6795 if (%remotedata) {
6796 git_print_header_div('remotes');
6797 git_remotes_body(\%remotedata, 15, $head);
6800 if (@forklist) {
6801 git_print_header_div('forks');
6802 git_project_list_body(\@forklist, 'age', 0, 15,
6803 $#forklist <= 15 ? undef :
6804 $cgi->a({-href => href(action=>"forks")}, "..."),
6805 'no_header', 'forks');
6808 git_footer_html();
6811 sub git_tag {
6812 my %tag = parse_tag($hash);
6814 if (! %tag) {
6815 die_error(404, "Unknown tag object");
6818 my $head = git_get_head_hash($project);
6819 git_header_html();
6820 git_print_page_nav('','', $head,undef,$head);
6821 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6822 print "<div class=\"title_text\">\n" .
6823 "<table class=\"object_header\">\n" .
6824 "<tr>\n" .
6825 "<td>object</td>\n" .
6826 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6827 $tag{'object'}) . "</td>\n" .
6828 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6829 $tag{'type'}) . "</td>\n" .
6830 "</tr>\n";
6831 if (defined($tag{'author'})) {
6832 git_print_authorship_rows(\%tag, 'author');
6834 print "</table>\n\n" .
6835 "</div>\n";
6836 print "<div class=\"page_body\">";
6837 my $comment = $tag{'comment'};
6838 foreach my $line (@$comment) {
6839 chomp $line;
6840 print esc_html($line, -nbsp=>1) . "<br/>\n";
6842 print "</div>\n";
6843 git_footer_html();
6846 sub git_blame_common {
6847 my $format = shift || 'porcelain';
6848 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6849 $format = 'incremental';
6850 $action = 'blame_incremental'; # for page title etc
6853 # permissions
6854 gitweb_check_feature('blame')
6855 or die_error(403, "Blame view not allowed");
6857 # error checking
6858 die_error(400, "No file name given") unless $file_name;
6859 $hash_base ||= git_get_head_hash($project);
6860 die_error(404, "Couldn't find base commit") unless $hash_base;
6861 my %co = parse_commit($hash_base)
6862 or die_error(404, "Commit not found");
6863 my $ftype = "blob";
6864 if (!defined $hash) {
6865 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6866 or die_error(404, "Error looking up file");
6867 } else {
6868 $ftype = git_get_type($hash);
6869 if ($ftype !~ "blob") {
6870 die_error(400, "Object is not a blob");
6874 my $fd;
6875 if ($format eq 'incremental') {
6876 # get file contents (as base)
6877 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6878 or die_error(500, "Open git-cat-file failed");
6879 } elsif ($format eq 'data') {
6880 # run git-blame --incremental
6881 open $fd, "-|", git_cmd(), "blame", "--incremental",
6882 $hash_base, "--", $file_name
6883 or die_error(500, "Open git-blame --incremental failed");
6884 } else {
6885 # run git-blame --porcelain
6886 open $fd, "-|", git_cmd(), "blame", '-p',
6887 $hash_base, '--', $file_name
6888 or die_error(500, "Open git-blame --porcelain failed");
6890 binmode $fd, ':utf8';
6892 # incremental blame data returns early
6893 if ($format eq 'data') {
6894 print $cgi->header(
6895 -type=>"text/plain", -charset => "utf-8",
6896 -status=> "200 OK");
6897 local $| = 1; # output autoflush
6898 while (my $line = <$fd>) {
6899 print to_utf8($line);
6901 close $fd
6902 or print "ERROR $!\n";
6904 print 'END';
6905 if (defined $t0 && gitweb_check_feature('timed')) {
6906 print ' '.
6907 tv_interval($t0, [ gettimeofday() ]).
6908 ' '.$number_of_git_cmds;
6910 print "\n";
6912 return;
6915 # page header
6916 git_header_html();
6917 my $formats_nav =
6918 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6919 "blob") .
6920 " | ";
6921 if ($format eq 'incremental') {
6922 $formats_nav .=
6923 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6924 "blame") . " (non-incremental)";
6925 } else {
6926 $formats_nav .=
6927 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6928 "blame") . " (incremental)";
6930 $formats_nav .=
6931 " | " .
6932 $cgi->a({-href => href(action=>"history", -replay=>1)},
6933 "history") .
6934 " | " .
6935 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6936 "HEAD");
6937 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6938 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6939 git_print_page_path($file_name, $ftype, $hash_base);
6941 # page body
6942 if ($format eq 'incremental') {
6943 print "<noscript>\n<div class=\"error\"><center><b>\n".
6944 "This page requires JavaScript to run.\n Use ".
6945 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6946 'this page').
6947 " instead.\n".
6948 "</b></center></div>\n</noscript>\n";
6950 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6953 print qq!<div class="page_body">\n!;
6954 print qq!<div id="progress_info">... / ...</div>\n!
6955 if ($format eq 'incremental');
6956 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6957 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6958 qq!<thead>\n!.
6959 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6960 qq!</thead>\n!.
6961 qq!<tbody>\n!;
6963 my @rev_color = qw(light dark);
6964 my $num_colors = scalar(@rev_color);
6965 my $current_color = 0;
6967 if ($format eq 'incremental') {
6968 my $color_class = $rev_color[$current_color];
6970 #contents of a file
6971 my $linenr = 0;
6972 LINE:
6973 while (my $line = <$fd>) {
6974 chomp $line;
6975 $linenr++;
6977 print qq!<tr id="l$linenr" class="$color_class">!.
6978 qq!<td class="sha1"><a href=""> </a></td>!.
6979 qq!<td class="linenr">!.
6980 qq!<a class="linenr" href="">$linenr</a></td>!;
6981 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6982 print qq!</tr>\n!;
6985 } else { # porcelain, i.e. ordinary blame
6986 my %metainfo = (); # saves information about commits
6988 # blame data
6989 LINE:
6990 while (my $line = <$fd>) {
6991 chomp $line;
6992 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6993 # no <lines in group> for subsequent lines in group of lines
6994 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6995 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6996 if (!exists $metainfo{$full_rev}) {
6997 $metainfo{$full_rev} = { 'nprevious' => 0 };
6999 my $meta = $metainfo{$full_rev};
7000 my $data;
7001 while ($data = <$fd>) {
7002 chomp $data;
7003 last if ($data =~ s/^\t//); # contents of line
7004 if ($data =~ /^(\S+)(?: (.*))?$/) {
7005 $meta->{$1} = $2 unless exists $meta->{$1};
7007 if ($data =~ /^previous /) {
7008 $meta->{'nprevious'}++;
7011 my $short_rev = substr($full_rev, 0, 8);
7012 my $author = $meta->{'author'};
7013 my %date =
7014 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
7015 my $date = $date{'iso-tz'};
7016 if ($group_size) {
7017 $current_color = ($current_color + 1) % $num_colors;
7019 my $tr_class = $rev_color[$current_color];
7020 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
7021 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
7022 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
7023 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
7024 if ($group_size) {
7025 print "<td class=\"sha1\"";
7026 print " title=\"". esc_html($author) . ", $date\"";
7027 print " rowspan=\"$group_size\"" if ($group_size > 1);
7028 print ">";
7029 print $cgi->a({-href => href(action=>"commit",
7030 hash=>$full_rev,
7031 file_name=>$file_name)},
7032 esc_html($short_rev));
7033 if ($group_size >= 2) {
7034 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
7035 if (@author_initials) {
7036 print "<br />" .
7037 esc_html(join('', @author_initials));
7038 # or join('.', ...)
7041 print "</td>\n";
7043 # 'previous' <sha1 of parent commit> <filename at commit>
7044 if (exists $meta->{'previous'} &&
7045 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
7046 $meta->{'parent'} = $1;
7047 $meta->{'file_parent'} = unquote($2);
7049 my $linenr_commit =
7050 exists($meta->{'parent'}) ?
7051 $meta->{'parent'} : $full_rev;
7052 my $linenr_filename =
7053 exists($meta->{'file_parent'}) ?
7054 $meta->{'file_parent'} : unquote($meta->{'filename'});
7055 my $blamed = href(action => 'blame',
7056 file_name => $linenr_filename,
7057 hash_base => $linenr_commit);
7058 print "<td class=\"linenr\">";
7059 print $cgi->a({ -href => "$blamed#l$orig_lineno",
7060 -class => "linenr" },
7061 esc_html($lineno));
7062 print "</td>";
7063 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
7064 print "</tr>\n";
7065 } # end while
7069 # footer
7070 print "</tbody>\n".
7071 "</table>\n"; # class="blame"
7072 print "</div>\n"; # class="blame_body"
7073 close $fd
7074 or print "Reading blob failed\n";
7076 git_footer_html();
7079 sub git_blame {
7080 git_blame_common();
7083 sub git_blame_incremental {
7084 git_blame_common('incremental');
7087 sub git_blame_data {
7088 git_blame_common('data');
7091 sub git_tags {
7092 my $head = git_get_head_hash($project);
7093 git_header_html();
7094 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
7095 git_print_header_div('summary', $project);
7097 my @tagslist = git_get_tags_list();
7098 if (@tagslist) {
7099 git_tags_body(\@tagslist);
7101 git_footer_html();
7104 sub git_heads {
7105 my $head = git_get_head_hash($project);
7106 git_header_html();
7107 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
7108 git_print_header_div('summary', $project);
7110 my @headslist = git_get_heads_list();
7111 if (@headslist) {
7112 git_heads_body(\@headslist, $head);
7114 git_footer_html();
7117 # used both for single remote view and for list of all the remotes
7118 sub git_remotes {
7119 gitweb_check_feature('remote_heads')
7120 or die_error(403, "Remote heads view is disabled");
7122 my $head = git_get_head_hash($project);
7123 my $remote = $input_params{'hash'};
7125 my $remotedata = git_get_remotes_list($remote);
7126 die_error(500, "Unable to get remote information") unless defined $remotedata;
7128 unless (%$remotedata) {
7129 die_error(404, defined $remote ?
7130 "Remote $remote not found" :
7131 "No remotes found");
7134 git_header_html(undef, undef, -action_extra => $remote);
7135 git_print_page_nav('', '', $head, undef, $head,
7136 format_ref_views($remote ? '' : 'remotes'));
7138 fill_remote_heads($remotedata);
7139 if (defined $remote) {
7140 git_print_header_div('remotes', "$remote remote for $project");
7141 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7142 } else {
7143 git_print_header_div('summary', "$project remotes");
7144 git_remotes_body($remotedata, undef, $head);
7147 git_footer_html();
7150 sub git_blob_plain {
7151 my $type = shift;
7152 my $expires;
7154 if (!defined $hash) {
7155 if (defined $file_name) {
7156 my $base = $hash_base || git_get_head_hash($project);
7157 $hash = git_get_hash_by_path($base, $file_name, "blob")
7158 or die_error(404, "Cannot find file");
7159 } else {
7160 die_error(400, "No file name defined");
7162 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7163 # blobs defined by non-textual hash id's can be cached
7164 $expires = "+1d";
7167 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7168 or die_error(500, "Open git-cat-file blob '$hash' failed");
7170 # content-type (can include charset)
7171 $type = blob_contenttype($fd, $file_name, $type);
7173 # "save as" filename, even when no $file_name is given
7174 my $save_as = "$hash";
7175 if (defined $file_name) {
7176 $save_as = $file_name;
7177 } elsif ($type =~ m/^text\//) {
7178 $save_as .= '.txt';
7181 # With XSS prevention on, blobs of all types except a few known safe
7182 # ones are served with "Content-Disposition: attachment" to make sure
7183 # they don't run in our security domain. For certain image types,
7184 # blob view writes an <img> tag referring to blob_plain view, and we
7185 # want to be sure not to break that by serving the image as an
7186 # attachment (though Firefox 3 doesn't seem to care).
7187 my $sandbox = $prevent_xss &&
7188 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7190 # serve text/* as text/plain
7191 if ($prevent_xss &&
7192 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7193 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7194 my $rest = $1;
7195 $rest = defined $rest ? $rest : '';
7196 $type = "text/plain$rest";
7199 print $cgi->header(
7200 -type => $type,
7201 -expires => $expires,
7202 -content_disposition =>
7203 ($sandbox ? 'attachment' : 'inline')
7204 . '; filename="' . $save_as . '"');
7205 local $/ = undef;
7206 binmode STDOUT, ':raw';
7207 print <$fd>;
7208 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7209 close $fd;
7212 sub git_blob {
7213 my $expires;
7215 if (!defined $hash) {
7216 if (defined $file_name) {
7217 my $base = $hash_base || git_get_head_hash($project);
7218 $hash = git_get_hash_by_path($base, $file_name, "blob")
7219 or die_error(404, "Cannot find file");
7220 } else {
7221 die_error(400, "No file name defined");
7223 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7224 # blobs defined by non-textual hash id's can be cached
7225 $expires = "+1d";
7228 my $have_blame = gitweb_check_feature('blame');
7229 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7230 or die_error(500, "Couldn't cat $file_name, $hash");
7231 my $mimetype = blob_mimetype($fd, $file_name);
7232 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7233 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7234 close $fd;
7235 return git_blob_plain($mimetype);
7237 # we can have blame only for text/* mimetype
7238 $have_blame &&= ($mimetype =~ m!^text/!);
7240 my $highlight = gitweb_check_feature('highlight');
7241 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7242 $fd = run_highlighter($fd, $highlight, $syntax)
7243 if $syntax;
7245 git_header_html(undef, $expires);
7246 my $formats_nav = '';
7247 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7248 if (defined $file_name) {
7249 if ($have_blame) {
7250 $formats_nav .=
7251 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7252 "blame") .
7253 " | ";
7255 $formats_nav .=
7256 $cgi->a({-href => href(action=>"history", -replay=>1)},
7257 "history") .
7258 " | " .
7259 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7260 "raw") .
7261 " | " .
7262 $cgi->a({-href => href(action=>"blob",
7263 hash_base=>"HEAD", file_name=>$file_name)},
7264 "HEAD");
7265 } else {
7266 $formats_nav .=
7267 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7268 "raw");
7270 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7271 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7272 } else {
7273 print "<div class=\"page_nav\">\n" .
7274 "<br/><br/></div>\n" .
7275 "<div class=\"title\">".esc_html($hash)."</div>\n";
7277 git_print_page_path($file_name, "blob", $hash_base);
7278 print "<div class=\"page_body\">\n";
7279 if ($mimetype =~ m!^image/!) {
7280 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7281 if ($file_name) {
7282 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7284 print qq! src="! .
7285 href(action=>"blob_plain", hash=>$hash,
7286 hash_base=>$hash_base, file_name=>$file_name) .
7287 qq!" />\n!;
7288 } else {
7289 my $nr;
7290 while (my $line = <$fd>) {
7291 chomp $line;
7292 $nr++;
7293 $line = untabify($line);
7294 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7295 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7296 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7299 close $fd
7300 or print "Reading blob failed.\n";
7301 print "</div>";
7302 git_footer_html();
7305 sub git_tree {
7306 if (!defined $hash_base) {
7307 $hash_base = "HEAD";
7309 if (!defined $hash) {
7310 if (defined $file_name) {
7311 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7312 } else {
7313 $hash = $hash_base;
7316 die_error(404, "No such tree") unless defined($hash);
7318 my $show_sizes = gitweb_check_feature('show-sizes');
7319 my $have_blame = gitweb_check_feature('blame');
7321 my @entries = ();
7323 local $/ = "\0";
7324 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7325 ($show_sizes ? '-l' : ()), @extra_options, $hash
7326 or die_error(500, "Open git-ls-tree failed");
7327 @entries = map { chomp; $_ } <$fd>;
7328 close $fd
7329 or die_error(404, "Reading tree failed");
7332 my $refs = git_get_references();
7333 my $ref = format_ref_marker($refs, $hash_base);
7334 git_header_html();
7335 my $basedir = '';
7336 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7337 my @views_nav = ();
7338 if (defined $file_name) {
7339 push @views_nav,
7340 $cgi->a({-href => href(action=>"history", -replay=>1)},
7341 "history"),
7342 $cgi->a({-href => href(action=>"tree",
7343 hash_base=>"HEAD", file_name=>$file_name)},
7344 "HEAD"),
7346 my $snapshot_links = format_snapshot_links($hash);
7347 if (defined $snapshot_links) {
7348 # FIXME: Should be available when we have no hash base as well.
7349 push @views_nav, $snapshot_links;
7351 git_print_page_nav('tree','', $hash_base, undef, undef,
7352 join(' | ', @views_nav));
7353 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7354 } else {
7355 undef $hash_base;
7356 print "<div class=\"page_nav\">\n";
7357 print "<br/><br/></div>\n";
7358 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7360 if (defined $file_name) {
7361 $basedir = $file_name;
7362 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7363 $basedir .= '/';
7365 git_print_page_path($file_name, 'tree', $hash_base);
7367 print "<div class=\"page_body\">\n";
7368 print "<table class=\"tree\">\n";
7369 my $alternate = 1;
7370 # '..' (top directory) link if possible
7371 if (defined $hash_base &&
7372 defined $file_name && $file_name =~ m![^/]+$!) {
7373 if ($alternate) {
7374 print "<tr class=\"dark\">\n";
7375 } else {
7376 print "<tr class=\"light\">\n";
7378 $alternate ^= 1;
7380 my $up = $file_name;
7381 $up =~ s!/?[^/]+$!!;
7382 undef $up unless $up;
7383 # based on git_print_tree_entry
7384 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7385 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7386 print '<td class="list">';
7387 print $cgi->a({-href => href(action=>"tree",
7388 hash_base=>$hash_base,
7389 file_name=>$up)},
7390 "..");
7391 print "</td>\n";
7392 print "<td class=\"link\"></td>\n";
7394 print "</tr>\n";
7396 foreach my $line (@entries) {
7397 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7399 if ($alternate) {
7400 print "<tr class=\"dark\">\n";
7401 } else {
7402 print "<tr class=\"light\">\n";
7404 $alternate ^= 1;
7406 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7408 print "</tr>\n";
7410 print "</table>\n" .
7411 "</div>";
7412 git_footer_html();
7415 sub sanitize_for_filename {
7416 my $name = shift;
7418 $name =~ s!/!-!g;
7419 $name =~ s/[^[:alnum:]_.-]//g;
7421 return $name;
7424 sub snapshot_name {
7425 my ($project, $hash) = @_;
7427 # path/to/project.git -> project
7428 # path/to/project/.git -> project
7429 my $name = to_utf8($project);
7430 $name =~ s,([^/])/*\.git$,$1,;
7431 $name = sanitize_for_filename(basename($name));
7433 my $ver = $hash;
7434 if ($hash =~ /^[0-9a-fA-F]+$/) {
7435 # shorten SHA-1 hash
7436 my $full_hash = git_get_full_hash($project, $hash);
7437 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7438 $ver = git_get_short_hash($project, $hash);
7440 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7441 # tags don't need shortened SHA-1 hash
7442 $ver = $1;
7443 } else {
7444 # branches and other need shortened SHA-1 hash
7445 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7446 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7447 my $ref_dir = (defined $1) ? $1 : '';
7448 $ver = $2;
7450 $ref_dir = sanitize_for_filename($ref_dir);
7451 # for refs neither in heads nor remotes we want to
7452 # add a ref dir to archive name
7453 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7454 $ver = $ref_dir . '-' . $ver;
7457 $ver .= '-' . git_get_short_hash($project, $hash);
7459 # special case of sanitization for filename - we change
7460 # slashes to dots instead of dashes
7461 # in case of hierarchical branch names
7462 $ver =~ s!/!.!g;
7463 $ver =~ s/[^[:alnum:]_.-]//g;
7465 # name = project-version_string
7466 $name = "$name-$ver";
7468 return wantarray ? ($name, $name) : $name;
7471 sub exit_if_unmodified_since {
7472 my ($latest_epoch) = @_;
7473 our $cgi;
7475 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7476 if (defined $if_modified) {
7477 my $since;
7478 if (eval { require HTTP::Date; 1; }) {
7479 $since = HTTP::Date::str2time($if_modified);
7480 } elsif (eval { require Time::ParseDate; 1; }) {
7481 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7483 if (defined $since && $latest_epoch <= $since) {
7484 my %latest_date = parse_date($latest_epoch);
7485 print $cgi->header(
7486 -last_modified => $latest_date{'rfc2822'},
7487 -status => '304 Not Modified');
7488 goto DONE_GITWEB;
7493 sub git_snapshot {
7494 my $format = $input_params{'snapshot_format'};
7495 if (!@snapshot_fmts) {
7496 die_error(403, "Snapshots not allowed");
7498 # default to first supported snapshot format
7499 $format ||= $snapshot_fmts[0];
7500 if ($format !~ m/^[a-z0-9]+$/) {
7501 die_error(400, "Invalid snapshot format parameter");
7502 } elsif (!exists($known_snapshot_formats{$format})) {
7503 die_error(400, "Unknown snapshot format");
7504 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7505 die_error(403, "Snapshot format not allowed");
7506 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7507 die_error(403, "Unsupported snapshot format");
7510 my $type = git_get_type("$hash^{}");
7511 if (!$type) {
7512 die_error(404, 'Object does not exist');
7513 } elsif ($type eq 'blob') {
7514 die_error(400, 'Object is not a tree-ish');
7517 my ($name, $prefix) = snapshot_name($project, $hash);
7518 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7520 my %co = parse_commit($hash);
7521 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7523 my $cmd = quote_command(
7524 git_cmd(), 'archive',
7525 "--format=$known_snapshot_formats{$format}{'format'}",
7526 "--prefix=$prefix/", $hash);
7527 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7528 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7531 $filename =~ s/(["\\])/\\$1/g;
7532 my %latest_date;
7533 if (%co) {
7534 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7537 print $cgi->header(
7538 -type => $known_snapshot_formats{$format}{'type'},
7539 -content_disposition => 'inline; filename="' . $filename . '"',
7540 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7541 -status => '200 OK');
7543 open my $fd, "-|", $cmd
7544 or die_error(500, "Execute git-archive failed");
7545 binmode STDOUT, ':raw';
7546 print <$fd>;
7547 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7548 close $fd;
7551 sub git_log_generic {
7552 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7554 my $head = git_get_head_hash($project);
7555 if (!defined $base) {
7556 $base = $head;
7558 if (!defined $page) {
7559 $page = 0;
7561 my $refs = git_get_references();
7563 my $commit_hash = $base;
7564 if (defined $parent) {
7565 $commit_hash = "$parent..$base";
7567 my @commitlist =
7568 parse_commits($commit_hash, 101, (100 * $page),
7569 defined $file_name ? ($file_name, "--full-history") : ());
7571 my $ftype;
7572 if (!defined $file_hash && defined $file_name) {
7573 # some commits could have deleted file in question,
7574 # and not have it in tree, but one of them has to have it
7575 for (my $i = 0; $i < @commitlist; $i++) {
7576 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7577 last if defined $file_hash;
7580 if (defined $file_hash) {
7581 $ftype = git_get_type($file_hash);
7583 if (defined $file_name && !defined $ftype) {
7584 die_error(500, "Unknown type of object");
7586 my %co;
7587 if (defined $file_name) {
7588 %co = parse_commit($base)
7589 or die_error(404, "Unknown commit object");
7593 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7594 my $next_link = '';
7595 if ($#commitlist >= 100) {
7596 $next_link =
7597 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7598 -accesskey => "n", -title => "Alt-n"}, "next");
7600 my $patch_max = gitweb_get_feature('patches');
7601 if ($patch_max && !defined $file_name) {
7602 if ($patch_max < 0 || @commitlist <= $patch_max) {
7603 $paging_nav .= " &sdot; " .
7604 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7605 "patches");
7609 git_header_html();
7610 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7611 if (defined $file_name) {
7612 git_print_header_div('commit', esc_html($co{'title'}), $base);
7613 } else {
7614 git_print_header_div('summary', $project)
7616 git_print_page_path($file_name, $ftype, $hash_base)
7617 if (defined $file_name);
7619 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7620 $file_name, $file_hash, $ftype);
7622 git_footer_html();
7625 sub git_log {
7626 git_log_generic('log', \&git_log_body,
7627 $hash, $hash_parent);
7630 sub git_commit {
7631 $hash ||= $hash_base || "HEAD";
7632 my %co = parse_commit($hash)
7633 or die_error(404, "Unknown commit object");
7635 my $parent = $co{'parent'};
7636 my $parents = $co{'parents'}; # listref
7638 # we need to prepare $formats_nav before any parameter munging
7639 my $formats_nav;
7640 if (!defined $parent) {
7641 # --root commitdiff
7642 $formats_nav .= '(initial)';
7643 } elsif (@$parents == 1) {
7644 # single parent commit
7645 $formats_nav .=
7646 '(parent: ' .
7647 $cgi->a({-href => href(action=>"commit",
7648 hash=>$parent)},
7649 esc_html(substr($parent, 0, 7))) .
7650 ')';
7651 } else {
7652 # merge commit
7653 $formats_nav .=
7654 '(merge: ' .
7655 join(' ', map {
7656 $cgi->a({-href => href(action=>"commit",
7657 hash=>$_)},
7658 esc_html(substr($_, 0, 7)));
7659 } @$parents ) .
7660 ')';
7662 if (gitweb_check_feature('patches') && @$parents <= 1) {
7663 $formats_nav .= " | " .
7664 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7665 "patch");
7668 if (!defined $parent) {
7669 $parent = "--root";
7671 my @difftree;
7672 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7673 @diff_opts,
7674 (@$parents <= 1 ? $parent : '-c'),
7675 $hash, "--"
7676 or die_error(500, "Open git-diff-tree failed");
7677 @difftree = map { chomp; $_ } <$fd>;
7678 close $fd or die_error(404, "Reading git-diff-tree failed");
7680 # non-textual hash id's can be cached
7681 my $expires;
7682 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7683 $expires = "+1d";
7685 my $refs = git_get_references();
7686 my $ref = format_ref_marker($refs, $co{'id'});
7688 git_header_html(undef, $expires);
7689 git_print_page_nav('commit', '',
7690 $hash, $co{'tree'}, $hash,
7691 $formats_nav);
7693 if (defined $co{'parent'}) {
7694 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7695 } else {
7696 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7698 print "<div class=\"title_text\">\n" .
7699 "<table class=\"object_header\">\n";
7700 git_print_authorship_rows(\%co);
7701 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7702 print "<tr>" .
7703 "<td>tree</td>" .
7704 "<td class=\"sha1\">" .
7705 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7706 class => "list"}, $co{'tree'}) .
7707 "</td>" .
7708 "<td class=\"link\">" .
7709 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7710 "tree");
7711 my $snapshot_links = format_snapshot_links($hash);
7712 if (defined $snapshot_links) {
7713 print " | " . $snapshot_links;
7715 print "</td>" .
7716 "</tr>\n";
7718 foreach my $par (@$parents) {
7719 print "<tr>" .
7720 "<td>parent</td>" .
7721 "<td class=\"sha1\">" .
7722 $cgi->a({-href => href(action=>"commit", hash=>$par),
7723 class => "list"}, $par) .
7724 "</td>" .
7725 "<td class=\"link\">" .
7726 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7727 " | " .
7728 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7729 "</td>" .
7730 "</tr>\n";
7732 print "</table>".
7733 "</div>\n";
7735 print "<div class=\"page_body\">\n";
7736 git_print_log($co{'comment'});
7737 print "</div>\n";
7739 git_difftree_body(\@difftree, $hash, @$parents);
7741 git_footer_html();
7744 sub git_object {
7745 # object is defined by:
7746 # - hash or hash_base alone
7747 # - hash_base and file_name
7748 my $type;
7750 # - hash or hash_base alone
7751 if ($hash || ($hash_base && !defined $file_name)) {
7752 my $object_id = $hash || $hash_base;
7754 open my $fd, "-|", quote_command(
7755 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7756 or die_error(404, "Object does not exist");
7757 $type = <$fd>;
7758 chomp $type;
7759 close $fd
7760 or die_error(404, "Object does not exist");
7762 # - hash_base and file_name
7763 } elsif ($hash_base && defined $file_name) {
7764 $file_name =~ s,/+$,,;
7766 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7767 or die_error(404, "Base object does not exist");
7769 # here errors should not happen
7770 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7771 or die_error(500, "Open git-ls-tree failed");
7772 my $line = <$fd>;
7773 close $fd;
7775 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7776 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7777 die_error(404, "File or directory for given base does not exist");
7779 $type = $2;
7780 $hash = $3;
7781 } else {
7782 die_error(400, "Not enough information to find object");
7785 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7786 hash=>$hash, hash_base=>$hash_base,
7787 file_name=>$file_name),
7788 -status => '302 Found');
7791 sub git_blobdiff {
7792 my $format = shift || 'html';
7793 my $diff_style = $input_params{'diff_style'} || 'inline';
7795 my $fd;
7796 my @difftree;
7797 my %diffinfo;
7798 my $expires;
7800 # preparing $fd and %diffinfo for git_patchset_body
7801 # new style URI
7802 if (defined $hash_base && defined $hash_parent_base) {
7803 if (defined $file_name) {
7804 # read raw output
7805 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7806 $hash_parent_base, $hash_base,
7807 "--", (defined $file_parent ? $file_parent : ()), $file_name
7808 or die_error(500, "Open git-diff-tree failed");
7809 @difftree = map { chomp; $_ } <$fd>;
7810 close $fd
7811 or die_error(404, "Reading git-diff-tree failed");
7812 @difftree
7813 or die_error(404, "Blob diff not found");
7815 } elsif (defined $hash &&
7816 $hash =~ /[0-9a-fA-F]{40}/) {
7817 # try to find filename from $hash
7819 # read filtered raw output
7820 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7821 $hash_parent_base, $hash_base, "--"
7822 or die_error(500, "Open git-diff-tree failed");
7823 @difftree =
7824 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7825 # $hash == to_id
7826 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7827 map { chomp; $_ } <$fd>;
7828 close $fd
7829 or die_error(404, "Reading git-diff-tree failed");
7830 @difftree
7831 or die_error(404, "Blob diff not found");
7833 } else {
7834 die_error(400, "Missing one of the blob diff parameters");
7837 if (@difftree > 1) {
7838 die_error(400, "Ambiguous blob diff specification");
7841 %diffinfo = parse_difftree_raw_line($difftree[0]);
7842 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7843 $file_name ||= $diffinfo{'to_file'};
7845 $hash_parent ||= $diffinfo{'from_id'};
7846 $hash ||= $diffinfo{'to_id'};
7848 # non-textual hash id's can be cached
7849 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7850 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7851 $expires = '+1d';
7854 # open patch output
7855 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7856 '-p', ($format eq 'html' ? "--full-index" : ()),
7857 $hash_parent_base, $hash_base,
7858 "--", (defined $file_parent ? $file_parent : ()), $file_name
7859 or die_error(500, "Open git-diff-tree failed");
7862 # old/legacy style URI -- not generated anymore since 1.4.3.
7863 if (!%diffinfo) {
7864 die_error('404 Not Found', "Missing one of the blob diff parameters")
7867 # header
7868 if ($format eq 'html') {
7869 my $formats_nav =
7870 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7871 "raw");
7872 $formats_nav .= diff_style_nav($diff_style);
7873 git_header_html(undef, $expires);
7874 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7875 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7876 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7877 } else {
7878 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7879 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7881 if (defined $file_name) {
7882 git_print_page_path($file_name, "blob", $hash_base);
7883 } else {
7884 print "<div class=\"page_path\"></div>\n";
7887 } elsif ($format eq 'plain') {
7888 print $cgi->header(
7889 -type => 'text/plain',
7890 -charset => 'utf-8',
7891 -expires => $expires,
7892 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7894 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7896 } else {
7897 die_error(400, "Unknown blobdiff format");
7900 # patch
7901 if ($format eq 'html') {
7902 print "<div class=\"page_body\">\n";
7904 git_patchset_body($fd, $diff_style,
7905 [ \%diffinfo ], $hash_base, $hash_parent_base);
7906 close $fd;
7908 print "</div>\n"; # class="page_body"
7909 git_footer_html();
7911 } else {
7912 while (my $line = <$fd>) {
7913 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7914 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7916 print $line;
7918 last if $line =~ m!^\+\+\+!;
7920 local $/ = undef;
7921 print <$fd>;
7922 close $fd;
7926 sub git_blobdiff_plain {
7927 git_blobdiff('plain');
7930 # assumes that it is added as later part of already existing navigation,
7931 # so it returns "| foo | bar" rather than just "foo | bar"
7932 sub diff_style_nav {
7933 my ($diff_style, $is_combined) = @_;
7934 $diff_style ||= 'inline';
7936 return "" if ($is_combined);
7938 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7939 my %styles = @styles;
7940 @styles =
7941 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7943 return join '',
7944 map { " | ".$_ }
7945 map {
7946 $_ eq $diff_style ? $styles{$_} :
7947 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7948 } @styles;
7951 sub git_commitdiff {
7952 my %params = @_;
7953 my $format = $params{-format} || 'html';
7954 my $diff_style = $input_params{'diff_style'} || 'inline';
7956 my ($patch_max) = gitweb_get_feature('patches');
7957 if ($format eq 'patch') {
7958 die_error(403, "Patch view not allowed") unless $patch_max;
7961 $hash ||= $hash_base || "HEAD";
7962 my %co = parse_commit($hash)
7963 or die_error(404, "Unknown commit object");
7965 # choose format for commitdiff for merge
7966 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7967 $hash_parent = '--cc';
7969 # we need to prepare $formats_nav before almost any parameter munging
7970 my $formats_nav;
7971 if ($format eq 'html') {
7972 $formats_nav =
7973 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7974 "raw");
7975 if ($patch_max && @{$co{'parents'}} <= 1) {
7976 $formats_nav .= " | " .
7977 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7978 "patch");
7980 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7982 if (defined $hash_parent &&
7983 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7984 # commitdiff with two commits given
7985 my $hash_parent_short = $hash_parent;
7986 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7987 $hash_parent_short = substr($hash_parent, 0, 7);
7989 $formats_nav .=
7990 ' (from';
7991 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7992 if ($co{'parents'}[$i] eq $hash_parent) {
7993 $formats_nav .= ' parent ' . ($i+1);
7994 last;
7997 $formats_nav .= ': ' .
7998 $cgi->a({-href => href(-replay=>1,
7999 hash=>$hash_parent, hash_base=>undef)},
8000 esc_html($hash_parent_short)) .
8001 ')';
8002 } elsif (!$co{'parent'}) {
8003 # --root commitdiff
8004 $formats_nav .= ' (initial)';
8005 } elsif (scalar @{$co{'parents'}} == 1) {
8006 # single parent commit
8007 $formats_nav .=
8008 ' (parent: ' .
8009 $cgi->a({-href => href(-replay=>1,
8010 hash=>$co{'parent'}, hash_base=>undef)},
8011 esc_html(substr($co{'parent'}, 0, 7))) .
8012 ')';
8013 } else {
8014 # merge commit
8015 if ($hash_parent eq '--cc') {
8016 $formats_nav .= ' | ' .
8017 $cgi->a({-href => href(-replay=>1,
8018 hash=>$hash, hash_parent=>'-c')},
8019 'combined');
8020 } else { # $hash_parent eq '-c'
8021 $formats_nav .= ' | ' .
8022 $cgi->a({-href => href(-replay=>1,
8023 hash=>$hash, hash_parent=>'--cc')},
8024 'compact');
8026 $formats_nav .=
8027 ' (merge: ' .
8028 join(' ', map {
8029 $cgi->a({-href => href(-replay=>1,
8030 hash=>$_, hash_base=>undef)},
8031 esc_html(substr($_, 0, 7)));
8032 } @{$co{'parents'}} ) .
8033 ')';
8037 my $hash_parent_param = $hash_parent;
8038 if (!defined $hash_parent_param) {
8039 # --cc for multiple parents, --root for parentless
8040 $hash_parent_param =
8041 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
8044 # read commitdiff
8045 my $fd;
8046 my @difftree;
8047 if ($format eq 'html') {
8048 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8049 "--no-commit-id", "--patch-with-raw", "--full-index",
8050 $hash_parent_param, $hash, "--"
8051 or die_error(500, "Open git-diff-tree failed");
8053 while (my $line = <$fd>) {
8054 chomp $line;
8055 # empty line ends raw part of diff-tree output
8056 last unless $line;
8057 push @difftree, scalar parse_difftree_raw_line($line);
8060 } elsif ($format eq 'plain') {
8061 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8062 '-p', $hash_parent_param, $hash, "--"
8063 or die_error(500, "Open git-diff-tree failed");
8064 } elsif ($format eq 'patch') {
8065 # For commit ranges, we limit the output to the number of
8066 # patches specified in the 'patches' feature.
8067 # For single commits, we limit the output to a single patch,
8068 # diverging from the git-format-patch default.
8069 my @commit_spec = ();
8070 if ($hash_parent) {
8071 if ($patch_max > 0) {
8072 push @commit_spec, "-$patch_max";
8074 push @commit_spec, '-n', "$hash_parent..$hash";
8075 } else {
8076 if ($params{-single}) {
8077 push @commit_spec, '-1';
8078 } else {
8079 if ($patch_max > 0) {
8080 push @commit_spec, "-$patch_max";
8082 push @commit_spec, "-n";
8084 push @commit_spec, '--root', $hash;
8086 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
8087 '--encoding=utf8', '--stdout', @commit_spec
8088 or die_error(500, "Open git-format-patch failed");
8089 } else {
8090 die_error(400, "Unknown commitdiff format");
8093 # non-textual hash id's can be cached
8094 my $expires;
8095 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8096 $expires = "+1d";
8099 # write commit message
8100 if ($format eq 'html') {
8101 my $refs = git_get_references();
8102 my $ref = format_ref_marker($refs, $co{'id'});
8104 git_header_html(undef, $expires);
8105 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
8106 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
8107 print "<div class=\"title_text\">\n" .
8108 "<table class=\"object_header\">\n";
8109 git_print_authorship_rows(\%co);
8110 print "</table>".
8111 "</div>\n";
8112 print "<div class=\"page_body\">\n";
8113 if (@{$co{'comment'}} > 1) {
8114 print "<div class=\"log\">\n";
8115 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
8116 print "</div>\n"; # class="log"
8119 } elsif ($format eq 'plain') {
8120 my $refs = git_get_references("tags");
8121 my $tagname = git_get_rev_name_tags($hash);
8122 my $filename = basename($project) . "-$hash.patch";
8124 print $cgi->header(
8125 -type => 'text/plain',
8126 -charset => 'utf-8',
8127 -expires => $expires,
8128 -content_disposition => 'inline; filename="' . "$filename" . '"');
8129 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8130 print "From: " . to_utf8($co{'author'}) . "\n";
8131 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8132 print "Subject: " . to_utf8($co{'title'}) . "\n";
8134 print "X-Git-Tag: $tagname\n" if $tagname;
8135 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8137 foreach my $line (@{$co{'comment'}}) {
8138 print to_utf8($line) . "\n";
8140 print "---\n\n";
8141 } elsif ($format eq 'patch') {
8142 my $filename = basename($project) . "-$hash.patch";
8144 print $cgi->header(
8145 -type => 'text/plain',
8146 -charset => 'utf-8',
8147 -expires => $expires,
8148 -content_disposition => 'inline; filename="' . "$filename" . '"');
8151 # write patch
8152 if ($format eq 'html') {
8153 my $use_parents = !defined $hash_parent ||
8154 $hash_parent eq '-c' || $hash_parent eq '--cc';
8155 git_difftree_body(\@difftree, $hash,
8156 $use_parents ? @{$co{'parents'}} : $hash_parent);
8157 print "<br/>\n";
8159 git_patchset_body($fd, $diff_style,
8160 \@difftree, $hash,
8161 $use_parents ? @{$co{'parents'}} : $hash_parent);
8162 close $fd;
8163 print "</div>\n"; # class="page_body"
8164 git_footer_html();
8166 } elsif ($format eq 'plain') {
8167 local $/ = undef;
8168 print <$fd>;
8169 close $fd
8170 or print "Reading git-diff-tree failed\n";
8171 } elsif ($format eq 'patch') {
8172 local $/ = undef;
8173 print <$fd>;
8174 close $fd
8175 or print "Reading git-format-patch failed\n";
8179 sub git_commitdiff_plain {
8180 git_commitdiff(-format => 'plain');
8183 # format-patch-style patches
8184 sub git_patch {
8185 git_commitdiff(-format => 'patch', -single => 1);
8188 sub git_patches {
8189 git_commitdiff(-format => 'patch');
8192 sub git_history {
8193 git_log_generic('history', \&git_history_body,
8194 $hash_base, $hash_parent_base,
8195 $file_name, $hash);
8198 sub git_search {
8199 $searchtype ||= 'commit';
8201 # check if appropriate features are enabled
8202 gitweb_check_feature('search')
8203 or die_error(403, "Search is disabled");
8204 if ($searchtype eq 'pickaxe') {
8205 # pickaxe may take all resources of your box and run for several minutes
8206 # with every query - so decide by yourself how public you make this feature
8207 gitweb_check_feature('pickaxe')
8208 or die_error(403, "Pickaxe search is disabled");
8210 if ($searchtype eq 'grep') {
8211 # grep search might be potentially CPU-intensive, too
8212 gitweb_check_feature('grep')
8213 or die_error(403, "Grep search is disabled");
8216 if (!defined $searchtext) {
8217 die_error(400, "Text field is empty");
8219 if (!defined $hash) {
8220 $hash = git_get_head_hash($project);
8222 my %co = parse_commit($hash);
8223 if (!%co) {
8224 die_error(404, "Unknown commit object");
8226 if (!defined $page) {
8227 $page = 0;
8230 if ($searchtype eq 'commit' ||
8231 $searchtype eq 'author' ||
8232 $searchtype eq 'committer') {
8233 git_search_message(%co);
8234 } elsif ($searchtype eq 'pickaxe') {
8235 git_search_changes(%co);
8236 } elsif ($searchtype eq 'grep') {
8237 git_search_files(%co);
8238 } else {
8239 die_error(400, "Unknown search type");
8243 sub git_search_help {
8244 git_header_html();
8245 git_print_page_nav('','', $hash,$hash,$hash);
8246 print <<EOT;
8247 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8248 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8249 the pattern entered is recognized as the POSIX extended
8250 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8251 insensitive).</p>
8252 <dl>
8253 <dt><b>commit</b></dt>
8254 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8256 my $have_grep = gitweb_check_feature('grep');
8257 if ($have_grep) {
8258 print <<EOT;
8259 <dt><b>grep</b></dt>
8260 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8261 a different one) are searched for the given pattern. On large trees, this search can take
8262 a while and put some strain on the server, so please use it with some consideration. Note that
8263 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8264 case-sensitive.</dd>
8267 print <<EOT;
8268 <dt><b>author</b></dt>
8269 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8270 <dt><b>committer</b></dt>
8271 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8273 my $have_pickaxe = gitweb_check_feature('pickaxe');
8274 if ($have_pickaxe) {
8275 print <<EOT;
8276 <dt><b>pickaxe</b></dt>
8277 <dd>All commits that caused the string to appear or disappear from any file (changes that
8278 added, removed or "modified" the string) will be listed. This search can take a while and
8279 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8280 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8283 print "</dl>\n";
8284 git_footer_html();
8287 sub git_shortlog {
8288 git_log_generic('shortlog', \&git_shortlog_body,
8289 $hash, $hash_parent);
8292 ## ......................................................................
8293 ## feeds (RSS, Atom; OPML)
8295 sub git_feed {
8296 my $format = shift || 'atom';
8297 my $have_blame = gitweb_check_feature('blame');
8299 # Atom: http://www.atomenabled.org/developers/syndication/
8300 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8301 if ($format ne 'rss' && $format ne 'atom') {
8302 die_error(400, "Unknown web feed format");
8305 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8306 my $head = $hash || 'HEAD';
8307 my @commitlist = parse_commits($head, 150, 0, $file_name);
8309 my %latest_commit;
8310 my %latest_date;
8311 my $content_type = "application/$format+xml";
8312 if (defined $cgi->http('HTTP_ACCEPT') &&
8313 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8314 # browser (feed reader) prefers text/xml
8315 $content_type = 'text/xml';
8317 if (defined($commitlist[0])) {
8318 %latest_commit = %{$commitlist[0]};
8319 my $latest_epoch = $latest_commit{'committer_epoch'};
8320 exit_if_unmodified_since($latest_epoch);
8321 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8323 print $cgi->header(
8324 -type => $content_type,
8325 -charset => 'utf-8',
8326 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8327 -status => '200 OK');
8329 # Optimization: skip generating the body if client asks only
8330 # for Last-Modified date.
8331 return if ($cgi->request_method() eq 'HEAD');
8333 # header variables
8334 my $title = "$site_name - $project/$action";
8335 my $feed_type = 'log';
8336 if (defined $hash) {
8337 $title .= " - '$hash'";
8338 $feed_type = 'branch log';
8339 if (defined $file_name) {
8340 $title .= " :: $file_name";
8341 $feed_type = 'history';
8343 } elsif (defined $file_name) {
8344 $title .= " - $file_name";
8345 $feed_type = 'history';
8347 $title .= " $feed_type";
8348 $title = esc_html($title);
8349 my $descr = git_get_project_description($project);
8350 if (defined $descr) {
8351 $descr = esc_html($descr);
8352 } else {
8353 $descr = "$project " .
8354 ($format eq 'rss' ? 'RSS' : 'Atom') .
8355 " feed";
8357 my $owner = git_get_project_owner($project);
8358 $owner = esc_html($owner);
8360 #header
8361 my $alt_url;
8362 if (defined $file_name) {
8363 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8364 } elsif (defined $hash) {
8365 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8366 } else {
8367 $alt_url = href(-full=>1, action=>"summary");
8369 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8370 if ($format eq 'rss') {
8371 print <<XML;
8372 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8373 <channel>
8375 print "<title>$title</title>\n" .
8376 "<link>$alt_url</link>\n" .
8377 "<description>$descr</description>\n" .
8378 "<language>en</language>\n" .
8379 # project owner is responsible for 'editorial' content
8380 "<managingEditor>$owner</managingEditor>\n";
8381 if (defined $logo || defined $favicon) {
8382 # prefer the logo to the favicon, since RSS
8383 # doesn't allow both
8384 my $img = esc_url($logo || $favicon);
8385 print "<image>\n" .
8386 "<url>$img</url>\n" .
8387 "<title>$title</title>\n" .
8388 "<link>$alt_url</link>\n" .
8389 "</image>\n";
8391 if (%latest_date) {
8392 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8393 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8395 print "<generator>gitweb v.$version/$git_version</generator>\n";
8396 } elsif ($format eq 'atom') {
8397 print <<XML;
8398 <feed xmlns="http://www.w3.org/2005/Atom">
8400 print "<title>$title</title>\n" .
8401 "<subtitle>$descr</subtitle>\n" .
8402 '<link rel="alternate" type="text/html" href="' .
8403 $alt_url . '" />' . "\n" .
8404 '<link rel="self" type="' . $content_type . '" href="' .
8405 $cgi->self_url() . '" />' . "\n" .
8406 "<id>" . href(-full=>1) . "</id>\n" .
8407 # use project owner for feed author
8408 "<author><name>$owner</name></author>\n";
8409 if (defined $favicon) {
8410 print "<icon>" . esc_url($favicon) . "</icon>\n";
8412 if (defined $logo) {
8413 # not twice as wide as tall: 72 x 27 pixels
8414 print "<logo>" . esc_url($logo) . "</logo>\n";
8416 if (! %latest_date) {
8417 # dummy date to keep the feed valid until commits trickle in:
8418 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8419 } else {
8420 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8422 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8425 # contents
8426 for (my $i = 0; $i <= $#commitlist; $i++) {
8427 my %co = %{$commitlist[$i]};
8428 my $commit = $co{'id'};
8429 # we read 150, we always show 30 and the ones more recent than 48 hours
8430 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8431 last;
8433 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8435 # get list of changed files
8436 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8437 $co{'parent'} || "--root",
8438 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8439 or next;
8440 my @difftree = map { chomp; $_ } <$fd>;
8441 close $fd
8442 or next;
8444 # print element (entry, item)
8445 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8446 if ($format eq 'rss') {
8447 print "<item>\n" .
8448 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8449 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8450 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8451 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8452 "<link>$co_url</link>\n" .
8453 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8454 "<content:encoded>" .
8455 "<![CDATA[\n";
8456 } elsif ($format eq 'atom') {
8457 print "<entry>\n" .
8458 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8459 "<updated>$cd{'iso-8601'}</updated>\n" .
8460 "<author>\n" .
8461 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8462 if ($co{'author_email'}) {
8463 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8465 print "</author>\n" .
8466 # use committer for contributor
8467 "<contributor>\n" .
8468 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8469 if ($co{'committer_email'}) {
8470 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8472 print "</contributor>\n" .
8473 "<published>$cd{'iso-8601'}</published>\n" .
8474 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8475 "<id>$co_url</id>\n" .
8476 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8477 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8479 my $comment = $co{'comment'};
8480 print "<pre>\n";
8481 foreach my $line (@$comment) {
8482 $line = esc_html($line);
8483 print "$line\n";
8485 print "</pre><ul>\n";
8486 foreach my $difftree_line (@difftree) {
8487 my %difftree = parse_difftree_raw_line($difftree_line);
8488 next if !$difftree{'from_id'};
8490 my $file = $difftree{'file'} || $difftree{'to_file'};
8492 print "<li>" .
8493 "[" .
8494 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8495 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8496 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8497 file_name=>$file, file_parent=>$difftree{'from_file'}),
8498 -title => "diff"}, 'D');
8499 if ($have_blame) {
8500 print $cgi->a({-href => href(-full=>1, action=>"blame",
8501 file_name=>$file, hash_base=>$commit),
8502 -title => "blame"}, 'B');
8504 # if this is not a feed of a file history
8505 if (!defined $file_name || $file_name ne $file) {
8506 print $cgi->a({-href => href(-full=>1, action=>"history",
8507 file_name=>$file, hash=>$commit),
8508 -title => "history"}, 'H');
8510 $file = esc_path($file);
8511 print "] ".
8512 "$file</li>\n";
8514 if ($format eq 'rss') {
8515 print "</ul>]]>\n" .
8516 "</content:encoded>\n" .
8517 "</item>\n";
8518 } elsif ($format eq 'atom') {
8519 print "</ul>\n</div>\n" .
8520 "</content>\n" .
8521 "</entry>\n";
8525 # end of feed
8526 if ($format eq 'rss') {
8527 print "</channel>\n</rss>\n";
8528 } elsif ($format eq 'atom') {
8529 print "</feed>\n";
8533 sub git_rss {
8534 git_feed('rss');
8537 sub git_atom {
8538 git_feed('atom');
8541 sub git_opml {
8542 my @list = git_get_projects_list($project_filter, $strict_export);
8543 if (!@list) {
8544 die_error(404, "No projects found");
8547 print $cgi->header(
8548 -type => 'text/xml',
8549 -charset => 'utf-8',
8550 -content_disposition => 'inline; filename="opml.xml"');
8552 my $title = esc_html($site_name);
8553 my $filter = " within subdirectory ";
8554 if (defined $project_filter) {
8555 $filter .= esc_html($project_filter);
8556 } else {
8557 $filter = "";
8559 print <<XML;
8560 <?xml version="1.0" encoding="utf-8"?>
8561 <opml version="1.0">
8562 <head>
8563 <title>$title OPML Export$filter</title>
8564 </head>
8565 <body>
8566 <outline text="git RSS feeds">
8569 foreach my $pr (@list) {
8570 my %proj = %$pr;
8571 my $head = git_get_head_hash($proj{'path'});
8572 if (!defined $head) {
8573 next;
8575 $git_dir = "$projectroot/$proj{'path'}";
8576 my %co = parse_commit($head);
8577 if (!%co) {
8578 next;
8581 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8582 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8583 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8584 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8586 print <<XML;
8587 </outline>
8588 </body>
8589 </opml>