gitweb: correct improper caching behavior
[git/gitweb.git] / gitweb / gitweb.perl
blob593730bdb139b67fc7b488861a3e26bac27e8377
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 @all_projects = filter_forks_from_projects_list(\@all_projects)
5681 if gitweb_check_feature('forks');
5682 my @all_projects_filled = fill_project_list_info_uncached(\@all_projects);
5683 git_store_cache_file($cache_file, \@all_projects_filled);
5684 @projects = git_filter_cached_projects(\@all_projects_filled, $projlist);
5685 } else {
5686 @projects = fill_project_list_info_uncached($projlist, @wanted_keys);
5690 if ($projlist_cache_lifetime && $stale > 0) {
5691 print "<div class=\"stale_info\">Cached version (${stale}s old)</div>\n"
5692 unless $shown_stale_message;
5693 $shown_stale_message = 1;
5696 return @projects;
5699 sub fill_project_list_info_uncached {
5700 my ($projlist, @wanted_keys) = @_;
5701 my @projects;
5702 my $filter_set = sub { return @_; };
5703 if (@wanted_keys) {
5704 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5705 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5708 my $show_ctags = gitweb_check_feature('ctags');
5709 PROJECT:
5710 foreach my $pr (@$projlist) {
5711 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5712 my (@activity) = git_get_last_activity($pr->{'path'});
5713 unless (@activity) {
5714 next PROJECT;
5716 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5718 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5719 my $descr = git_get_project_description($pr->{'path'}) || "";
5720 $descr = to_utf8($descr);
5721 $pr->{'descr_long'} = $descr;
5722 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5724 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5725 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5727 if ($show_ctags &&
5728 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5729 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5731 if ($projects_list_group_categories &&
5732 project_info_needs_filling($pr, $filter_set->('category'))) {
5733 my $cat = git_get_project_category($pr->{'path'}) ||
5734 $project_list_default_category;
5735 $pr->{'category'} = to_utf8($cat);
5738 push @projects, $pr;
5741 return @projects;
5744 sub sort_projects_list {
5745 my ($projlist, $order) = @_;
5747 sub order_str {
5748 my $key = shift;
5749 return sub { $a->{$key} cmp $b->{$key} };
5752 sub order_num_then_undef {
5753 my $key = shift;
5754 return sub {
5755 defined $a->{$key} ?
5756 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5757 (defined $b->{$key} ? 1 : 0)
5761 my %orderings = (
5762 project => order_str('path'),
5763 descr => order_str('descr_long'),
5764 owner => order_str('owner'),
5765 age => order_num_then_undef('age'),
5768 my $ordering = $orderings{$order};
5769 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5772 # returns a hash of categories, containing the list of project
5773 # belonging to each category
5774 sub build_projlist_by_category {
5775 my ($projlist, $from, $to) = @_;
5776 my %categories;
5778 $from = 0 unless defined $from;
5779 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5781 for (my $i = $from; $i <= $to; $i++) {
5782 my $pr = $projlist->[$i];
5783 push @{$categories{ $pr->{'category'} }}, $pr;
5786 return wantarray ? %categories : \%categories;
5789 # print 'sort by' <th> element, generating 'sort by $name' replay link
5790 # if that order is not selected
5791 sub print_sort_th {
5792 print format_sort_th(@_);
5795 sub format_sort_th {
5796 my ($name, $order, $header) = @_;
5797 my $sort_th = "";
5798 $header ||= ucfirst($name);
5800 if ($order eq $name) {
5801 $sort_th .= "<th>$header</th>\n";
5802 } else {
5803 $sort_th .= "<th>" .
5804 $cgi->a({-href => href(-replay=>1, order=>$name),
5805 -class => "header"}, $header) .
5806 "</th>\n";
5809 return $sort_th;
5812 sub git_project_list_rows {
5813 my ($projlist, $from, $to, $check_forks) = @_;
5815 $from = 0 unless defined $from;
5816 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5818 my $alternate = 1;
5819 for (my $i = $from; $i <= $to; $i++) {
5820 my $pr = $projlist->[$i];
5822 if ($alternate) {
5823 print "<tr class=\"dark\">\n";
5824 } else {
5825 print "<tr class=\"light\">\n";
5827 $alternate ^= 1;
5829 if ($check_forks) {
5830 print "<td>";
5831 if ($pr->{'forks'}) {
5832 my $nforks = scalar @{$pr->{'forks'}};
5833 if ($nforks > 0) {
5834 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5835 -title => "$nforks forks"}, "+");
5836 } else {
5837 print $cgi->span({-title => "$nforks forks"}, "+");
5840 print "</td>\n";
5842 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5843 -class => "list"},
5844 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5845 "</td>\n" .
5846 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5847 -class => "list",
5848 -title => $pr->{'descr_long'}},
5849 $search_regexp
5850 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5851 $pr->{'descr'}, $search_regexp)
5852 : esc_html($pr->{'descr'})) .
5853 "</td>\n";
5854 unless ($omit_owner) {
5855 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5857 unless ($omit_age_column) {
5858 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5859 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5861 print"<td class=\"link\">" .
5862 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5863 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5864 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5865 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5866 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5867 "</td>\n" .
5868 "</tr>\n";
5872 sub git_project_list_body {
5873 # actually uses global variable $project
5874 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action) = @_;
5875 my @projects = @$projlist;
5877 my $check_forks = gitweb_check_feature('forks');
5878 my $show_ctags = gitweb_check_feature('ctags');
5879 my $tagfilter = $show_ctags ? $input_params{'ctag_filter'} : undef;
5880 $check_forks = undef
5881 if ($tagfilter || $search_regexp);
5883 # filtering out forks before filling info allows to do less work
5884 @projects = filter_forks_from_projects_list(\@projects)
5885 if ($check_forks);
5886 # search_projects_list pre-fills required info
5887 @projects = search_projects_list(\@projects,
5888 'search_regexp' => $search_regexp,
5889 'tagfilter' => $tagfilter)
5890 if ($tagfilter || $search_regexp);
5891 # fill the rest
5892 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5893 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5894 push @all_fields, 'owner' unless($omit_owner);
5895 @projects = fill_project_list_info(\@projects, @all_fields);
5897 $order ||= $default_projects_order;
5898 $from = 0 unless defined $from;
5899 $to = $#projects if (!defined $to || $#projects < $to);
5901 # short circuit
5902 if ($from > $to) {
5903 print "<center>\n".
5904 "<b>No such projects found</b><br />\n".
5905 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5906 "</center>\n<br />\n";
5907 return;
5910 @projects = sort_projects_list(\@projects, $order);
5912 if ($show_ctags) {
5913 my $ctags = git_gather_all_ctags(\@projects);
5914 my $cloud = git_populate_project_tagcloud($ctags, $ctags_action||'project_list');
5915 print git_show_project_tagcloud($cloud, 64);
5918 print "<table class=\"project_list\">\n";
5919 unless ($no_header) {
5920 print "<tr>\n";
5921 if ($check_forks) {
5922 print "<th></th>\n";
5924 print_sort_th('project', $order, 'Project');
5925 print_sort_th('descr', $order, 'Description');
5926 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5927 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5928 print "<th></th>\n" . # for links
5929 "</tr>\n";
5932 if ($projects_list_group_categories) {
5933 # only display categories with projects in the $from-$to window
5934 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5935 my %categories = build_projlist_by_category(\@projects, $from, $to);
5936 foreach my $cat (sort keys %categories) {
5937 unless ($cat eq "") {
5938 print "<tr>\n";
5939 if ($check_forks) {
5940 print "<td></td>\n";
5942 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5943 print "</tr>\n";
5946 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5948 } else {
5949 git_project_list_rows(\@projects, $from, $to, $check_forks);
5952 if (defined $extra) {
5953 print "<tr>\n";
5954 if ($check_forks) {
5955 print "<td></td>\n";
5957 print "<td colspan=\"5\">$extra</td>\n" .
5958 "</tr>\n";
5960 print "</table>\n";
5963 sub git_log_body {
5964 # uses global variable $project
5965 my ($commitlist, $from, $to, $refs, $extra) = @_;
5967 $from = 0 unless defined $from;
5968 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5970 for (my $i = 0; $i <= $to; $i++) {
5971 my %co = %{$commitlist->[$i]};
5972 next if !%co;
5973 my $commit = $co{'id'};
5974 my $ref = format_ref_marker($refs, $commit);
5975 git_print_header_div('commit',
5976 "<span class=\"age\">$co{'age_string'}</span>" .
5977 esc_html($co{'title'}) . $ref,
5978 $commit);
5979 print "<div class=\"title_text\">\n" .
5980 "<div class=\"log_link\">\n" .
5981 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5982 " | " .
5983 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5984 " | " .
5985 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5986 "<br/>\n" .
5987 "</div>\n";
5988 git_print_authorship(\%co, -tag => 'span');
5989 print "<br/>\n</div>\n";
5991 print "<div class=\"log_body\">\n";
5992 git_print_log($co{'comment'}, -final_empty_line=> 1);
5993 print "</div>\n";
5995 if ($extra) {
5996 print "<div class=\"page_nav\">\n";
5997 print "$extra\n";
5998 print "</div>\n";
6002 sub git_shortlog_body {
6003 # uses global variable $project
6004 my ($commitlist, $from, $to, $refs, $extra) = @_;
6006 $from = 0 unless defined $from;
6007 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6009 print "<table class=\"shortlog\">\n";
6010 my $alternate = 1;
6011 for (my $i = $from; $i <= $to; $i++) {
6012 my %co = %{$commitlist->[$i]};
6013 my $commit = $co{'id'};
6014 my $ref = format_ref_marker($refs, $commit);
6015 if ($alternate) {
6016 print "<tr class=\"dark\">\n";
6017 } else {
6018 print "<tr class=\"light\">\n";
6020 $alternate ^= 1;
6021 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
6022 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6023 format_author_html('td', \%co, 10) . "<td>";
6024 print format_subject_html($co{'title'}, $co{'title_short'},
6025 href(action=>"commit", hash=>$commit), $ref);
6026 print "</td>\n" .
6027 "<td class=\"link\">" .
6028 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
6029 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
6030 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
6031 my $snapshot_links = format_snapshot_links($commit);
6032 if (defined $snapshot_links) {
6033 print " | " . $snapshot_links;
6035 print "</td>\n" .
6036 "</tr>\n";
6038 if (defined $extra) {
6039 print "<tr>\n" .
6040 "<td colspan=\"4\">$extra</td>\n" .
6041 "</tr>\n";
6043 print "</table>\n";
6046 sub git_history_body {
6047 # Warning: assumes constant type (blob or tree) during history
6048 my ($commitlist, $from, $to, $refs, $extra,
6049 $file_name, $file_hash, $ftype) = @_;
6051 $from = 0 unless defined $from;
6052 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
6054 print "<table class=\"history\">\n";
6055 my $alternate = 1;
6056 for (my $i = $from; $i <= $to; $i++) {
6057 my %co = %{$commitlist->[$i]};
6058 if (!%co) {
6059 next;
6061 my $commit = $co{'id'};
6063 my $ref = format_ref_marker($refs, $commit);
6065 if ($alternate) {
6066 print "<tr class=\"dark\">\n";
6067 } else {
6068 print "<tr class=\"light\">\n";
6070 $alternate ^= 1;
6071 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6072 # shortlog: format_author_html('td', \%co, 10)
6073 format_author_html('td', \%co, 15, 3) . "<td>";
6074 # originally git_history used chop_str($co{'title'}, 50)
6075 print format_subject_html($co{'title'}, $co{'title_short'},
6076 href(action=>"commit", hash=>$commit), $ref);
6077 print "</td>\n" .
6078 "<td class=\"link\">" .
6079 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
6080 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
6082 if ($ftype eq 'blob') {
6083 my $blob_current = $file_hash;
6084 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6085 if (defined $blob_current && defined $blob_parent &&
6086 $blob_current ne $blob_parent) {
6087 print " | " .
6088 $cgi->a({-href => href(action=>"blobdiff",
6089 hash=>$blob_current, hash_parent=>$blob_parent,
6090 hash_base=>$hash_base, hash_parent_base=>$commit,
6091 file_name=>$file_name)},
6092 "diff to current");
6095 print "</td>\n" .
6096 "</tr>\n";
6098 if (defined $extra) {
6099 print "<tr>\n" .
6100 "<td colspan=\"4\">$extra</td>\n" .
6101 "</tr>\n";
6103 print "</table>\n";
6106 sub git_tags_body {
6107 # uses global variable $project
6108 my ($taglist, $from, $to, $extra) = @_;
6109 $from = 0 unless defined $from;
6110 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6112 print "<table class=\"tags\">\n";
6113 my $alternate = 1;
6114 for (my $i = $from; $i <= $to; $i++) {
6115 my $entry = $taglist->[$i];
6116 my %tag = %$entry;
6117 my $comment = $tag{'subject'};
6118 my $comment_short;
6119 if (defined $comment) {
6120 $comment_short = chop_str($comment, 30, 5);
6122 if ($alternate) {
6123 print "<tr class=\"dark\">\n";
6124 } else {
6125 print "<tr class=\"light\">\n";
6127 $alternate ^= 1;
6128 if (defined $tag{'age'}) {
6129 print "<td><i>$tag{'age'}</i></td>\n";
6130 } else {
6131 print "<td></td>\n";
6133 print "<td>" .
6134 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6135 -class => "list name"}, esc_html($tag{'name'})) .
6136 "</td>\n" .
6137 "<td>";
6138 if (defined $comment) {
6139 print format_subject_html($comment, $comment_short,
6140 href(action=>"tag", hash=>$tag{'id'}));
6142 print "</td>\n" .
6143 "<td class=\"selflink\">";
6144 if ($tag{'type'} eq "tag") {
6145 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6146 } else {
6147 print "&nbsp;";
6149 print "</td>\n" .
6150 "<td class=\"link\">" . " | " .
6151 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6152 if ($tag{'reftype'} eq "commit") {
6153 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6154 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6155 } elsif ($tag{'reftype'} eq "blob") {
6156 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6158 print "</td>\n" .
6159 "</tr>";
6161 if (defined $extra) {
6162 print "<tr>\n" .
6163 "<td colspan=\"5\">$extra</td>\n" .
6164 "</tr>\n";
6166 print "</table>\n";
6169 sub git_heads_body {
6170 # uses global variable $project
6171 my ($headlist, $head_at, $from, $to, $extra) = @_;
6172 $from = 0 unless defined $from;
6173 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6175 print "<table class=\"heads\">\n";
6176 my $alternate = 1;
6177 for (my $i = $from; $i <= $to; $i++) {
6178 my $entry = $headlist->[$i];
6179 my %ref = %$entry;
6180 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6181 if ($alternate) {
6182 print "<tr class=\"dark\">\n";
6183 } else {
6184 print "<tr class=\"light\">\n";
6186 $alternate ^= 1;
6187 print "<td><i>$ref{'age'}</i></td>\n" .
6188 ($curr ? "<td class=\"current_head\">" : "<td>") .
6189 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6190 -class => "list name"},esc_html($ref{'name'})) .
6191 "</td>\n" .
6192 "<td class=\"link\">" .
6193 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6194 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6195 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6196 "</td>\n" .
6197 "</tr>";
6199 if (defined $extra) {
6200 print "<tr>\n" .
6201 "<td colspan=\"3\">$extra</td>\n" .
6202 "</tr>\n";
6204 print "</table>\n";
6207 # Display a single remote block
6208 sub git_remote_block {
6209 my ($remote, $rdata, $limit, $head) = @_;
6211 my $heads = $rdata->{'heads'};
6212 my $fetch = $rdata->{'fetch'};
6213 my $push = $rdata->{'push'};
6215 my $urls_table = "<table class=\"projects_list\">\n" ;
6217 if (defined $fetch) {
6218 if ($fetch eq $push) {
6219 $urls_table .= format_repo_url("URL", $fetch);
6220 } else {
6221 $urls_table .= format_repo_url("Fetch URL", $fetch);
6222 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6224 } elsif (defined $push) {
6225 $urls_table .= format_repo_url("Push URL", $push);
6226 } else {
6227 $urls_table .= format_repo_url("", "No remote URL");
6230 $urls_table .= "</table>\n";
6232 my $dots;
6233 if (defined $limit && $limit < @$heads) {
6234 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6237 print $urls_table;
6238 git_heads_body($heads, $head, 0, $limit, $dots);
6241 # Display a list of remote names with the respective fetch and push URLs
6242 sub git_remotes_list {
6243 my ($remotedata, $limit) = @_;
6244 print "<table class=\"heads\">\n";
6245 my $alternate = 1;
6246 my @remotes = sort keys %$remotedata;
6248 my $limited = $limit && $limit < @remotes;
6250 $#remotes = $limit - 1 if $limited;
6252 while (my $remote = shift @remotes) {
6253 my $rdata = $remotedata->{$remote};
6254 my $fetch = $rdata->{'fetch'};
6255 my $push = $rdata->{'push'};
6256 if ($alternate) {
6257 print "<tr class=\"dark\">\n";
6258 } else {
6259 print "<tr class=\"light\">\n";
6261 $alternate ^= 1;
6262 print "<td>" .
6263 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6264 -class=> "list name"},esc_html($remote)) .
6265 "</td>";
6266 print "<td class=\"link\">" .
6267 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6268 " | " .
6269 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6270 "</td>";
6272 print "</tr>\n";
6275 if ($limited) {
6276 print "<tr>\n" .
6277 "<td colspan=\"3\">" .
6278 $cgi->a({-href => href(action=>"remotes")}, "...") .
6279 "</td>\n" . "</tr>\n";
6282 print "</table>";
6285 # Display remote heads grouped by remote, unless there are too many
6286 # remotes, in which case we only display the remote names
6287 sub git_remotes_body {
6288 my ($remotedata, $limit, $head) = @_;
6289 if ($limit and $limit < keys %$remotedata) {
6290 git_remotes_list($remotedata, $limit);
6291 } else {
6292 fill_remote_heads($remotedata);
6293 while (my ($remote, $rdata) = each %$remotedata) {
6294 git_print_section({-class=>"remote", -id=>$remote},
6295 ["remotes", $remote, $remote], sub {
6296 git_remote_block($remote, $rdata, $limit, $head);
6302 sub git_search_message {
6303 my %co = @_;
6305 my $greptype;
6306 if ($searchtype eq 'commit') {
6307 $greptype = "--grep=";
6308 } elsif ($searchtype eq 'author') {
6309 $greptype = "--author=";
6310 } elsif ($searchtype eq 'committer') {
6311 $greptype = "--committer=";
6313 $greptype .= $searchtext;
6314 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6315 $greptype, '--regexp-ignore-case',
6316 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6318 my $paging_nav = '';
6319 if ($page > 0) {
6320 $paging_nav .=
6321 $cgi->a({-href => href(-replay=>1, page=>undef)},
6322 "first") .
6323 " &sdot; " .
6324 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6325 -accesskey => "p", -title => "Alt-p"}, "prev");
6326 } else {
6327 $paging_nav .= "first &sdot; prev";
6329 my $next_link = '';
6330 if ($#commitlist >= 100) {
6331 $next_link =
6332 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6333 -accesskey => "n", -title => "Alt-n"}, "next");
6334 $paging_nav .= " &sdot; $next_link";
6335 } else {
6336 $paging_nav .= " &sdot; next";
6339 git_header_html();
6341 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6342 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6343 if ($page == 0 && !@commitlist) {
6344 print "<p>No match.</p>\n";
6345 } else {
6346 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6349 git_footer_html();
6352 sub git_search_changes {
6353 my %co = @_;
6355 local $/ = "\n";
6356 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6357 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6358 ($search_use_regexp ? '--pickaxe-regex' : ())
6359 or die_error(500, "Open git-log failed");
6361 git_header_html();
6363 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6364 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6366 print "<table class=\"pickaxe search\">\n";
6367 my $alternate = 1;
6368 undef %co;
6369 my @files;
6370 while (my $line = <$fd>) {
6371 chomp $line;
6372 next unless $line;
6374 my %set = parse_difftree_raw_line($line);
6375 if (defined $set{'commit'}) {
6376 # finish previous commit
6377 if (%co) {
6378 print "</td>\n" .
6379 "<td class=\"link\">" .
6380 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6381 "commit") .
6382 " | " .
6383 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6384 hash_base=>$co{'id'})},
6385 "tree") .
6386 "</td>\n" .
6387 "</tr>\n";
6390 if ($alternate) {
6391 print "<tr class=\"dark\">\n";
6392 } else {
6393 print "<tr class=\"light\">\n";
6395 $alternate ^= 1;
6396 %co = parse_commit($set{'commit'});
6397 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6398 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6399 "<td><i>$author</i></td>\n" .
6400 "<td>" .
6401 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6402 -class => "list subject"},
6403 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6404 } elsif (defined $set{'to_id'}) {
6405 next if ($set{'to_id'} =~ m/^0{40}$/);
6407 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6408 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6409 -class => "list"},
6410 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6411 "<br/>\n";
6414 close $fd;
6416 # finish last commit (warning: repetition!)
6417 if (%co) {
6418 print "</td>\n" .
6419 "<td class=\"link\">" .
6420 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6421 "commit") .
6422 " | " .
6423 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6424 hash_base=>$co{'id'})},
6425 "tree") .
6426 "</td>\n" .
6427 "</tr>\n";
6430 print "</table>\n";
6432 git_footer_html();
6435 sub git_search_files {
6436 my %co = @_;
6438 local $/ = "\n";
6439 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6440 $search_use_regexp ? ('-E', '-i') : '-F',
6441 $searchtext, $co{'tree'}
6442 or die_error(500, "Open git-grep failed");
6444 git_header_html();
6446 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6447 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6449 print "<table class=\"grep_search\">\n";
6450 my $alternate = 1;
6451 my $matches = 0;
6452 my $lastfile = '';
6453 my $file_href;
6454 while (my $line = <$fd>) {
6455 chomp $line;
6456 my ($file, $lno, $ltext, $binary);
6457 last if ($matches++ > 1000);
6458 if ($line =~ /^Binary file (.+) matches$/) {
6459 $file = $1;
6460 $binary = 1;
6461 } else {
6462 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6463 $file =~ s/^$co{'tree'}://;
6465 if ($file ne $lastfile) {
6466 $lastfile and print "</td></tr>\n";
6467 if ($alternate++) {
6468 print "<tr class=\"dark\">\n";
6469 } else {
6470 print "<tr class=\"light\">\n";
6472 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6473 file_name=>$file);
6474 print "<td class=\"list\">".
6475 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6476 print "</td><td>\n";
6477 $lastfile = $file;
6479 if ($binary) {
6480 print "<div class=\"binary\">Binary file</div>\n";
6481 } else {
6482 $ltext = untabify($ltext);
6483 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6484 $ltext = esc_html($1, -nbsp=>1);
6485 $ltext .= '<span class="match">';
6486 $ltext .= esc_html($2, -nbsp=>1);
6487 $ltext .= '</span>';
6488 $ltext .= esc_html($3, -nbsp=>1);
6489 } else {
6490 $ltext = esc_html($ltext, -nbsp=>1);
6492 print "<div class=\"pre\">" .
6493 $cgi->a({-href => $file_href.'#l'.$lno,
6494 -class => "linenr"}, sprintf('%4i', $lno)) .
6495 ' ' . $ltext . "</div>\n";
6498 if ($lastfile) {
6499 print "</td></tr>\n";
6500 if ($matches > 1000) {
6501 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6503 } else {
6504 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6506 close $fd;
6508 print "</table>\n";
6510 git_footer_html();
6513 sub git_search_grep_body {
6514 my ($commitlist, $from, $to, $extra) = @_;
6515 $from = 0 unless defined $from;
6516 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6518 print "<table class=\"commit_search\">\n";
6519 my $alternate = 1;
6520 for (my $i = $from; $i <= $to; $i++) {
6521 my %co = %{$commitlist->[$i]};
6522 if (!%co) {
6523 next;
6525 my $commit = $co{'id'};
6526 if ($alternate) {
6527 print "<tr class=\"dark\">\n";
6528 } else {
6529 print "<tr class=\"light\">\n";
6531 $alternate ^= 1;
6532 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6533 format_author_html('td', \%co, 15, 5) .
6534 "<td>" .
6535 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6536 -class => "list subject"},
6537 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6538 my $comment = $co{'comment'};
6539 foreach my $line (@$comment) {
6540 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6541 my ($lead, $match, $trail) = ($1, $2, $3);
6542 $match = chop_str($match, 70, 5, 'center');
6543 my $contextlen = int((80 - length($match))/2);
6544 $contextlen = 30 if ($contextlen > 30);
6545 $lead = chop_str($lead, $contextlen, 10, 'left');
6546 $trail = chop_str($trail, $contextlen, 10, 'right');
6548 $lead = esc_html($lead);
6549 $match = esc_html($match);
6550 $trail = esc_html($trail);
6552 print "$lead<span class=\"match\">$match</span>$trail<br />";
6555 print "</td>\n" .
6556 "<td class=\"link\">" .
6557 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6558 " | " .
6559 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6560 " | " .
6561 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6562 print "</td>\n" .
6563 "</tr>\n";
6565 if (defined $extra) {
6566 print "<tr>\n" .
6567 "<td colspan=\"3\">$extra</td>\n" .
6568 "</tr>\n";
6570 print "</table>\n";
6573 ## ======================================================================
6574 ## ======================================================================
6575 ## actions
6577 sub git_project_list_load {
6578 my $empty_list_ok = shift;
6579 my $order = $input_params{'order'};
6580 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6581 die_error(400, "Unknown order parameter");
6584 my @list = git_get_projects_list($project_filter, $strict_export);
6585 if (!@list) {
6586 die_error(404, "No projects found") unless $empty_list_ok;
6589 return (\@list, $order);
6592 sub git_frontpage {
6593 my ($projlist, $order);
6595 if ($frontpage_no_project_list) {
6596 $project = undef;
6597 $project_filter = undef;
6598 } else {
6599 ($projlist, $order) = git_project_list_load(1);
6601 git_header_html();
6602 if (defined $home_text && -f $home_text) {
6603 print "<div class=\"index_include\">\n";
6604 insert_file($home_text);
6605 print "</div>\n";
6607 git_project_search_form($searchtext, $search_use_regexp);
6608 if ($frontpage_no_project_list) {
6609 my $show_ctags = gitweb_check_feature('ctags');
6610 if ($frontpage_no_project_list == 1 and $show_ctags) {
6611 my @projects = git_get_projects_list($project_filter, $strict_export);
6612 @projects = filter_forks_from_projects_list(\@projects) if gitweb_check_feature('forks');
6613 @projects = fill_project_list_info(\@projects, 'ctags');
6614 my $ctags = git_gather_all_ctags(\@projects);
6615 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6616 print git_show_project_tagcloud($cloud, 64);
6618 } else {
6619 git_project_list_body($projlist, $order);
6621 git_footer_html();
6624 sub git_project_list {
6625 my ($projlist, $order) = git_project_list_load();
6626 git_header_html();
6627 if (not $frontpage_no_project_list && defined $home_text && -f $home_text) {
6628 print "<div class=\"index_include\">\n";
6629 insert_file($home_text);
6630 print "</div>\n";
6632 git_project_search_form();
6633 git_project_list_body($projlist, $order);
6634 git_footer_html();
6637 sub git_forks {
6638 my $order = $input_params{'order'};
6639 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6640 die_error(400, "Unknown order parameter");
6643 my $filter = $project;
6644 $filter =~ s/\.git$//;
6645 my @list = git_get_projects_list($filter);
6646 if (!@list) {
6647 die_error(404, "No forks found");
6650 git_header_html();
6651 git_print_page_nav('','');
6652 git_print_header_div('summary', "$project forks");
6653 git_project_list_body(\@list, $order, undef, undef, undef, undef, 'forks');
6654 git_footer_html();
6657 sub git_project_index {
6658 my @projects = git_get_projects_list($project_filter, $strict_export);
6659 if (!@projects) {
6660 die_error(404, "No projects found");
6663 print $cgi->header(
6664 -type => 'text/plain',
6665 -charset => 'utf-8',
6666 -content_disposition => 'inline; filename="index.aux"');
6668 foreach my $pr (@projects) {
6669 if (!exists $pr->{'owner'}) {
6670 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6673 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6674 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6675 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6676 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6677 $path =~ s/ /\+/g;
6678 $owner =~ s/ /\+/g;
6680 print "$path $owner\n";
6684 sub git_summary {
6685 my $descr = git_get_project_description($project) || "none";
6686 my %co = parse_commit("HEAD");
6687 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6688 my $head = $co{'id'};
6689 my $remote_heads = gitweb_check_feature('remote_heads');
6691 my $owner = git_get_project_owner($project);
6693 my $refs = git_get_references();
6694 # These get_*_list functions return one more to allow us to see if
6695 # there are more ...
6696 my @taglist = git_get_tags_list(16);
6697 my @headlist = git_get_heads_list(16);
6698 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6699 my @forklist;
6700 my $check_forks = gitweb_check_feature('forks');
6702 if ($check_forks) {
6703 # find forks of a project
6704 my $filter = $project;
6705 $filter =~ s/\.git$//;
6706 @forklist = git_get_projects_list($filter);
6707 # filter out forks of forks
6708 @forklist = filter_forks_from_projects_list(\@forklist)
6709 if (@forklist);
6712 git_header_html();
6713 git_print_page_nav('summary','', $head);
6715 print "<div class=\"title\">&nbsp;</div>\n";
6716 print "<table class=\"projects_list\">\n" .
6717 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6718 if ($owner and not $omit_owner) {
6719 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6721 if (defined $cd{'rfc2822'}) {
6722 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6723 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6726 # use per project git URL list in $projectroot/$project/cloneurl
6727 # or make project git URL from git base URL and project name
6728 my $url_tag = "URL";
6729 my @url_list = git_get_project_url_list($project);
6730 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6731 foreach my $git_url (@url_list) {
6732 next unless $git_url;
6733 print format_repo_url($url_tag, $git_url);
6734 $url_tag = "";
6737 # Tag cloud
6738 my $show_ctags = gitweb_check_feature('ctags');
6739 if ($show_ctags) {
6740 my $ctags = git_get_project_ctags($project);
6741 if (%$ctags || $show_ctags !~ /^\d+$/) {
6742 # without ability to add tags, don't show if there are none
6743 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6744 print "<tr id=\"metadata_ctags\">" .
6745 "<td style=\"vertical-align:middle\">content tags<br />";
6746 print "</td>\n<td>" unless %$ctags;
6747 print "<form action=\"$show_ctags\" method=\"post\">" .
6748 "<input type=\"hidden\" name=\"p\" value=\"$project\"/>" .
6749 "add: <input type=\"text\" name=\"t\" size=\"10\" /></form>"
6750 unless $show_ctags =~ /^\d+$/;
6751 print "</td>\n<td>" if %$ctags;
6752 print git_show_project_tagcloud($cloud, 48)."</td>" .
6753 "</tr>\n";
6757 print "</table>\n";
6759 # If XSS prevention is on, we don't include README.html.
6760 # TODO: Allow a readme in some safe format.
6761 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6762 print "<div class=\"title\">readme</div>\n" .
6763 "<div class=\"readme\">\n";
6764 insert_file("$projectroot/$project/README.html");
6765 print "\n</div>\n"; # class="readme"
6768 # we need to request one more than 16 (0..15) to check if
6769 # those 16 are all
6770 my @commitlist = $head ? parse_commits($head, 17) : ();
6771 if (@commitlist) {
6772 git_print_header_div('shortlog');
6773 git_shortlog_body(\@commitlist, 0, 15, $refs,
6774 $#commitlist <= 15 ? undef :
6775 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6778 if (@taglist) {
6779 git_print_header_div('tags');
6780 git_tags_body(\@taglist, 0, 15,
6781 $#taglist <= 15 ? undef :
6782 $cgi->a({-href => href(action=>"tags")}, "..."));
6785 if (@headlist) {
6786 git_print_header_div('heads');
6787 git_heads_body(\@headlist, $head, 0, 15,
6788 $#headlist <= 15 ? undef :
6789 $cgi->a({-href => href(action=>"heads")}, "..."));
6792 if (%remotedata) {
6793 git_print_header_div('remotes');
6794 git_remotes_body(\%remotedata, 15, $head);
6797 if (@forklist) {
6798 git_print_header_div('forks');
6799 git_project_list_body(\@forklist, 'age', 0, 15,
6800 $#forklist <= 15 ? undef :
6801 $cgi->a({-href => href(action=>"forks")}, "..."),
6802 'no_header', 'forks');
6805 git_footer_html();
6808 sub git_tag {
6809 my %tag = parse_tag($hash);
6811 if (! %tag) {
6812 die_error(404, "Unknown tag object");
6815 my $head = git_get_head_hash($project);
6816 git_header_html();
6817 git_print_page_nav('','', $head,undef,$head);
6818 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6819 print "<div class=\"title_text\">\n" .
6820 "<table class=\"object_header\">\n" .
6821 "<tr>\n" .
6822 "<td>object</td>\n" .
6823 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6824 $tag{'object'}) . "</td>\n" .
6825 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6826 $tag{'type'}) . "</td>\n" .
6827 "</tr>\n";
6828 if (defined($tag{'author'})) {
6829 git_print_authorship_rows(\%tag, 'author');
6831 print "</table>\n\n" .
6832 "</div>\n";
6833 print "<div class=\"page_body\">";
6834 my $comment = $tag{'comment'};
6835 foreach my $line (@$comment) {
6836 chomp $line;
6837 print esc_html($line, -nbsp=>1) . "<br/>\n";
6839 print "</div>\n";
6840 git_footer_html();
6843 sub git_blame_common {
6844 my $format = shift || 'porcelain';
6845 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6846 $format = 'incremental';
6847 $action = 'blame_incremental'; # for page title etc
6850 # permissions
6851 gitweb_check_feature('blame')
6852 or die_error(403, "Blame view not allowed");
6854 # error checking
6855 die_error(400, "No file name given") unless $file_name;
6856 $hash_base ||= git_get_head_hash($project);
6857 die_error(404, "Couldn't find base commit") unless $hash_base;
6858 my %co = parse_commit($hash_base)
6859 or die_error(404, "Commit not found");
6860 my $ftype = "blob";
6861 if (!defined $hash) {
6862 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6863 or die_error(404, "Error looking up file");
6864 } else {
6865 $ftype = git_get_type($hash);
6866 if ($ftype !~ "blob") {
6867 die_error(400, "Object is not a blob");
6871 my $fd;
6872 if ($format eq 'incremental') {
6873 # get file contents (as base)
6874 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6875 or die_error(500, "Open git-cat-file failed");
6876 } elsif ($format eq 'data') {
6877 # run git-blame --incremental
6878 open $fd, "-|", git_cmd(), "blame", "--incremental",
6879 $hash_base, "--", $file_name
6880 or die_error(500, "Open git-blame --incremental failed");
6881 } else {
6882 # run git-blame --porcelain
6883 open $fd, "-|", git_cmd(), "blame", '-p',
6884 $hash_base, '--', $file_name
6885 or die_error(500, "Open git-blame --porcelain failed");
6887 binmode $fd, ':utf8';
6889 # incremental blame data returns early
6890 if ($format eq 'data') {
6891 print $cgi->header(
6892 -type=>"text/plain", -charset => "utf-8",
6893 -status=> "200 OK");
6894 local $| = 1; # output autoflush
6895 while (my $line = <$fd>) {
6896 print to_utf8($line);
6898 close $fd
6899 or print "ERROR $!\n";
6901 print 'END';
6902 if (defined $t0 && gitweb_check_feature('timed')) {
6903 print ' '.
6904 tv_interval($t0, [ gettimeofday() ]).
6905 ' '.$number_of_git_cmds;
6907 print "\n";
6909 return;
6912 # page header
6913 git_header_html();
6914 my $formats_nav =
6915 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6916 "blob") .
6917 " | ";
6918 if ($format eq 'incremental') {
6919 $formats_nav .=
6920 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6921 "blame") . " (non-incremental)";
6922 } else {
6923 $formats_nav .=
6924 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6925 "blame") . " (incremental)";
6927 $formats_nav .=
6928 " | " .
6929 $cgi->a({-href => href(action=>"history", -replay=>1)},
6930 "history") .
6931 " | " .
6932 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6933 "HEAD");
6934 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6935 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6936 git_print_page_path($file_name, $ftype, $hash_base);
6938 # page body
6939 if ($format eq 'incremental') {
6940 print "<noscript>\n<div class=\"error\"><center><b>\n".
6941 "This page requires JavaScript to run.\n Use ".
6942 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6943 'this page').
6944 " instead.\n".
6945 "</b></center></div>\n</noscript>\n";
6947 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6950 print qq!<div class="page_body">\n!;
6951 print qq!<div id="progress_info">... / ...</div>\n!
6952 if ($format eq 'incremental');
6953 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6954 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6955 qq!<thead>\n!.
6956 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6957 qq!</thead>\n!.
6958 qq!<tbody>\n!;
6960 my @rev_color = qw(light dark);
6961 my $num_colors = scalar(@rev_color);
6962 my $current_color = 0;
6964 if ($format eq 'incremental') {
6965 my $color_class = $rev_color[$current_color];
6967 #contents of a file
6968 my $linenr = 0;
6969 LINE:
6970 while (my $line = <$fd>) {
6971 chomp $line;
6972 $linenr++;
6974 print qq!<tr id="l$linenr" class="$color_class">!.
6975 qq!<td class="sha1"><a href=""> </a></td>!.
6976 qq!<td class="linenr">!.
6977 qq!<a class="linenr" href="">$linenr</a></td>!;
6978 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6979 print qq!</tr>\n!;
6982 } else { # porcelain, i.e. ordinary blame
6983 my %metainfo = (); # saves information about commits
6985 # blame data
6986 LINE:
6987 while (my $line = <$fd>) {
6988 chomp $line;
6989 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6990 # no <lines in group> for subsequent lines in group of lines
6991 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6992 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6993 if (!exists $metainfo{$full_rev}) {
6994 $metainfo{$full_rev} = { 'nprevious' => 0 };
6996 my $meta = $metainfo{$full_rev};
6997 my $data;
6998 while ($data = <$fd>) {
6999 chomp $data;
7000 last if ($data =~ s/^\t//); # contents of line
7001 if ($data =~ /^(\S+)(?: (.*))?$/) {
7002 $meta->{$1} = $2 unless exists $meta->{$1};
7004 if ($data =~ /^previous /) {
7005 $meta->{'nprevious'}++;
7008 my $short_rev = substr($full_rev, 0, 8);
7009 my $author = $meta->{'author'};
7010 my %date =
7011 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
7012 my $date = $date{'iso-tz'};
7013 if ($group_size) {
7014 $current_color = ($current_color + 1) % $num_colors;
7016 my $tr_class = $rev_color[$current_color];
7017 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
7018 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
7019 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
7020 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
7021 if ($group_size) {
7022 print "<td class=\"sha1\"";
7023 print " title=\"". esc_html($author) . ", $date\"";
7024 print " rowspan=\"$group_size\"" if ($group_size > 1);
7025 print ">";
7026 print $cgi->a({-href => href(action=>"commit",
7027 hash=>$full_rev,
7028 file_name=>$file_name)},
7029 esc_html($short_rev));
7030 if ($group_size >= 2) {
7031 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
7032 if (@author_initials) {
7033 print "<br />" .
7034 esc_html(join('', @author_initials));
7035 # or join('.', ...)
7038 print "</td>\n";
7040 # 'previous' <sha1 of parent commit> <filename at commit>
7041 if (exists $meta->{'previous'} &&
7042 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
7043 $meta->{'parent'} = $1;
7044 $meta->{'file_parent'} = unquote($2);
7046 my $linenr_commit =
7047 exists($meta->{'parent'}) ?
7048 $meta->{'parent'} : $full_rev;
7049 my $linenr_filename =
7050 exists($meta->{'file_parent'}) ?
7051 $meta->{'file_parent'} : unquote($meta->{'filename'});
7052 my $blamed = href(action => 'blame',
7053 file_name => $linenr_filename,
7054 hash_base => $linenr_commit);
7055 print "<td class=\"linenr\">";
7056 print $cgi->a({ -href => "$blamed#l$orig_lineno",
7057 -class => "linenr" },
7058 esc_html($lineno));
7059 print "</td>";
7060 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
7061 print "</tr>\n";
7062 } # end while
7066 # footer
7067 print "</tbody>\n".
7068 "</table>\n"; # class="blame"
7069 print "</div>\n"; # class="blame_body"
7070 close $fd
7071 or print "Reading blob failed\n";
7073 git_footer_html();
7076 sub git_blame {
7077 git_blame_common();
7080 sub git_blame_incremental {
7081 git_blame_common('incremental');
7084 sub git_blame_data {
7085 git_blame_common('data');
7088 sub git_tags {
7089 my $head = git_get_head_hash($project);
7090 git_header_html();
7091 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
7092 git_print_header_div('summary', $project);
7094 my @tagslist = git_get_tags_list();
7095 if (@tagslist) {
7096 git_tags_body(\@tagslist);
7098 git_footer_html();
7101 sub git_heads {
7102 my $head = git_get_head_hash($project);
7103 git_header_html();
7104 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
7105 git_print_header_div('summary', $project);
7107 my @headslist = git_get_heads_list();
7108 if (@headslist) {
7109 git_heads_body(\@headslist, $head);
7111 git_footer_html();
7114 # used both for single remote view and for list of all the remotes
7115 sub git_remotes {
7116 gitweb_check_feature('remote_heads')
7117 or die_error(403, "Remote heads view is disabled");
7119 my $head = git_get_head_hash($project);
7120 my $remote = $input_params{'hash'};
7122 my $remotedata = git_get_remotes_list($remote);
7123 die_error(500, "Unable to get remote information") unless defined $remotedata;
7125 unless (%$remotedata) {
7126 die_error(404, defined $remote ?
7127 "Remote $remote not found" :
7128 "No remotes found");
7131 git_header_html(undef, undef, -action_extra => $remote);
7132 git_print_page_nav('', '', $head, undef, $head,
7133 format_ref_views($remote ? '' : 'remotes'));
7135 fill_remote_heads($remotedata);
7136 if (defined $remote) {
7137 git_print_header_div('remotes', "$remote remote for $project");
7138 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7139 } else {
7140 git_print_header_div('summary', "$project remotes");
7141 git_remotes_body($remotedata, undef, $head);
7144 git_footer_html();
7147 sub git_blob_plain {
7148 my $type = shift;
7149 my $expires;
7151 if (!defined $hash) {
7152 if (defined $file_name) {
7153 my $base = $hash_base || git_get_head_hash($project);
7154 $hash = git_get_hash_by_path($base, $file_name, "blob")
7155 or die_error(404, "Cannot find file");
7156 } else {
7157 die_error(400, "No file name defined");
7159 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7160 # blobs defined by non-textual hash id's can be cached
7161 $expires = "+1d";
7164 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7165 or die_error(500, "Open git-cat-file blob '$hash' failed");
7167 # content-type (can include charset)
7168 $type = blob_contenttype($fd, $file_name, $type);
7170 # "save as" filename, even when no $file_name is given
7171 my $save_as = "$hash";
7172 if (defined $file_name) {
7173 $save_as = $file_name;
7174 } elsif ($type =~ m/^text\//) {
7175 $save_as .= '.txt';
7178 # With XSS prevention on, blobs of all types except a few known safe
7179 # ones are served with "Content-Disposition: attachment" to make sure
7180 # they don't run in our security domain. For certain image types,
7181 # blob view writes an <img> tag referring to blob_plain view, and we
7182 # want to be sure not to break that by serving the image as an
7183 # attachment (though Firefox 3 doesn't seem to care).
7184 my $sandbox = $prevent_xss &&
7185 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7187 # serve text/* as text/plain
7188 if ($prevent_xss &&
7189 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7190 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7191 my $rest = $1;
7192 $rest = defined $rest ? $rest : '';
7193 $type = "text/plain$rest";
7196 print $cgi->header(
7197 -type => $type,
7198 -expires => $expires,
7199 -content_disposition =>
7200 ($sandbox ? 'attachment' : 'inline')
7201 . '; filename="' . $save_as . '"');
7202 local $/ = undef;
7203 binmode STDOUT, ':raw';
7204 print <$fd>;
7205 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7206 close $fd;
7209 sub git_blob {
7210 my $expires;
7212 if (!defined $hash) {
7213 if (defined $file_name) {
7214 my $base = $hash_base || git_get_head_hash($project);
7215 $hash = git_get_hash_by_path($base, $file_name, "blob")
7216 or die_error(404, "Cannot find file");
7217 } else {
7218 die_error(400, "No file name defined");
7220 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7221 # blobs defined by non-textual hash id's can be cached
7222 $expires = "+1d";
7225 my $have_blame = gitweb_check_feature('blame');
7226 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7227 or die_error(500, "Couldn't cat $file_name, $hash");
7228 my $mimetype = blob_mimetype($fd, $file_name);
7229 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7230 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7231 close $fd;
7232 return git_blob_plain($mimetype);
7234 # we can have blame only for text/* mimetype
7235 $have_blame &&= ($mimetype =~ m!^text/!);
7237 my $highlight = gitweb_check_feature('highlight');
7238 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7239 $fd = run_highlighter($fd, $highlight, $syntax)
7240 if $syntax;
7242 git_header_html(undef, $expires);
7243 my $formats_nav = '';
7244 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7245 if (defined $file_name) {
7246 if ($have_blame) {
7247 $formats_nav .=
7248 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7249 "blame") .
7250 " | ";
7252 $formats_nav .=
7253 $cgi->a({-href => href(action=>"history", -replay=>1)},
7254 "history") .
7255 " | " .
7256 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7257 "raw") .
7258 " | " .
7259 $cgi->a({-href => href(action=>"blob",
7260 hash_base=>"HEAD", file_name=>$file_name)},
7261 "HEAD");
7262 } else {
7263 $formats_nav .=
7264 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7265 "raw");
7267 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7268 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7269 } else {
7270 print "<div class=\"page_nav\">\n" .
7271 "<br/><br/></div>\n" .
7272 "<div class=\"title\">".esc_html($hash)."</div>\n";
7274 git_print_page_path($file_name, "blob", $hash_base);
7275 print "<div class=\"page_body\">\n";
7276 if ($mimetype =~ m!^image/!) {
7277 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7278 if ($file_name) {
7279 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7281 print qq! src="! .
7282 href(action=>"blob_plain", hash=>$hash,
7283 hash_base=>$hash_base, file_name=>$file_name) .
7284 qq!" />\n!;
7285 } else {
7286 my $nr;
7287 while (my $line = <$fd>) {
7288 chomp $line;
7289 $nr++;
7290 $line = untabify($line);
7291 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7292 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7293 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7296 close $fd
7297 or print "Reading blob failed.\n";
7298 print "</div>";
7299 git_footer_html();
7302 sub git_tree {
7303 if (!defined $hash_base) {
7304 $hash_base = "HEAD";
7306 if (!defined $hash) {
7307 if (defined $file_name) {
7308 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7309 } else {
7310 $hash = $hash_base;
7313 die_error(404, "No such tree") unless defined($hash);
7315 my $show_sizes = gitweb_check_feature('show-sizes');
7316 my $have_blame = gitweb_check_feature('blame');
7318 my @entries = ();
7320 local $/ = "\0";
7321 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7322 ($show_sizes ? '-l' : ()), @extra_options, $hash
7323 or die_error(500, "Open git-ls-tree failed");
7324 @entries = map { chomp; $_ } <$fd>;
7325 close $fd
7326 or die_error(404, "Reading tree failed");
7329 my $refs = git_get_references();
7330 my $ref = format_ref_marker($refs, $hash_base);
7331 git_header_html();
7332 my $basedir = '';
7333 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7334 my @views_nav = ();
7335 if (defined $file_name) {
7336 push @views_nav,
7337 $cgi->a({-href => href(action=>"history", -replay=>1)},
7338 "history"),
7339 $cgi->a({-href => href(action=>"tree",
7340 hash_base=>"HEAD", file_name=>$file_name)},
7341 "HEAD"),
7343 my $snapshot_links = format_snapshot_links($hash);
7344 if (defined $snapshot_links) {
7345 # FIXME: Should be available when we have no hash base as well.
7346 push @views_nav, $snapshot_links;
7348 git_print_page_nav('tree','', $hash_base, undef, undef,
7349 join(' | ', @views_nav));
7350 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7351 } else {
7352 undef $hash_base;
7353 print "<div class=\"page_nav\">\n";
7354 print "<br/><br/></div>\n";
7355 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7357 if (defined $file_name) {
7358 $basedir = $file_name;
7359 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7360 $basedir .= '/';
7362 git_print_page_path($file_name, 'tree', $hash_base);
7364 print "<div class=\"page_body\">\n";
7365 print "<table class=\"tree\">\n";
7366 my $alternate = 1;
7367 # '..' (top directory) link if possible
7368 if (defined $hash_base &&
7369 defined $file_name && $file_name =~ m![^/]+$!) {
7370 if ($alternate) {
7371 print "<tr class=\"dark\">\n";
7372 } else {
7373 print "<tr class=\"light\">\n";
7375 $alternate ^= 1;
7377 my $up = $file_name;
7378 $up =~ s!/?[^/]+$!!;
7379 undef $up unless $up;
7380 # based on git_print_tree_entry
7381 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7382 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7383 print '<td class="list">';
7384 print $cgi->a({-href => href(action=>"tree",
7385 hash_base=>$hash_base,
7386 file_name=>$up)},
7387 "..");
7388 print "</td>\n";
7389 print "<td class=\"link\"></td>\n";
7391 print "</tr>\n";
7393 foreach my $line (@entries) {
7394 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7396 if ($alternate) {
7397 print "<tr class=\"dark\">\n";
7398 } else {
7399 print "<tr class=\"light\">\n";
7401 $alternate ^= 1;
7403 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7405 print "</tr>\n";
7407 print "</table>\n" .
7408 "</div>";
7409 git_footer_html();
7412 sub sanitize_for_filename {
7413 my $name = shift;
7415 $name =~ s!/!-!g;
7416 $name =~ s/[^[:alnum:]_.-]//g;
7418 return $name;
7421 sub snapshot_name {
7422 my ($project, $hash) = @_;
7424 # path/to/project.git -> project
7425 # path/to/project/.git -> project
7426 my $name = to_utf8($project);
7427 $name =~ s,([^/])/*\.git$,$1,;
7428 $name = sanitize_for_filename(basename($name));
7430 my $ver = $hash;
7431 if ($hash =~ /^[0-9a-fA-F]+$/) {
7432 # shorten SHA-1 hash
7433 my $full_hash = git_get_full_hash($project, $hash);
7434 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7435 $ver = git_get_short_hash($project, $hash);
7437 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7438 # tags don't need shortened SHA-1 hash
7439 $ver = $1;
7440 } else {
7441 # branches and other need shortened SHA-1 hash
7442 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7443 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7444 my $ref_dir = (defined $1) ? $1 : '';
7445 $ver = $2;
7447 $ref_dir = sanitize_for_filename($ref_dir);
7448 # for refs neither in heads nor remotes we want to
7449 # add a ref dir to archive name
7450 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7451 $ver = $ref_dir . '-' . $ver;
7454 $ver .= '-' . git_get_short_hash($project, $hash);
7456 # special case of sanitization for filename - we change
7457 # slashes to dots instead of dashes
7458 # in case of hierarchical branch names
7459 $ver =~ s!/!.!g;
7460 $ver =~ s/[^[:alnum:]_.-]//g;
7462 # name = project-version_string
7463 $name = "$name-$ver";
7465 return wantarray ? ($name, $name) : $name;
7468 sub exit_if_unmodified_since {
7469 my ($latest_epoch) = @_;
7470 our $cgi;
7472 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7473 if (defined $if_modified) {
7474 my $since;
7475 if (eval { require HTTP::Date; 1; }) {
7476 $since = HTTP::Date::str2time($if_modified);
7477 } elsif (eval { require Time::ParseDate; 1; }) {
7478 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7480 if (defined $since && $latest_epoch <= $since) {
7481 my %latest_date = parse_date($latest_epoch);
7482 print $cgi->header(
7483 -last_modified => $latest_date{'rfc2822'},
7484 -status => '304 Not Modified');
7485 goto DONE_GITWEB;
7490 sub git_snapshot {
7491 my $format = $input_params{'snapshot_format'};
7492 if (!@snapshot_fmts) {
7493 die_error(403, "Snapshots not allowed");
7495 # default to first supported snapshot format
7496 $format ||= $snapshot_fmts[0];
7497 if ($format !~ m/^[a-z0-9]+$/) {
7498 die_error(400, "Invalid snapshot format parameter");
7499 } elsif (!exists($known_snapshot_formats{$format})) {
7500 die_error(400, "Unknown snapshot format");
7501 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7502 die_error(403, "Snapshot format not allowed");
7503 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7504 die_error(403, "Unsupported snapshot format");
7507 my $type = git_get_type("$hash^{}");
7508 if (!$type) {
7509 die_error(404, 'Object does not exist');
7510 } elsif ($type eq 'blob') {
7511 die_error(400, 'Object is not a tree-ish');
7514 my ($name, $prefix) = snapshot_name($project, $hash);
7515 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7517 my %co = parse_commit($hash);
7518 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7520 my $cmd = quote_command(
7521 git_cmd(), 'archive',
7522 "--format=$known_snapshot_formats{$format}{'format'}",
7523 "--prefix=$prefix/", $hash);
7524 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7525 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7528 $filename =~ s/(["\\])/\\$1/g;
7529 my %latest_date;
7530 if (%co) {
7531 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7534 print $cgi->header(
7535 -type => $known_snapshot_formats{$format}{'type'},
7536 -content_disposition => 'inline; filename="' . $filename . '"',
7537 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7538 -status => '200 OK');
7540 open my $fd, "-|", $cmd
7541 or die_error(500, "Execute git-archive failed");
7542 binmode STDOUT, ':raw';
7543 print <$fd>;
7544 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7545 close $fd;
7548 sub git_log_generic {
7549 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7551 my $head = git_get_head_hash($project);
7552 if (!defined $base) {
7553 $base = $head;
7555 if (!defined $page) {
7556 $page = 0;
7558 my $refs = git_get_references();
7560 my $commit_hash = $base;
7561 if (defined $parent) {
7562 $commit_hash = "$parent..$base";
7564 my @commitlist =
7565 parse_commits($commit_hash, 101, (100 * $page),
7566 defined $file_name ? ($file_name, "--full-history") : ());
7568 my $ftype;
7569 if (!defined $file_hash && defined $file_name) {
7570 # some commits could have deleted file in question,
7571 # and not have it in tree, but one of them has to have it
7572 for (my $i = 0; $i < @commitlist; $i++) {
7573 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7574 last if defined $file_hash;
7577 if (defined $file_hash) {
7578 $ftype = git_get_type($file_hash);
7580 if (defined $file_name && !defined $ftype) {
7581 die_error(500, "Unknown type of object");
7583 my %co;
7584 if (defined $file_name) {
7585 %co = parse_commit($base)
7586 or die_error(404, "Unknown commit object");
7590 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7591 my $next_link = '';
7592 if ($#commitlist >= 100) {
7593 $next_link =
7594 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7595 -accesskey => "n", -title => "Alt-n"}, "next");
7597 my $patch_max = gitweb_get_feature('patches');
7598 if ($patch_max && !defined $file_name) {
7599 if ($patch_max < 0 || @commitlist <= $patch_max) {
7600 $paging_nav .= " &sdot; " .
7601 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7602 "patches");
7606 git_header_html();
7607 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7608 if (defined $file_name) {
7609 git_print_header_div('commit', esc_html($co{'title'}), $base);
7610 } else {
7611 git_print_header_div('summary', $project)
7613 git_print_page_path($file_name, $ftype, $hash_base)
7614 if (defined $file_name);
7616 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7617 $file_name, $file_hash, $ftype);
7619 git_footer_html();
7622 sub git_log {
7623 git_log_generic('log', \&git_log_body,
7624 $hash, $hash_parent);
7627 sub git_commit {
7628 $hash ||= $hash_base || "HEAD";
7629 my %co = parse_commit($hash)
7630 or die_error(404, "Unknown commit object");
7632 my $parent = $co{'parent'};
7633 my $parents = $co{'parents'}; # listref
7635 # we need to prepare $formats_nav before any parameter munging
7636 my $formats_nav;
7637 if (!defined $parent) {
7638 # --root commitdiff
7639 $formats_nav .= '(initial)';
7640 } elsif (@$parents == 1) {
7641 # single parent commit
7642 $formats_nav .=
7643 '(parent: ' .
7644 $cgi->a({-href => href(action=>"commit",
7645 hash=>$parent)},
7646 esc_html(substr($parent, 0, 7))) .
7647 ')';
7648 } else {
7649 # merge commit
7650 $formats_nav .=
7651 '(merge: ' .
7652 join(' ', map {
7653 $cgi->a({-href => href(action=>"commit",
7654 hash=>$_)},
7655 esc_html(substr($_, 0, 7)));
7656 } @$parents ) .
7657 ')';
7659 if (gitweb_check_feature('patches') && @$parents <= 1) {
7660 $formats_nav .= " | " .
7661 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7662 "patch");
7665 if (!defined $parent) {
7666 $parent = "--root";
7668 my @difftree;
7669 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7670 @diff_opts,
7671 (@$parents <= 1 ? $parent : '-c'),
7672 $hash, "--"
7673 or die_error(500, "Open git-diff-tree failed");
7674 @difftree = map { chomp; $_ } <$fd>;
7675 close $fd or die_error(404, "Reading git-diff-tree failed");
7677 # non-textual hash id's can be cached
7678 my $expires;
7679 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7680 $expires = "+1d";
7682 my $refs = git_get_references();
7683 my $ref = format_ref_marker($refs, $co{'id'});
7685 git_header_html(undef, $expires);
7686 git_print_page_nav('commit', '',
7687 $hash, $co{'tree'}, $hash,
7688 $formats_nav);
7690 if (defined $co{'parent'}) {
7691 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7692 } else {
7693 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7695 print "<div class=\"title_text\">\n" .
7696 "<table class=\"object_header\">\n";
7697 git_print_authorship_rows(\%co);
7698 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7699 print "<tr>" .
7700 "<td>tree</td>" .
7701 "<td class=\"sha1\">" .
7702 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7703 class => "list"}, $co{'tree'}) .
7704 "</td>" .
7705 "<td class=\"link\">" .
7706 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7707 "tree");
7708 my $snapshot_links = format_snapshot_links($hash);
7709 if (defined $snapshot_links) {
7710 print " | " . $snapshot_links;
7712 print "</td>" .
7713 "</tr>\n";
7715 foreach my $par (@$parents) {
7716 print "<tr>" .
7717 "<td>parent</td>" .
7718 "<td class=\"sha1\">" .
7719 $cgi->a({-href => href(action=>"commit", hash=>$par),
7720 class => "list"}, $par) .
7721 "</td>" .
7722 "<td class=\"link\">" .
7723 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7724 " | " .
7725 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7726 "</td>" .
7727 "</tr>\n";
7729 print "</table>".
7730 "</div>\n";
7732 print "<div class=\"page_body\">\n";
7733 git_print_log($co{'comment'});
7734 print "</div>\n";
7736 git_difftree_body(\@difftree, $hash, @$parents);
7738 git_footer_html();
7741 sub git_object {
7742 # object is defined by:
7743 # - hash or hash_base alone
7744 # - hash_base and file_name
7745 my $type;
7747 # - hash or hash_base alone
7748 if ($hash || ($hash_base && !defined $file_name)) {
7749 my $object_id = $hash || $hash_base;
7751 open my $fd, "-|", quote_command(
7752 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7753 or die_error(404, "Object does not exist");
7754 $type = <$fd>;
7755 chomp $type;
7756 close $fd
7757 or die_error(404, "Object does not exist");
7759 # - hash_base and file_name
7760 } elsif ($hash_base && defined $file_name) {
7761 $file_name =~ s,/+$,,;
7763 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7764 or die_error(404, "Base object does not exist");
7766 # here errors should not happen
7767 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7768 or die_error(500, "Open git-ls-tree failed");
7769 my $line = <$fd>;
7770 close $fd;
7772 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7773 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7774 die_error(404, "File or directory for given base does not exist");
7776 $type = $2;
7777 $hash = $3;
7778 } else {
7779 die_error(400, "Not enough information to find object");
7782 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7783 hash=>$hash, hash_base=>$hash_base,
7784 file_name=>$file_name),
7785 -status => '302 Found');
7788 sub git_blobdiff {
7789 my $format = shift || 'html';
7790 my $diff_style = $input_params{'diff_style'} || 'inline';
7792 my $fd;
7793 my @difftree;
7794 my %diffinfo;
7795 my $expires;
7797 # preparing $fd and %diffinfo for git_patchset_body
7798 # new style URI
7799 if (defined $hash_base && defined $hash_parent_base) {
7800 if (defined $file_name) {
7801 # read raw output
7802 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7803 $hash_parent_base, $hash_base,
7804 "--", (defined $file_parent ? $file_parent : ()), $file_name
7805 or die_error(500, "Open git-diff-tree failed");
7806 @difftree = map { chomp; $_ } <$fd>;
7807 close $fd
7808 or die_error(404, "Reading git-diff-tree failed");
7809 @difftree
7810 or die_error(404, "Blob diff not found");
7812 } elsif (defined $hash &&
7813 $hash =~ /[0-9a-fA-F]{40}/) {
7814 # try to find filename from $hash
7816 # read filtered raw output
7817 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7818 $hash_parent_base, $hash_base, "--"
7819 or die_error(500, "Open git-diff-tree failed");
7820 @difftree =
7821 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7822 # $hash == to_id
7823 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7824 map { chomp; $_ } <$fd>;
7825 close $fd
7826 or die_error(404, "Reading git-diff-tree failed");
7827 @difftree
7828 or die_error(404, "Blob diff not found");
7830 } else {
7831 die_error(400, "Missing one of the blob diff parameters");
7834 if (@difftree > 1) {
7835 die_error(400, "Ambiguous blob diff specification");
7838 %diffinfo = parse_difftree_raw_line($difftree[0]);
7839 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7840 $file_name ||= $diffinfo{'to_file'};
7842 $hash_parent ||= $diffinfo{'from_id'};
7843 $hash ||= $diffinfo{'to_id'};
7845 # non-textual hash id's can be cached
7846 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7847 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7848 $expires = '+1d';
7851 # open patch output
7852 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7853 '-p', ($format eq 'html' ? "--full-index" : ()),
7854 $hash_parent_base, $hash_base,
7855 "--", (defined $file_parent ? $file_parent : ()), $file_name
7856 or die_error(500, "Open git-diff-tree failed");
7859 # old/legacy style URI -- not generated anymore since 1.4.3.
7860 if (!%diffinfo) {
7861 die_error('404 Not Found', "Missing one of the blob diff parameters")
7864 # header
7865 if ($format eq 'html') {
7866 my $formats_nav =
7867 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7868 "raw");
7869 $formats_nav .= diff_style_nav($diff_style);
7870 git_header_html(undef, $expires);
7871 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7872 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7873 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7874 } else {
7875 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7876 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7878 if (defined $file_name) {
7879 git_print_page_path($file_name, "blob", $hash_base);
7880 } else {
7881 print "<div class=\"page_path\"></div>\n";
7884 } elsif ($format eq 'plain') {
7885 print $cgi->header(
7886 -type => 'text/plain',
7887 -charset => 'utf-8',
7888 -expires => $expires,
7889 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7891 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7893 } else {
7894 die_error(400, "Unknown blobdiff format");
7897 # patch
7898 if ($format eq 'html') {
7899 print "<div class=\"page_body\">\n";
7901 git_patchset_body($fd, $diff_style,
7902 [ \%diffinfo ], $hash_base, $hash_parent_base);
7903 close $fd;
7905 print "</div>\n"; # class="page_body"
7906 git_footer_html();
7908 } else {
7909 while (my $line = <$fd>) {
7910 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7911 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7913 print $line;
7915 last if $line =~ m!^\+\+\+!;
7917 local $/ = undef;
7918 print <$fd>;
7919 close $fd;
7923 sub git_blobdiff_plain {
7924 git_blobdiff('plain');
7927 # assumes that it is added as later part of already existing navigation,
7928 # so it returns "| foo | bar" rather than just "foo | bar"
7929 sub diff_style_nav {
7930 my ($diff_style, $is_combined) = @_;
7931 $diff_style ||= 'inline';
7933 return "" if ($is_combined);
7935 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7936 my %styles = @styles;
7937 @styles =
7938 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7940 return join '',
7941 map { " | ".$_ }
7942 map {
7943 $_ eq $diff_style ? $styles{$_} :
7944 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7945 } @styles;
7948 sub git_commitdiff {
7949 my %params = @_;
7950 my $format = $params{-format} || 'html';
7951 my $diff_style = $input_params{'diff_style'} || 'inline';
7953 my ($patch_max) = gitweb_get_feature('patches');
7954 if ($format eq 'patch') {
7955 die_error(403, "Patch view not allowed") unless $patch_max;
7958 $hash ||= $hash_base || "HEAD";
7959 my %co = parse_commit($hash)
7960 or die_error(404, "Unknown commit object");
7962 # choose format for commitdiff for merge
7963 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7964 $hash_parent = '--cc';
7966 # we need to prepare $formats_nav before almost any parameter munging
7967 my $formats_nav;
7968 if ($format eq 'html') {
7969 $formats_nav =
7970 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7971 "raw");
7972 if ($patch_max && @{$co{'parents'}} <= 1) {
7973 $formats_nav .= " | " .
7974 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7975 "patch");
7977 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7979 if (defined $hash_parent &&
7980 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7981 # commitdiff with two commits given
7982 my $hash_parent_short = $hash_parent;
7983 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7984 $hash_parent_short = substr($hash_parent, 0, 7);
7986 $formats_nav .=
7987 ' (from';
7988 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7989 if ($co{'parents'}[$i] eq $hash_parent) {
7990 $formats_nav .= ' parent ' . ($i+1);
7991 last;
7994 $formats_nav .= ': ' .
7995 $cgi->a({-href => href(-replay=>1,
7996 hash=>$hash_parent, hash_base=>undef)},
7997 esc_html($hash_parent_short)) .
7998 ')';
7999 } elsif (!$co{'parent'}) {
8000 # --root commitdiff
8001 $formats_nav .= ' (initial)';
8002 } elsif (scalar @{$co{'parents'}} == 1) {
8003 # single parent commit
8004 $formats_nav .=
8005 ' (parent: ' .
8006 $cgi->a({-href => href(-replay=>1,
8007 hash=>$co{'parent'}, hash_base=>undef)},
8008 esc_html(substr($co{'parent'}, 0, 7))) .
8009 ')';
8010 } else {
8011 # merge commit
8012 if ($hash_parent eq '--cc') {
8013 $formats_nav .= ' | ' .
8014 $cgi->a({-href => href(-replay=>1,
8015 hash=>$hash, hash_parent=>'-c')},
8016 'combined');
8017 } else { # $hash_parent eq '-c'
8018 $formats_nav .= ' | ' .
8019 $cgi->a({-href => href(-replay=>1,
8020 hash=>$hash, hash_parent=>'--cc')},
8021 'compact');
8023 $formats_nav .=
8024 ' (merge: ' .
8025 join(' ', map {
8026 $cgi->a({-href => href(-replay=>1,
8027 hash=>$_, hash_base=>undef)},
8028 esc_html(substr($_, 0, 7)));
8029 } @{$co{'parents'}} ) .
8030 ')';
8034 my $hash_parent_param = $hash_parent;
8035 if (!defined $hash_parent_param) {
8036 # --cc for multiple parents, --root for parentless
8037 $hash_parent_param =
8038 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
8041 # read commitdiff
8042 my $fd;
8043 my @difftree;
8044 if ($format eq 'html') {
8045 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8046 "--no-commit-id", "--patch-with-raw", "--full-index",
8047 $hash_parent_param, $hash, "--"
8048 or die_error(500, "Open git-diff-tree failed");
8050 while (my $line = <$fd>) {
8051 chomp $line;
8052 # empty line ends raw part of diff-tree output
8053 last unless $line;
8054 push @difftree, scalar parse_difftree_raw_line($line);
8057 } elsif ($format eq 'plain') {
8058 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8059 '-p', $hash_parent_param, $hash, "--"
8060 or die_error(500, "Open git-diff-tree failed");
8061 } elsif ($format eq 'patch') {
8062 # For commit ranges, we limit the output to the number of
8063 # patches specified in the 'patches' feature.
8064 # For single commits, we limit the output to a single patch,
8065 # diverging from the git-format-patch default.
8066 my @commit_spec = ();
8067 if ($hash_parent) {
8068 if ($patch_max > 0) {
8069 push @commit_spec, "-$patch_max";
8071 push @commit_spec, '-n', "$hash_parent..$hash";
8072 } else {
8073 if ($params{-single}) {
8074 push @commit_spec, '-1';
8075 } else {
8076 if ($patch_max > 0) {
8077 push @commit_spec, "-$patch_max";
8079 push @commit_spec, "-n";
8081 push @commit_spec, '--root', $hash;
8083 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
8084 '--encoding=utf8', '--stdout', @commit_spec
8085 or die_error(500, "Open git-format-patch failed");
8086 } else {
8087 die_error(400, "Unknown commitdiff format");
8090 # non-textual hash id's can be cached
8091 my $expires;
8092 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8093 $expires = "+1d";
8096 # write commit message
8097 if ($format eq 'html') {
8098 my $refs = git_get_references();
8099 my $ref = format_ref_marker($refs, $co{'id'});
8101 git_header_html(undef, $expires);
8102 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
8103 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
8104 print "<div class=\"title_text\">\n" .
8105 "<table class=\"object_header\">\n";
8106 git_print_authorship_rows(\%co);
8107 print "</table>".
8108 "</div>\n";
8109 print "<div class=\"page_body\">\n";
8110 if (@{$co{'comment'}} > 1) {
8111 print "<div class=\"log\">\n";
8112 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
8113 print "</div>\n"; # class="log"
8116 } elsif ($format eq 'plain') {
8117 my $refs = git_get_references("tags");
8118 my $tagname = git_get_rev_name_tags($hash);
8119 my $filename = basename($project) . "-$hash.patch";
8121 print $cgi->header(
8122 -type => 'text/plain',
8123 -charset => 'utf-8',
8124 -expires => $expires,
8125 -content_disposition => 'inline; filename="' . "$filename" . '"');
8126 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8127 print "From: " . to_utf8($co{'author'}) . "\n";
8128 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8129 print "Subject: " . to_utf8($co{'title'}) . "\n";
8131 print "X-Git-Tag: $tagname\n" if $tagname;
8132 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8134 foreach my $line (@{$co{'comment'}}) {
8135 print to_utf8($line) . "\n";
8137 print "---\n\n";
8138 } elsif ($format eq 'patch') {
8139 my $filename = basename($project) . "-$hash.patch";
8141 print $cgi->header(
8142 -type => 'text/plain',
8143 -charset => 'utf-8',
8144 -expires => $expires,
8145 -content_disposition => 'inline; filename="' . "$filename" . '"');
8148 # write patch
8149 if ($format eq 'html') {
8150 my $use_parents = !defined $hash_parent ||
8151 $hash_parent eq '-c' || $hash_parent eq '--cc';
8152 git_difftree_body(\@difftree, $hash,
8153 $use_parents ? @{$co{'parents'}} : $hash_parent);
8154 print "<br/>\n";
8156 git_patchset_body($fd, $diff_style,
8157 \@difftree, $hash,
8158 $use_parents ? @{$co{'parents'}} : $hash_parent);
8159 close $fd;
8160 print "</div>\n"; # class="page_body"
8161 git_footer_html();
8163 } elsif ($format eq 'plain') {
8164 local $/ = undef;
8165 print <$fd>;
8166 close $fd
8167 or print "Reading git-diff-tree failed\n";
8168 } elsif ($format eq 'patch') {
8169 local $/ = undef;
8170 print <$fd>;
8171 close $fd
8172 or print "Reading git-format-patch failed\n";
8176 sub git_commitdiff_plain {
8177 git_commitdiff(-format => 'plain');
8180 # format-patch-style patches
8181 sub git_patch {
8182 git_commitdiff(-format => 'patch', -single => 1);
8185 sub git_patches {
8186 git_commitdiff(-format => 'patch');
8189 sub git_history {
8190 git_log_generic('history', \&git_history_body,
8191 $hash_base, $hash_parent_base,
8192 $file_name, $hash);
8195 sub git_search {
8196 $searchtype ||= 'commit';
8198 # check if appropriate features are enabled
8199 gitweb_check_feature('search')
8200 or die_error(403, "Search is disabled");
8201 if ($searchtype eq 'pickaxe') {
8202 # pickaxe may take all resources of your box and run for several minutes
8203 # with every query - so decide by yourself how public you make this feature
8204 gitweb_check_feature('pickaxe')
8205 or die_error(403, "Pickaxe search is disabled");
8207 if ($searchtype eq 'grep') {
8208 # grep search might be potentially CPU-intensive, too
8209 gitweb_check_feature('grep')
8210 or die_error(403, "Grep search is disabled");
8213 if (!defined $searchtext) {
8214 die_error(400, "Text field is empty");
8216 if (!defined $hash) {
8217 $hash = git_get_head_hash($project);
8219 my %co = parse_commit($hash);
8220 if (!%co) {
8221 die_error(404, "Unknown commit object");
8223 if (!defined $page) {
8224 $page = 0;
8227 if ($searchtype eq 'commit' ||
8228 $searchtype eq 'author' ||
8229 $searchtype eq 'committer') {
8230 git_search_message(%co);
8231 } elsif ($searchtype eq 'pickaxe') {
8232 git_search_changes(%co);
8233 } elsif ($searchtype eq 'grep') {
8234 git_search_files(%co);
8235 } else {
8236 die_error(400, "Unknown search type");
8240 sub git_search_help {
8241 git_header_html();
8242 git_print_page_nav('','', $hash,$hash,$hash);
8243 print <<EOT;
8244 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8245 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8246 the pattern entered is recognized as the POSIX extended
8247 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8248 insensitive).</p>
8249 <dl>
8250 <dt><b>commit</b></dt>
8251 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8253 my $have_grep = gitweb_check_feature('grep');
8254 if ($have_grep) {
8255 print <<EOT;
8256 <dt><b>grep</b></dt>
8257 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8258 a different one) are searched for the given pattern. On large trees, this search can take
8259 a while and put some strain on the server, so please use it with some consideration. Note that
8260 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8261 case-sensitive.</dd>
8264 print <<EOT;
8265 <dt><b>author</b></dt>
8266 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8267 <dt><b>committer</b></dt>
8268 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8270 my $have_pickaxe = gitweb_check_feature('pickaxe');
8271 if ($have_pickaxe) {
8272 print <<EOT;
8273 <dt><b>pickaxe</b></dt>
8274 <dd>All commits that caused the string to appear or disappear from any file (changes that
8275 added, removed or "modified" the string) will be listed. This search can take a while and
8276 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8277 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8280 print "</dl>\n";
8281 git_footer_html();
8284 sub git_shortlog {
8285 git_log_generic('shortlog', \&git_shortlog_body,
8286 $hash, $hash_parent);
8289 ## ......................................................................
8290 ## feeds (RSS, Atom; OPML)
8292 sub git_feed {
8293 my $format = shift || 'atom';
8294 my $have_blame = gitweb_check_feature('blame');
8296 # Atom: http://www.atomenabled.org/developers/syndication/
8297 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8298 if ($format ne 'rss' && $format ne 'atom') {
8299 die_error(400, "Unknown web feed format");
8302 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8303 my $head = $hash || 'HEAD';
8304 my @commitlist = parse_commits($head, 150, 0, $file_name);
8306 my %latest_commit;
8307 my %latest_date;
8308 my $content_type = "application/$format+xml";
8309 if (defined $cgi->http('HTTP_ACCEPT') &&
8310 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8311 # browser (feed reader) prefers text/xml
8312 $content_type = 'text/xml';
8314 if (defined($commitlist[0])) {
8315 %latest_commit = %{$commitlist[0]};
8316 my $latest_epoch = $latest_commit{'committer_epoch'};
8317 exit_if_unmodified_since($latest_epoch);
8318 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8320 print $cgi->header(
8321 -type => $content_type,
8322 -charset => 'utf-8',
8323 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8324 -status => '200 OK');
8326 # Optimization: skip generating the body if client asks only
8327 # for Last-Modified date.
8328 return if ($cgi->request_method() eq 'HEAD');
8330 # header variables
8331 my $title = "$site_name - $project/$action";
8332 my $feed_type = 'log';
8333 if (defined $hash) {
8334 $title .= " - '$hash'";
8335 $feed_type = 'branch log';
8336 if (defined $file_name) {
8337 $title .= " :: $file_name";
8338 $feed_type = 'history';
8340 } elsif (defined $file_name) {
8341 $title .= " - $file_name";
8342 $feed_type = 'history';
8344 $title .= " $feed_type";
8345 $title = esc_html($title);
8346 my $descr = git_get_project_description($project);
8347 if (defined $descr) {
8348 $descr = esc_html($descr);
8349 } else {
8350 $descr = "$project " .
8351 ($format eq 'rss' ? 'RSS' : 'Atom') .
8352 " feed";
8354 my $owner = git_get_project_owner($project);
8355 $owner = esc_html($owner);
8357 #header
8358 my $alt_url;
8359 if (defined $file_name) {
8360 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8361 } elsif (defined $hash) {
8362 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8363 } else {
8364 $alt_url = href(-full=>1, action=>"summary");
8366 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8367 if ($format eq 'rss') {
8368 print <<XML;
8369 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8370 <channel>
8372 print "<title>$title</title>\n" .
8373 "<link>$alt_url</link>\n" .
8374 "<description>$descr</description>\n" .
8375 "<language>en</language>\n" .
8376 # project owner is responsible for 'editorial' content
8377 "<managingEditor>$owner</managingEditor>\n";
8378 if (defined $logo || defined $favicon) {
8379 # prefer the logo to the favicon, since RSS
8380 # doesn't allow both
8381 my $img = esc_url($logo || $favicon);
8382 print "<image>\n" .
8383 "<url>$img</url>\n" .
8384 "<title>$title</title>\n" .
8385 "<link>$alt_url</link>\n" .
8386 "</image>\n";
8388 if (%latest_date) {
8389 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8390 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8392 print "<generator>gitweb v.$version/$git_version</generator>\n";
8393 } elsif ($format eq 'atom') {
8394 print <<XML;
8395 <feed xmlns="http://www.w3.org/2005/Atom">
8397 print "<title>$title</title>\n" .
8398 "<subtitle>$descr</subtitle>\n" .
8399 '<link rel="alternate" type="text/html" href="' .
8400 $alt_url . '" />' . "\n" .
8401 '<link rel="self" type="' . $content_type . '" href="' .
8402 $cgi->self_url() . '" />' . "\n" .
8403 "<id>" . href(-full=>1) . "</id>\n" .
8404 # use project owner for feed author
8405 "<author><name>$owner</name></author>\n";
8406 if (defined $favicon) {
8407 print "<icon>" . esc_url($favicon) . "</icon>\n";
8409 if (defined $logo) {
8410 # not twice as wide as tall: 72 x 27 pixels
8411 print "<logo>" . esc_url($logo) . "</logo>\n";
8413 if (! %latest_date) {
8414 # dummy date to keep the feed valid until commits trickle in:
8415 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8416 } else {
8417 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8419 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8422 # contents
8423 for (my $i = 0; $i <= $#commitlist; $i++) {
8424 my %co = %{$commitlist[$i]};
8425 my $commit = $co{'id'};
8426 # we read 150, we always show 30 and the ones more recent than 48 hours
8427 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8428 last;
8430 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8432 # get list of changed files
8433 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8434 $co{'parent'} || "--root",
8435 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8436 or next;
8437 my @difftree = map { chomp; $_ } <$fd>;
8438 close $fd
8439 or next;
8441 # print element (entry, item)
8442 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8443 if ($format eq 'rss') {
8444 print "<item>\n" .
8445 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8446 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8447 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8448 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8449 "<link>$co_url</link>\n" .
8450 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8451 "<content:encoded>" .
8452 "<![CDATA[\n";
8453 } elsif ($format eq 'atom') {
8454 print "<entry>\n" .
8455 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8456 "<updated>$cd{'iso-8601'}</updated>\n" .
8457 "<author>\n" .
8458 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8459 if ($co{'author_email'}) {
8460 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8462 print "</author>\n" .
8463 # use committer for contributor
8464 "<contributor>\n" .
8465 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8466 if ($co{'committer_email'}) {
8467 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8469 print "</contributor>\n" .
8470 "<published>$cd{'iso-8601'}</published>\n" .
8471 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8472 "<id>$co_url</id>\n" .
8473 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8474 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8476 my $comment = $co{'comment'};
8477 print "<pre>\n";
8478 foreach my $line (@$comment) {
8479 $line = esc_html($line);
8480 print "$line\n";
8482 print "</pre><ul>\n";
8483 foreach my $difftree_line (@difftree) {
8484 my %difftree = parse_difftree_raw_line($difftree_line);
8485 next if !$difftree{'from_id'};
8487 my $file = $difftree{'file'} || $difftree{'to_file'};
8489 print "<li>" .
8490 "[" .
8491 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8492 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8493 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8494 file_name=>$file, file_parent=>$difftree{'from_file'}),
8495 -title => "diff"}, 'D');
8496 if ($have_blame) {
8497 print $cgi->a({-href => href(-full=>1, action=>"blame",
8498 file_name=>$file, hash_base=>$commit),
8499 -title => "blame"}, 'B');
8501 # if this is not a feed of a file history
8502 if (!defined $file_name || $file_name ne $file) {
8503 print $cgi->a({-href => href(-full=>1, action=>"history",
8504 file_name=>$file, hash=>$commit),
8505 -title => "history"}, 'H');
8507 $file = esc_path($file);
8508 print "] ".
8509 "$file</li>\n";
8511 if ($format eq 'rss') {
8512 print "</ul>]]>\n" .
8513 "</content:encoded>\n" .
8514 "</item>\n";
8515 } elsif ($format eq 'atom') {
8516 print "</ul>\n</div>\n" .
8517 "</content>\n" .
8518 "</entry>\n";
8522 # end of feed
8523 if ($format eq 'rss') {
8524 print "</channel>\n</rss>\n";
8525 } elsif ($format eq 'atom') {
8526 print "</feed>\n";
8530 sub git_rss {
8531 git_feed('rss');
8534 sub git_atom {
8535 git_feed('atom');
8538 sub git_opml {
8539 my @list = git_get_projects_list($project_filter, $strict_export);
8540 if (!@list) {
8541 die_error(404, "No projects found");
8544 print $cgi->header(
8545 -type => 'text/xml',
8546 -charset => 'utf-8',
8547 -content_disposition => 'inline; filename="opml.xml"');
8549 my $title = esc_html($site_name);
8550 my $filter = " within subdirectory ";
8551 if (defined $project_filter) {
8552 $filter .= esc_html($project_filter);
8553 } else {
8554 $filter = "";
8556 print <<XML;
8557 <?xml version="1.0" encoding="utf-8"?>
8558 <opml version="1.0">
8559 <head>
8560 <title>$title OPML Export$filter</title>
8561 </head>
8562 <body>
8563 <outline text="git RSS feeds">
8566 foreach my $pr (@list) {
8567 my %proj = %$pr;
8568 my $head = git_get_head_hash($proj{'path'});
8569 if (!defined $head) {
8570 next;
8572 $git_dir = "$projectroot/$proj{'path'}";
8573 my %co = parse_commit($head);
8574 if (!%co) {
8575 next;
8578 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8579 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8580 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8581 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8583 print <<XML;
8584 </outline>
8585 </body>
8586 </opml>