Merge commit 'refs/top-bases/t/projlist-cache/caching' into t/projlist-cache/caching
[git/gitweb.git] / gitweb / gitweb.perl
blobc4273dfd9cd4c2db1490fab1a7cbee38290c1172
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 # dispatch
1236 sub dispatch {
1237 if (!defined $action) {
1238 if (defined $hash) {
1239 $action = git_get_type($hash);
1240 $action or die_error(404, "Object does not exist");
1241 } elsif (defined $hash_base && defined $file_name) {
1242 $action = git_get_type("$hash_base:$file_name");
1243 $action or die_error(404, "File or directory does not exist");
1244 } elsif (defined $project) {
1245 $action = 'summary';
1246 } else {
1247 $action = 'frontpage';
1250 if (!defined($actions{$action})) {
1251 die_error(400, "Unknown action");
1253 if ($action !~ m/^(?:opml|frontpage|project_list|project_index)$/ &&
1254 !$project) {
1255 die_error(400, "Project needed");
1257 $actions{$action}->();
1260 sub reset_timer {
1261 our $t0 = [ gettimeofday() ]
1262 if defined $t0;
1263 our $number_of_git_cmds = 0;
1266 our $first_request = 1;
1267 sub run_request {
1268 reset_timer();
1270 evaluate_uri();
1271 if ($first_request) {
1272 evaluate_gitweb_config();
1273 evaluate_git_version();
1275 if ($per_request_config) {
1276 if (ref($per_request_config) eq 'CODE') {
1277 $per_request_config->();
1278 } elsif (!$first_request) {
1279 evaluate_gitweb_config();
1282 check_loadavg();
1284 # $projectroot and $projects_list might be set in gitweb config file
1285 $projects_list ||= $projectroot;
1287 evaluate_query_params();
1288 evaluate_path_info();
1289 evaluate_and_validate_params();
1290 evaluate_git_dir();
1292 configure_gitweb_features();
1294 dispatch();
1297 our $is_last_request = sub { 1 };
1298 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1299 our $CGI = 'CGI';
1300 our $cgi;
1301 sub configure_as_fcgi {
1302 require CGI::Fast;
1303 our $CGI = 'CGI::Fast';
1305 my $request_number = 0;
1306 # let each child service 100 requests
1307 our $is_last_request = sub { ++$request_number > 100 };
1309 sub evaluate_argv {
1310 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1311 configure_as_fcgi()
1312 if $script_name =~ /\.fcgi$/;
1314 return unless (@ARGV);
1316 require Getopt::Long;
1317 Getopt::Long::GetOptions(
1318 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1319 'nproc|n=i' => sub {
1320 my ($arg, $val) = @_;
1321 return unless eval { require FCGI::ProcManager; 1; };
1322 my $proc_manager = FCGI::ProcManager->new({
1323 n_processes => $val,
1325 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1326 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1327 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1332 sub run {
1333 evaluate_argv();
1335 $first_request = 1;
1336 $pre_listen_hook->()
1337 if $pre_listen_hook;
1339 REQUEST:
1340 while ($cgi = $CGI->new()) {
1341 $pre_dispatch_hook->()
1342 if $pre_dispatch_hook;
1344 run_request();
1346 $post_dispatch_hook->()
1347 if $post_dispatch_hook;
1348 $first_request = 0;
1350 last REQUEST if ($is_last_request->());
1353 DONE_GITWEB:
1357 run();
1359 if (defined caller) {
1360 # wrapped in a subroutine processing requests,
1361 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1362 return;
1363 } else {
1364 # pure CGI script, serving single request
1365 exit;
1368 ## ======================================================================
1369 ## action links
1371 # possible values of extra options
1372 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1373 # -replay => 1 - start from a current view (replay with modifications)
1374 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1375 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1376 sub href {
1377 my %params = @_;
1378 # default is to use -absolute url() i.e. $my_uri
1379 my $href = $params{-full} ? $my_url : $my_uri;
1381 # implicit -replay, must be first of implicit params
1382 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1384 $params{'project'} = $project unless exists $params{'project'};
1386 if ($params{-replay}) {
1387 while (my ($name, $symbol) = each %cgi_param_mapping) {
1388 if (!exists $params{$name}) {
1389 $params{$name} = $input_params{$name};
1394 my $use_pathinfo = gitweb_check_feature('pathinfo');
1395 if (defined $params{'project'} &&
1396 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1397 # try to put as many parameters as possible in PATH_INFO:
1398 # - project name
1399 # - action
1400 # - hash_parent or hash_parent_base:/file_parent
1401 # - hash or hash_base:/filename
1402 # - the snapshot_format as an appropriate suffix
1404 # When the script is the root DirectoryIndex for the domain,
1405 # $href here would be something like http://gitweb.example.com/
1406 # Thus, we strip any trailing / from $href, to spare us double
1407 # slashes in the final URL
1408 $href =~ s,/$,,;
1410 # Then add the project name, if present
1411 $href .= "/".esc_path_info($params{'project'});
1412 delete $params{'project'};
1414 # since we destructively absorb parameters, we keep this
1415 # boolean that remembers if we're handling a snapshot
1416 my $is_snapshot = $params{'action'} eq 'snapshot';
1418 # Summary just uses the project path URL, any other action is
1419 # added to the URL
1420 if (defined $params{'action'}) {
1421 $href .= "/".esc_path_info($params{'action'})
1422 unless $params{'action'} eq 'summary';
1423 delete $params{'action'};
1426 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1427 # stripping nonexistent or useless pieces
1428 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1429 || $params{'hash_parent'} || $params{'hash'});
1430 if (defined $params{'hash_base'}) {
1431 if (defined $params{'hash_parent_base'}) {
1432 $href .= esc_path_info($params{'hash_parent_base'});
1433 # skip the file_parent if it's the same as the file_name
1434 if (defined $params{'file_parent'}) {
1435 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1436 delete $params{'file_parent'};
1437 } elsif ($params{'file_parent'} !~ /\.\./) {
1438 $href .= ":/".esc_path_info($params{'file_parent'});
1439 delete $params{'file_parent'};
1442 $href .= "..";
1443 delete $params{'hash_parent'};
1444 delete $params{'hash_parent_base'};
1445 } elsif (defined $params{'hash_parent'}) {
1446 $href .= esc_path_info($params{'hash_parent'}). "..";
1447 delete $params{'hash_parent'};
1450 $href .= esc_path_info($params{'hash_base'});
1451 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1452 $href .= ":/".esc_path_info($params{'file_name'});
1453 delete $params{'file_name'};
1455 delete $params{'hash'};
1456 delete $params{'hash_base'};
1457 } elsif (defined $params{'hash'}) {
1458 $href .= esc_path_info($params{'hash'});
1459 delete $params{'hash'};
1462 # If the action was a snapshot, we can absorb the
1463 # snapshot_format parameter too
1464 if ($is_snapshot) {
1465 my $fmt = $params{'snapshot_format'};
1466 # snapshot_format should always be defined when href()
1467 # is called, but just in case some code forgets, we
1468 # fall back to the default
1469 $fmt ||= $snapshot_fmts[0];
1470 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1471 delete $params{'snapshot_format'};
1475 # now encode the parameters explicitly
1476 my @result = ();
1477 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1478 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1479 if (defined $params{$name}) {
1480 if (ref($params{$name}) eq "ARRAY") {
1481 foreach my $par (@{$params{$name}}) {
1482 push @result, $symbol . "=" . esc_param($par);
1484 } else {
1485 push @result, $symbol . "=" . esc_param($params{$name});
1489 $href .= "?" . join(';', @result) if scalar @result;
1491 # final transformation: trailing spaces must be escaped (URI-encoded)
1492 $href =~ s/(\s+)$/CGI::escape($1)/e;
1494 if ($params{-anchor}) {
1495 $href .= "#".esc_param($params{-anchor});
1498 return $href;
1502 ## ======================================================================
1503 ## validation, quoting/unquoting and escaping
1505 sub is_valid_action {
1506 my $input = shift;
1507 return undef unless exists $actions{$input};
1508 return 1;
1511 sub is_valid_project {
1512 my $input = shift;
1514 return unless defined $input;
1515 if (!is_valid_pathname($input) ||
1516 !(-d "$projectroot/$input") ||
1517 !check_export_ok("$projectroot/$input") ||
1518 ($strict_export && !project_in_list($input))) {
1519 return undef;
1520 } else {
1521 return 1;
1525 sub is_valid_pathname {
1526 my $input = shift;
1528 return undef unless defined $input;
1529 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1530 # at the beginning, at the end, and between slashes.
1531 # also this catches doubled slashes
1532 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1533 return undef;
1535 # no null characters
1536 if ($input =~ m!\0!) {
1537 return undef;
1539 return 1;
1542 sub is_valid_ref_format {
1543 my $input = shift;
1545 return undef unless defined $input;
1546 # restrictions on ref name according to git-check-ref-format
1547 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1548 return undef;
1550 return 1;
1553 sub is_valid_refname {
1554 my $input = shift;
1556 return undef unless defined $input;
1557 # textual hashes are O.K.
1558 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1559 return 1;
1561 # it must be correct pathname
1562 is_valid_pathname($input) or return undef;
1563 # check git-check-ref-format restrictions
1564 is_valid_ref_format($input) or return undef;
1565 return 1;
1568 # decode sequences of octets in utf8 into Perl's internal form,
1569 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1570 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1571 sub to_utf8 {
1572 my $str = shift;
1573 return undef unless defined $str;
1575 if (utf8::is_utf8($str) || utf8::decode($str)) {
1576 return $str;
1577 } else {
1578 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1582 # quote unsafe chars, but keep the slash, even when it's not
1583 # correct, but quoted slashes look too horrible in bookmarks
1584 sub esc_param {
1585 my $str = shift;
1586 return undef unless defined $str;
1587 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1588 $str =~ s/ /\+/g;
1589 return $str;
1592 # the quoting rules for path_info fragment are slightly different
1593 sub esc_path_info {
1594 my $str = shift;
1595 return undef unless defined $str;
1597 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1598 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1600 return $str;
1603 # quote unsafe chars in whole URL, so some characters cannot be quoted
1604 sub esc_url {
1605 my $str = shift;
1606 return undef unless defined $str;
1607 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1608 $str =~ s/ /\+/g;
1609 return $str;
1612 # quote unsafe characters in HTML attributes
1613 sub esc_attr {
1615 # for XHTML conformance escaping '"' to '&quot;' is not enough
1616 return esc_html(@_);
1619 # replace invalid utf8 character with SUBSTITUTION sequence
1620 sub esc_html {
1621 my $str = shift;
1622 my %opts = @_;
1624 return undef unless defined $str;
1626 $str = to_utf8($str);
1627 $str = $cgi->escapeHTML($str);
1628 if ($opts{'-nbsp'}) {
1629 $str =~ s/ /&nbsp;/g;
1631 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1632 return $str;
1635 # quote control characters and escape filename to HTML
1636 sub esc_path {
1637 my $str = shift;
1638 my %opts = @_;
1640 return undef unless defined $str;
1642 $str = to_utf8($str);
1643 $str = $cgi->escapeHTML($str);
1644 if ($opts{'-nbsp'}) {
1645 $str =~ s/ /&nbsp;/g;
1647 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1648 return $str;
1651 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1652 sub sanitize {
1653 my $str = shift;
1655 return undef unless defined $str;
1657 $str = to_utf8($str);
1658 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1659 return $str;
1662 # Make control characters "printable", using character escape codes (CEC)
1663 sub quot_cec {
1664 my $cntrl = shift;
1665 my %opts = @_;
1666 my %es = ( # character escape codes, aka escape sequences
1667 "\t" => '\t', # tab (HT)
1668 "\n" => '\n', # line feed (LF)
1669 "\r" => '\r', # carrige return (CR)
1670 "\f" => '\f', # form feed (FF)
1671 "\b" => '\b', # backspace (BS)
1672 "\a" => '\a', # alarm (bell) (BEL)
1673 "\e" => '\e', # escape (ESC)
1674 "\013" => '\v', # vertical tab (VT)
1675 "\000" => '\0', # nul character (NUL)
1677 my $chr = ( (exists $es{$cntrl})
1678 ? $es{$cntrl}
1679 : sprintf('\%2x', ord($cntrl)) );
1680 if ($opts{-nohtml}) {
1681 return $chr;
1682 } else {
1683 return "<span class=\"cntrl\">$chr</span>";
1687 # Alternatively use unicode control pictures codepoints,
1688 # Unicode "printable representation" (PR)
1689 sub quot_upr {
1690 my $cntrl = shift;
1691 my %opts = @_;
1693 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1694 if ($opts{-nohtml}) {
1695 return $chr;
1696 } else {
1697 return "<span class=\"cntrl\">$chr</span>";
1701 # git may return quoted and escaped filenames
1702 sub unquote {
1703 my $str = shift;
1705 sub unq {
1706 my $seq = shift;
1707 my %es = ( # character escape codes, aka escape sequences
1708 't' => "\t", # tab (HT, TAB)
1709 'n' => "\n", # newline (NL)
1710 'r' => "\r", # return (CR)
1711 'f' => "\f", # form feed (FF)
1712 'b' => "\b", # backspace (BS)
1713 'a' => "\a", # alarm (bell) (BEL)
1714 'e' => "\e", # escape (ESC)
1715 'v' => "\013", # vertical tab (VT)
1718 if ($seq =~ m/^[0-7]{1,3}$/) {
1719 # octal char sequence
1720 return chr(oct($seq));
1721 } elsif (exists $es{$seq}) {
1722 # C escape sequence, aka character escape code
1723 return $es{$seq};
1725 # quoted ordinary character
1726 return $seq;
1729 if ($str =~ m/^"(.*)"$/) {
1730 # needs unquoting
1731 $str = $1;
1732 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1734 return $str;
1737 # escape tabs (convert tabs to spaces)
1738 sub untabify {
1739 my $line = shift;
1741 while ((my $pos = index($line, "\t")) != -1) {
1742 if (my $count = (8 - ($pos % 8))) {
1743 my $spaces = ' ' x $count;
1744 $line =~ s/\t/$spaces/;
1748 return $line;
1751 sub project_in_list {
1752 my $project = shift;
1753 my @list = git_get_projects_list();
1754 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1757 ## ----------------------------------------------------------------------
1758 ## HTML aware string manipulation
1760 # Try to chop given string on a word boundary between position
1761 # $len and $len+$add_len. If there is no word boundary there,
1762 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1763 # (marking chopped part) would be longer than given string.
1764 sub chop_str {
1765 my $str = shift;
1766 my $len = shift;
1767 my $add_len = shift || 10;
1768 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1770 # Make sure perl knows it is utf8 encoded so we don't
1771 # cut in the middle of a utf8 multibyte char.
1772 $str = to_utf8($str);
1774 # allow only $len chars, but don't cut a word if it would fit in $add_len
1775 # if it doesn't fit, cut it if it's still longer than the dots we would add
1776 # remove chopped character entities entirely
1778 # when chopping in the middle, distribute $len into left and right part
1779 # return early if chopping wouldn't make string shorter
1780 if ($where eq 'center') {
1781 return $str if ($len + 5 >= length($str)); # filler is length 5
1782 $len = int($len/2);
1783 } else {
1784 return $str if ($len + 4 >= length($str)); # filler is length 4
1787 # regexps: ending and beginning with word part up to $add_len
1788 my $endre = qr/.{$len}\w{0,$add_len}/;
1789 my $begre = qr/\w{0,$add_len}.{$len}/;
1791 if ($where eq 'left') {
1792 $str =~ m/^(.*?)($begre)$/;
1793 my ($lead, $body) = ($1, $2);
1794 if (length($lead) > 4) {
1795 $lead = " ...";
1797 return "$lead$body";
1799 } elsif ($where eq 'center') {
1800 $str =~ m/^($endre)(.*)$/;
1801 my ($left, $str) = ($1, $2);
1802 $str =~ m/^(.*?)($begre)$/;
1803 my ($mid, $right) = ($1, $2);
1804 if (length($mid) > 5) {
1805 $mid = " ... ";
1807 return "$left$mid$right";
1809 } else {
1810 $str =~ m/^($endre)(.*)$/;
1811 my $body = $1;
1812 my $tail = $2;
1813 if (length($tail) > 4) {
1814 $tail = "... ";
1816 return "$body$tail";
1820 # takes the same arguments as chop_str, but also wraps a <span> around the
1821 # result with a title attribute if it does get chopped. Additionally, the
1822 # string is HTML-escaped.
1823 sub chop_and_escape_str {
1824 my ($str) = @_;
1826 my $chopped = chop_str(@_);
1827 $str = to_utf8($str);
1828 if ($chopped eq $str) {
1829 return esc_html($chopped);
1830 } else {
1831 $str =~ s/[[:cntrl:]]/?/g;
1832 return $cgi->span({-title=>$str}, esc_html($chopped));
1836 # Highlight selected fragments of string, using given CSS class,
1837 # and escape HTML. It is assumed that fragments do not overlap.
1838 # Regions are passed as list of pairs (array references).
1840 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1841 # '<span class="mark">foo</span>bar'
1842 sub esc_html_hl_regions {
1843 my ($str, $css_class, @sel) = @_;
1844 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1845 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1846 return esc_html($str, %opts) unless @sel;
1848 my $out = '';
1849 my $pos = 0;
1851 for my $s (@sel) {
1852 my ($begin, $end) = @$s;
1854 # Don't create empty <span> elements.
1855 next if $end <= $begin;
1857 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1858 %opts);
1860 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1861 if ($begin - $pos > 0);
1862 $out .= $cgi->span({-class => $css_class}, $escaped);
1864 $pos = $end;
1866 $out .= esc_html(substr($str, $pos), %opts)
1867 if ($pos < length($str));
1869 return $out;
1872 # return positions of beginning and end of each match
1873 sub matchpos_list {
1874 my ($str, $regexp) = @_;
1875 return unless (defined $str && defined $regexp);
1877 my @matches;
1878 while ($str =~ /$regexp/g) {
1879 push @matches, [$-[0], $+[0]];
1881 return @matches;
1884 # highlight match (if any), and escape HTML
1885 sub esc_html_match_hl {
1886 my ($str, $regexp) = @_;
1887 return esc_html($str) unless defined $regexp;
1889 my @matches = matchpos_list($str, $regexp);
1890 return esc_html($str) unless @matches;
1892 return esc_html_hl_regions($str, 'match', @matches);
1896 # highlight match (if any) of shortened string, and escape HTML
1897 sub esc_html_match_hl_chopped {
1898 my ($str, $chopped, $regexp) = @_;
1899 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1901 my @matches = matchpos_list($str, $regexp);
1902 return esc_html($chopped) unless @matches;
1904 # filter matches so that we mark chopped string
1905 my $tail = "... "; # see chop_str
1906 unless ($chopped =~ s/\Q$tail\E$//) {
1907 $tail = '';
1909 my $chop_len = length($chopped);
1910 my $tail_len = length($tail);
1911 my @filtered;
1913 for my $m (@matches) {
1914 if ($m->[0] > $chop_len) {
1915 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1916 last;
1917 } elsif ($m->[1] > $chop_len) {
1918 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1919 last;
1921 push @filtered, $m;
1924 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1927 ## ----------------------------------------------------------------------
1928 ## functions returning short strings
1930 # CSS class for given age value (in seconds)
1931 sub age_class {
1932 my $age = shift;
1934 if (!defined $age) {
1935 return "noage";
1936 } elsif ($age < 60*60*2) {
1937 return "age0";
1938 } elsif ($age < 60*60*24*2) {
1939 return "age1";
1940 } else {
1941 return "age2";
1945 # convert age in seconds to "nn units ago" string
1946 sub age_string {
1947 my $age = shift;
1948 my $age_str;
1950 if ($age > 60*60*24*365*2) {
1951 $age_str = (int $age/60/60/24/365);
1952 $age_str .= " years ago";
1953 } elsif ($age > 60*60*24*(365/12)*2) {
1954 $age_str = int $age/60/60/24/(365/12);
1955 $age_str .= " months ago";
1956 } elsif ($age > 60*60*24*7*2) {
1957 $age_str = int $age/60/60/24/7;
1958 $age_str .= " weeks ago";
1959 } elsif ($age > 60*60*24*2) {
1960 $age_str = int $age/60/60/24;
1961 $age_str .= " days ago";
1962 } elsif ($age > 60*60*2) {
1963 $age_str = int $age/60/60;
1964 $age_str .= " hours ago";
1965 } elsif ($age > 60*2) {
1966 $age_str = int $age/60;
1967 $age_str .= " min ago";
1968 } elsif ($age > 2) {
1969 $age_str = int $age;
1970 $age_str .= " sec ago";
1971 } else {
1972 $age_str .= " right now";
1974 return $age_str;
1977 use constant {
1978 S_IFINVALID => 0030000,
1979 S_IFGITLINK => 0160000,
1982 # submodule/subproject, a commit object reference
1983 sub S_ISGITLINK {
1984 my $mode = shift;
1986 return (($mode & S_IFMT) == S_IFGITLINK)
1989 # convert file mode in octal to symbolic file mode string
1990 sub mode_str {
1991 my $mode = oct shift;
1993 if (S_ISGITLINK($mode)) {
1994 return 'm---------';
1995 } elsif (S_ISDIR($mode & S_IFMT)) {
1996 return 'drwxr-xr-x';
1997 } elsif (S_ISLNK($mode)) {
1998 return 'lrwxrwxrwx';
1999 } elsif (S_ISREG($mode)) {
2000 # git cares only about the executable bit
2001 if ($mode & S_IXUSR) {
2002 return '-rwxr-xr-x';
2003 } else {
2004 return '-rw-r--r--';
2006 } else {
2007 return '----------';
2011 # convert file mode in octal to file type string
2012 sub file_type {
2013 my $mode = shift;
2015 if ($mode !~ m/^[0-7]+$/) {
2016 return $mode;
2017 } else {
2018 $mode = oct $mode;
2021 if (S_ISGITLINK($mode)) {
2022 return "submodule";
2023 } elsif (S_ISDIR($mode & S_IFMT)) {
2024 return "directory";
2025 } elsif (S_ISLNK($mode)) {
2026 return "symlink";
2027 } elsif (S_ISREG($mode)) {
2028 return "file";
2029 } else {
2030 return "unknown";
2034 # convert file mode in octal to file type description string
2035 sub file_type_long {
2036 my $mode = shift;
2038 if ($mode !~ m/^[0-7]+$/) {
2039 return $mode;
2040 } else {
2041 $mode = oct $mode;
2044 if (S_ISGITLINK($mode)) {
2045 return "submodule";
2046 } elsif (S_ISDIR($mode & S_IFMT)) {
2047 return "directory";
2048 } elsif (S_ISLNK($mode)) {
2049 return "symlink";
2050 } elsif (S_ISREG($mode)) {
2051 if ($mode & S_IXUSR) {
2052 return "executable";
2053 } else {
2054 return "file";
2056 } else {
2057 return "unknown";
2062 ## ----------------------------------------------------------------------
2063 ## functions returning short HTML fragments, or transforming HTML fragments
2064 ## which don't belong to other sections
2066 # format line of commit message.
2067 sub format_log_line_html {
2068 my $line = shift;
2070 $line = esc_html($line, -nbsp=>1);
2071 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2072 $cgi->a({-href => href(action=>"object", hash=>$1),
2073 -class => "text"}, $1);
2074 }eg;
2076 return $line;
2079 # format marker of refs pointing to given object
2081 # the destination action is chosen based on object type and current context:
2082 # - for annotated tags, we choose the tag view unless it's the current view
2083 # already, in which case we go to shortlog view
2084 # - for other refs, we keep the current view if we're in history, shortlog or
2085 # log view, and select shortlog otherwise
2086 sub format_ref_marker {
2087 my ($refs, $id) = @_;
2088 my $markers = '';
2090 if (defined $refs->{$id}) {
2091 foreach my $ref (@{$refs->{$id}}) {
2092 # this code exploits the fact that non-lightweight tags are the
2093 # only indirect objects, and that they are the only objects for which
2094 # we want to use tag instead of shortlog as action
2095 my ($type, $name) = qw();
2096 my $indirect = ($ref =~ s/\^\{\}$//);
2097 # e.g. tags/v2.6.11 or heads/next
2098 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2099 $type = $1;
2100 $name = $2;
2101 } else {
2102 $type = "ref";
2103 $name = $ref;
2106 my $class = $type;
2107 $class .= " indirect" if $indirect;
2109 my $dest_action = "shortlog";
2111 if ($indirect) {
2112 $dest_action = "tag" unless $action eq "tag";
2113 } elsif ($action =~ /^(history|(short)?log)$/) {
2114 $dest_action = $action;
2117 my $dest = "";
2118 $dest .= "refs/" unless $ref =~ m!^refs/!;
2119 $dest .= $ref;
2121 my $link = $cgi->a({
2122 -href => href(
2123 action=>$dest_action,
2124 hash=>$dest
2125 )}, $name);
2127 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2128 $link . "</span>";
2132 if ($markers) {
2133 return ' <span class="refs">'. $markers . '</span>';
2134 } else {
2135 return "";
2139 # format, perhaps shortened and with markers, title line
2140 sub format_subject_html {
2141 my ($long, $short, $href, $extra) = @_;
2142 $extra = '' unless defined($extra);
2144 if (length($short) < length($long)) {
2145 $long =~ s/[[:cntrl:]]/?/g;
2146 return $cgi->a({-href => $href, -class => "list subject",
2147 -title => to_utf8($long)},
2148 esc_html($short)) . $extra;
2149 } else {
2150 return $cgi->a({-href => $href, -class => "list subject"},
2151 esc_html($long)) . $extra;
2155 # Rather than recomputing the url for an email multiple times, we cache it
2156 # after the first hit. This gives a visible benefit in views where the avatar
2157 # for the same email is used repeatedly (e.g. shortlog).
2158 # The cache is shared by all avatar engines (currently gravatar only), which
2159 # are free to use it as preferred. Since only one avatar engine is used for any
2160 # given page, there's no risk for cache conflicts.
2161 our %avatar_cache = ();
2163 # Compute the picon url for a given email, by using the picon search service over at
2164 # http://www.cs.indiana.edu/picons/search.html
2165 sub picon_url {
2166 my $email = lc shift;
2167 if (!$avatar_cache{$email}) {
2168 my ($user, $domain) = split('@', $email);
2169 $avatar_cache{$email} =
2170 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2171 "$domain/$user/" .
2172 "users+domains+unknown/up/single";
2174 return $avatar_cache{$email};
2177 # Compute the gravatar url for a given email, if it's not in the cache already.
2178 # Gravatar stores only the part of the URL before the size, since that's the
2179 # one computationally more expensive. This also allows reuse of the cache for
2180 # different sizes (for this particular engine).
2181 sub gravatar_url {
2182 my $email = lc shift;
2183 my $size = shift;
2184 $avatar_cache{$email} ||=
2185 "//www.gravatar.com/avatar/" .
2186 Digest::MD5::md5_hex($email) . "?s=";
2187 return $avatar_cache{$email} . $size;
2190 # Insert an avatar for the given $email at the given $size if the feature
2191 # is enabled.
2192 sub git_get_avatar {
2193 my ($email, %opts) = @_;
2194 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2195 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2196 $opts{-size} ||= 'default';
2197 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2198 my $url = "";
2199 if ($git_avatar eq 'gravatar') {
2200 $url = gravatar_url($email, $size);
2201 } elsif ($git_avatar eq 'picon') {
2202 $url = picon_url($email);
2204 # Other providers can be added by extending the if chain, defining $url
2205 # as needed. If no variant puts something in $url, we assume avatars
2206 # are completely disabled/unavailable.
2207 if ($url) {
2208 return $pre_white .
2209 "<img width=\"$size\" " .
2210 "class=\"avatar\" " .
2211 "src=\"".esc_url($url)."\" " .
2212 "alt=\"\" " .
2213 "/>" . $post_white;
2214 } else {
2215 return "";
2219 sub format_search_author {
2220 my ($author, $searchtype, $displaytext) = @_;
2221 my $have_search = gitweb_check_feature('search');
2223 if ($have_search) {
2224 my $performed = "";
2225 if ($searchtype eq 'author') {
2226 $performed = "authored";
2227 } elsif ($searchtype eq 'committer') {
2228 $performed = "committed";
2231 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2232 searchtext=>$author,
2233 searchtype=>$searchtype), class=>"list",
2234 title=>"Search for commits $performed by $author"},
2235 $displaytext);
2237 } else {
2238 return $displaytext;
2242 # format the author name of the given commit with the given tag
2243 # the author name is chopped and escaped according to the other
2244 # optional parameters (see chop_str).
2245 sub format_author_html {
2246 my $tag = shift;
2247 my $co = shift;
2248 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2249 return "<$tag class=\"author\">" .
2250 format_search_author($co->{'author_name'}, "author",
2251 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2252 $author) .
2253 "</$tag>";
2256 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2257 sub format_git_diff_header_line {
2258 my $line = shift;
2259 my $diffinfo = shift;
2260 my ($from, $to) = @_;
2262 if ($diffinfo->{'nparents'}) {
2263 # combined diff
2264 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2265 if ($to->{'href'}) {
2266 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2267 esc_path($to->{'file'}));
2268 } else { # file was deleted (no href)
2269 $line .= esc_path($to->{'file'});
2271 } else {
2272 # "ordinary" diff
2273 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2274 if ($from->{'href'}) {
2275 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2276 'a/' . esc_path($from->{'file'}));
2277 } else { # file was added (no href)
2278 $line .= 'a/' . esc_path($from->{'file'});
2280 $line .= ' ';
2281 if ($to->{'href'}) {
2282 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2283 'b/' . esc_path($to->{'file'}));
2284 } else { # file was deleted
2285 $line .= 'b/' . esc_path($to->{'file'});
2289 return "<div class=\"diff header\">$line</div>\n";
2292 # format extended diff header line, before patch itself
2293 sub format_extended_diff_header_line {
2294 my $line = shift;
2295 my $diffinfo = shift;
2296 my ($from, $to) = @_;
2298 # match <path>
2299 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2300 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2301 esc_path($from->{'file'}));
2303 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2304 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2305 esc_path($to->{'file'}));
2307 # match single <mode>
2308 if ($line =~ m/\s(\d{6})$/) {
2309 $line .= '<span class="info"> (' .
2310 file_type_long($1) .
2311 ')</span>';
2313 # match <hash>
2314 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2315 # can match only for combined diff
2316 $line = 'index ';
2317 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2318 if ($from->{'href'}[$i]) {
2319 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2320 -class=>"hash"},
2321 substr($diffinfo->{'from_id'}[$i],0,7));
2322 } else {
2323 $line .= '0' x 7;
2325 # separator
2326 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2328 $line .= '..';
2329 if ($to->{'href'}) {
2330 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2331 substr($diffinfo->{'to_id'},0,7));
2332 } else {
2333 $line .= '0' x 7;
2336 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2337 # can match only for ordinary diff
2338 my ($from_link, $to_link);
2339 if ($from->{'href'}) {
2340 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2341 substr($diffinfo->{'from_id'},0,7));
2342 } else {
2343 $from_link = '0' x 7;
2345 if ($to->{'href'}) {
2346 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2347 substr($diffinfo->{'to_id'},0,7));
2348 } else {
2349 $to_link = '0' x 7;
2351 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2352 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2355 return $line . "<br/>\n";
2358 # format from-file/to-file diff header
2359 sub format_diff_from_to_header {
2360 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2361 my $line;
2362 my $result = '';
2364 $line = $from_line;
2365 #assert($line =~ m/^---/) if DEBUG;
2366 # no extra formatting for "^--- /dev/null"
2367 if (! $diffinfo->{'nparents'}) {
2368 # ordinary (single parent) diff
2369 if ($line =~ m!^--- "?a/!) {
2370 if ($from->{'href'}) {
2371 $line = '--- a/' .
2372 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2373 esc_path($from->{'file'}));
2374 } else {
2375 $line = '--- a/' .
2376 esc_path($from->{'file'});
2379 $result .= qq!<div class="diff from_file">$line</div>\n!;
2381 } else {
2382 # combined diff (merge commit)
2383 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2384 if ($from->{'href'}[$i]) {
2385 $line = '--- ' .
2386 $cgi->a({-href=>href(action=>"blobdiff",
2387 hash_parent=>$diffinfo->{'from_id'}[$i],
2388 hash_parent_base=>$parents[$i],
2389 file_parent=>$from->{'file'}[$i],
2390 hash=>$diffinfo->{'to_id'},
2391 hash_base=>$hash,
2392 file_name=>$to->{'file'}),
2393 -class=>"path",
2394 -title=>"diff" . ($i+1)},
2395 $i+1) .
2396 '/' .
2397 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2398 esc_path($from->{'file'}[$i]));
2399 } else {
2400 $line = '--- /dev/null';
2402 $result .= qq!<div class="diff from_file">$line</div>\n!;
2406 $line = $to_line;
2407 #assert($line =~ m/^\+\+\+/) if DEBUG;
2408 # no extra formatting for "^+++ /dev/null"
2409 if ($line =~ m!^\+\+\+ "?b/!) {
2410 if ($to->{'href'}) {
2411 $line = '+++ b/' .
2412 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2413 esc_path($to->{'file'}));
2414 } else {
2415 $line = '+++ b/' .
2416 esc_path($to->{'file'});
2419 $result .= qq!<div class="diff to_file">$line</div>\n!;
2421 return $result;
2424 # create note for patch simplified by combined diff
2425 sub format_diff_cc_simplified {
2426 my ($diffinfo, @parents) = @_;
2427 my $result = '';
2429 $result .= "<div class=\"diff header\">" .
2430 "diff --cc ";
2431 if (!is_deleted($diffinfo)) {
2432 $result .= $cgi->a({-href => href(action=>"blob",
2433 hash_base=>$hash,
2434 hash=>$diffinfo->{'to_id'},
2435 file_name=>$diffinfo->{'to_file'}),
2436 -class => "path"},
2437 esc_path($diffinfo->{'to_file'}));
2438 } else {
2439 $result .= esc_path($diffinfo->{'to_file'});
2441 $result .= "</div>\n" . # class="diff header"
2442 "<div class=\"diff nodifferences\">" .
2443 "Simple merge" .
2444 "</div>\n"; # class="diff nodifferences"
2446 return $result;
2449 sub diff_line_class {
2450 my ($line, $from, $to) = @_;
2452 # ordinary diff
2453 my $num_sign = 1;
2454 # combined diff
2455 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2456 $num_sign = scalar @{$from->{'href'}};
2459 my @diff_line_classifier = (
2460 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2461 { regexp => qr/^\\/, class => "incomplete" },
2462 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2463 # classifier for context must come before classifier add/rem,
2464 # or we would have to use more complicated regexp, for example
2465 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2466 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2467 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2469 for my $clsfy (@diff_line_classifier) {
2470 return $clsfy->{'class'}
2471 if ($line =~ $clsfy->{'regexp'});
2474 # fallback
2475 return "";
2478 # assumes that $from and $to are defined and correctly filled,
2479 # and that $line holds a line of chunk header for unified diff
2480 sub format_unidiff_chunk_header {
2481 my ($line, $from, $to) = @_;
2483 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2484 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2486 $from_lines = 0 unless defined $from_lines;
2487 $to_lines = 0 unless defined $to_lines;
2489 if ($from->{'href'}) {
2490 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2491 -class=>"list"}, $from_text);
2493 if ($to->{'href'}) {
2494 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2495 -class=>"list"}, $to_text);
2497 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2498 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2499 return $line;
2502 # assumes that $from and $to are defined and correctly filled,
2503 # and that $line holds a line of chunk header for combined diff
2504 sub format_cc_diff_chunk_header {
2505 my ($line, $from, $to) = @_;
2507 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2508 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2510 @from_text = split(' ', $ranges);
2511 for (my $i = 0; $i < @from_text; ++$i) {
2512 ($from_start[$i], $from_nlines[$i]) =
2513 (split(',', substr($from_text[$i], 1)), 0);
2516 $to_text = pop @from_text;
2517 $to_start = pop @from_start;
2518 $to_nlines = pop @from_nlines;
2520 $line = "<span class=\"chunk_info\">$prefix ";
2521 for (my $i = 0; $i < @from_text; ++$i) {
2522 if ($from->{'href'}[$i]) {
2523 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2524 -class=>"list"}, $from_text[$i]);
2525 } else {
2526 $line .= $from_text[$i];
2528 $line .= " ";
2530 if ($to->{'href'}) {
2531 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2532 -class=>"list"}, $to_text);
2533 } else {
2534 $line .= $to_text;
2536 $line .= " $prefix</span>" .
2537 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2538 return $line;
2541 # process patch (diff) line (not to be used for diff headers),
2542 # returning HTML-formatted (but not wrapped) line.
2543 # If the line is passed as a reference, it is treated as HTML and not
2544 # esc_html()'ed.
2545 sub format_diff_line {
2546 my ($line, $diff_class, $from, $to) = @_;
2548 if (ref($line)) {
2549 $line = $$line;
2550 } else {
2551 chomp $line;
2552 $line = untabify($line);
2554 if ($from && $to && $line =~ m/^\@{2} /) {
2555 $line = format_unidiff_chunk_header($line, $from, $to);
2556 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2557 $line = format_cc_diff_chunk_header($line, $from, $to);
2558 } else {
2559 $line = esc_html($line, -nbsp=>1);
2563 my $diff_classes = "diff";
2564 $diff_classes .= " $diff_class" if ($diff_class);
2565 $line = "<div class=\"$diff_classes\">$line</div>\n";
2567 return $line;
2570 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2571 # linked. Pass the hash of the tree/commit to snapshot.
2572 sub format_snapshot_links {
2573 my ($hash) = @_;
2574 my $num_fmts = @snapshot_fmts;
2575 if ($num_fmts > 1) {
2576 # A parenthesized list of links bearing format names.
2577 # e.g. "snapshot (_tar.gz_ _zip_)"
2578 return "snapshot (" . join(' ', map
2579 $cgi->a({
2580 -href => href(
2581 action=>"snapshot",
2582 hash=>$hash,
2583 snapshot_format=>$_
2585 }, $known_snapshot_formats{$_}{'display'})
2586 , @snapshot_fmts) . ")";
2587 } elsif ($num_fmts == 1) {
2588 # A single "snapshot" link whose tooltip bears the format name.
2589 # i.e. "_snapshot_"
2590 my ($fmt) = @snapshot_fmts;
2591 return
2592 $cgi->a({
2593 -href => href(
2594 action=>"snapshot",
2595 hash=>$hash,
2596 snapshot_format=>$fmt
2598 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2599 }, "snapshot");
2600 } else { # $num_fmts == 0
2601 return undef;
2605 ## ......................................................................
2606 ## functions returning values to be passed, perhaps after some
2607 ## transformation, to other functions; e.g. returning arguments to href()
2609 # returns hash to be passed to href to generate gitweb URL
2610 # in -title key it returns description of link
2611 sub get_feed_info {
2612 my $format = shift || 'Atom';
2613 my %res = (action => lc($format));
2614 my $matched_ref = 0;
2616 # feed links are possible only for project views
2617 return unless (defined $project);
2618 # some views should link to OPML, or to generic project feed,
2619 # or don't have specific feed yet (so they should use generic)
2620 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2622 my $branch = undef;
2623 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2624 # (fullname) to differentiate from tag links; this also makes
2625 # possible to detect branch links
2626 for my $ref (get_branch_refs()) {
2627 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2628 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2629 $branch = $1;
2630 $matched_ref = $ref;
2631 last;
2634 # find log type for feed description (title)
2635 my $type = 'log';
2636 if (defined $file_name) {
2637 $type = "history of $file_name";
2638 $type .= "/" if ($action eq 'tree');
2639 $type .= " on '$branch'" if (defined $branch);
2640 } else {
2641 $type = "log of $branch" if (defined $branch);
2644 $res{-title} = $type;
2645 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2646 $res{'file_name'} = $file_name;
2648 return %res;
2651 ## ----------------------------------------------------------------------
2652 ## git utility subroutines, invoking git commands
2654 # returns path to the core git executable and the --git-dir parameter as list
2655 sub git_cmd {
2656 $number_of_git_cmds++;
2657 return $GIT, '--git-dir='.$git_dir;
2660 # quote the given arguments for passing them to the shell
2661 # quote_command("command", "arg 1", "arg with ' and ! characters")
2662 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2663 # Try to avoid using this function wherever possible.
2664 sub quote_command {
2665 return join(' ',
2666 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2669 # get HEAD ref of given project as hash
2670 sub git_get_head_hash {
2671 return git_get_full_hash(shift, 'HEAD');
2674 sub git_get_full_hash {
2675 return git_get_hash(@_);
2678 sub git_get_short_hash {
2679 return git_get_hash(@_, '--short=7');
2682 sub git_get_hash {
2683 my ($project, $hash, @options) = @_;
2684 my $o_git_dir = $git_dir;
2685 my $retval = undef;
2686 $git_dir = "$projectroot/$project";
2687 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2688 '--verify', '-q', @options, $hash) {
2689 $retval = <$fd>;
2690 chomp $retval if defined $retval;
2691 close $fd;
2693 if (defined $o_git_dir) {
2694 $git_dir = $o_git_dir;
2696 return $retval;
2699 # get type of given object
2700 sub git_get_type {
2701 my $hash = shift;
2703 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2704 my $type = <$fd>;
2705 close $fd or return;
2706 chomp $type;
2707 return $type;
2710 # repository configuration
2711 our $config_file = '';
2712 our %config;
2714 # store multiple values for single key as anonymous array reference
2715 # single values stored directly in the hash, not as [ <value> ]
2716 sub hash_set_multi {
2717 my ($hash, $key, $value) = @_;
2719 if (!exists $hash->{$key}) {
2720 $hash->{$key} = $value;
2721 } elsif (!ref $hash->{$key}) {
2722 $hash->{$key} = [ $hash->{$key}, $value ];
2723 } else {
2724 push @{$hash->{$key}}, $value;
2728 # return hash of git project configuration
2729 # optionally limited to some section, e.g. 'gitweb'
2730 sub git_parse_project_config {
2731 my $section_regexp = shift;
2732 my %config;
2734 local $/ = "\0";
2736 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2737 or return;
2739 while (my $keyval = <$fh>) {
2740 chomp $keyval;
2741 my ($key, $value) = split(/\n/, $keyval, 2);
2743 hash_set_multi(\%config, $key, $value)
2744 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2746 close $fh;
2748 return %config;
2751 # convert config value to boolean: 'true' or 'false'
2752 # no value, number > 0, 'true' and 'yes' values are true
2753 # rest of values are treated as false (never as error)
2754 sub config_to_bool {
2755 my $val = shift;
2757 return 1 if !defined $val; # section.key
2759 # strip leading and trailing whitespace
2760 $val =~ s/^\s+//;
2761 $val =~ s/\s+$//;
2763 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2764 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2767 # convert config value to simple decimal number
2768 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2769 # to be multiplied by 1024, 1048576, or 1073741824
2770 sub config_to_int {
2771 my $val = shift;
2773 # strip leading and trailing whitespace
2774 $val =~ s/^\s+//;
2775 $val =~ s/\s+$//;
2777 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2778 $unit = lc($unit);
2779 # unknown unit is treated as 1
2780 return $num * ($unit eq 'g' ? 1073741824 :
2781 $unit eq 'm' ? 1048576 :
2782 $unit eq 'k' ? 1024 : 1);
2784 return $val;
2787 # convert config value to array reference, if needed
2788 sub config_to_multi {
2789 my $val = shift;
2791 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2794 sub git_get_project_config {
2795 my ($key, $type) = @_;
2797 return unless defined $git_dir;
2799 # key sanity check
2800 return unless ($key);
2801 # only subsection, if exists, is case sensitive,
2802 # and not lowercased by 'git config -z -l'
2803 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2804 $lo =~ s/_//g;
2805 $key = join(".", lc($hi), $mi, lc($lo));
2806 return if ($lo =~ /\W/ || $hi =~ /\W/);
2807 } else {
2808 $key = lc($key);
2809 $key =~ s/_//g;
2810 return if ($key =~ /\W/);
2812 $key =~ s/^gitweb\.//;
2814 # type sanity check
2815 if (defined $type) {
2816 $type =~ s/^--//;
2817 $type = undef
2818 unless ($type eq 'bool' || $type eq 'int');
2821 # get config
2822 if (!defined $config_file ||
2823 $config_file ne "$git_dir/config") {
2824 %config = git_parse_project_config('gitweb');
2825 $config_file = "$git_dir/config";
2828 # check if config variable (key) exists
2829 return unless exists $config{"gitweb.$key"};
2831 # ensure given type
2832 if (!defined $type) {
2833 return $config{"gitweb.$key"};
2834 } elsif ($type eq 'bool') {
2835 # backward compatibility: 'git config --bool' returns true/false
2836 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2837 } elsif ($type eq 'int') {
2838 return config_to_int($config{"gitweb.$key"});
2840 return $config{"gitweb.$key"};
2843 # get hash of given path at given ref
2844 sub git_get_hash_by_path {
2845 my $base = shift;
2846 my $path = shift || return undef;
2847 my $type = shift;
2849 $path =~ s,/+$,,;
2851 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2852 or die_error(500, "Open git-ls-tree failed");
2853 my $line = <$fd>;
2854 close $fd or return undef;
2856 if (!defined $line) {
2857 # there is no tree or hash given by $path at $base
2858 return undef;
2861 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2862 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2863 if (defined $type && $type ne $2) {
2864 # type doesn't match
2865 return undef;
2867 return $3;
2870 # get path of entry with given hash at given tree-ish (ref)
2871 # used to get 'from' filename for combined diff (merge commit) for renames
2872 sub git_get_path_by_hash {
2873 my $base = shift || return;
2874 my $hash = shift || return;
2876 local $/ = "\0";
2878 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2879 or return undef;
2880 while (my $line = <$fd>) {
2881 chomp $line;
2883 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2884 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2885 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2886 close $fd;
2887 return $1;
2890 close $fd;
2891 return undef;
2894 ## ......................................................................
2895 ## git utility functions, directly accessing git repository
2897 # get the value of config variable either from file named as the variable
2898 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2899 # configuration variable in the repository config file.
2900 sub git_get_file_or_project_config {
2901 my ($path, $name) = @_;
2903 $git_dir = "$projectroot/$path";
2904 open my $fd, '<', "$git_dir/$name"
2905 or return git_get_project_config($name);
2906 my $conf = <$fd>;
2907 close $fd;
2908 if (defined $conf) {
2909 chomp $conf;
2911 return $conf;
2914 sub git_get_project_description {
2915 my $path = shift;
2916 return git_get_file_or_project_config($path, 'description');
2919 sub git_get_project_category {
2920 my $path = shift;
2921 return git_get_file_or_project_config($path, 'category');
2925 # supported formats:
2926 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2927 # - if its contents is a number, use it as tag weight,
2928 # - otherwise add a tag with weight 1
2929 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2930 # the same value multiple times increases tag weight
2931 # * `gitweb.ctag' multi-valued repo config variable
2932 sub git_get_project_ctags {
2933 my $project = shift;
2934 my $ctags = {};
2936 $git_dir = "$projectroot/$project";
2937 if (opendir my $dh, "$git_dir/ctags") {
2938 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2939 foreach my $tagfile (@files) {
2940 open my $ct, '<', $tagfile
2941 or next;
2942 my $val = <$ct>;
2943 chomp $val if $val;
2944 close $ct;
2946 (my $ctag = $tagfile) =~ s#.*/##;
2947 if ($val =~ /^\d+$/) {
2948 $ctags->{$ctag} = $val;
2949 } else {
2950 $ctags->{$ctag} = 1;
2953 closedir $dh;
2955 } elsif (open my $fh, '<', "$git_dir/ctags") {
2956 while (my $line = <$fh>) {
2957 chomp $line;
2958 $ctags->{$line}++ if $line;
2960 close $fh;
2962 } else {
2963 my $taglist = config_to_multi(git_get_project_config('ctag'));
2964 foreach my $tag (@$taglist) {
2965 $ctags->{$tag}++;
2969 return $ctags;
2972 # return hash, where keys are content tags ('ctags'),
2973 # and values are sum of weights of given tag in every project
2974 sub git_gather_all_ctags {
2975 my $projects = shift;
2976 my $ctags = {};
2978 foreach my $p (@$projects) {
2979 foreach my $ct (keys %{$p->{'ctags'}}) {
2980 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2984 return $ctags;
2987 sub git_populate_project_tagcloud {
2988 my ($ctags, $action) = @_;
2990 # First, merge different-cased tags; tags vote on casing
2991 my %ctags_lc;
2992 foreach (keys %$ctags) {
2993 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2994 if (not $ctags_lc{lc $_}->{topcount}
2995 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2996 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2997 $ctags_lc{lc $_}->{topname} = $_;
3001 my $cloud;
3002 my $matched = $input_params{'ctag_filter'};
3003 if (eval { require HTML::TagCloud; 1; }) {
3004 $cloud = HTML::TagCloud->new;
3005 foreach my $ctag (sort keys %ctags_lc) {
3006 # Pad the title with spaces so that the cloud looks
3007 # less crammed.
3008 my $title = esc_html($ctags_lc{$ctag}->{topname});
3009 $title =~ s/ /&nbsp;/g;
3010 $title =~ s/^/&nbsp;/g;
3011 $title =~ s/$/&nbsp;/g;
3012 if (defined $matched && $matched eq $ctag) {
3013 $title = qq(<span class="match">$title</span>);
3015 $cloud->add($title, href(-replay=>1, action=>$action, ctag_filter=>$ctag),
3016 $ctags_lc{$ctag}->{count});
3018 } else {
3019 $cloud = {};
3020 foreach my $ctag (keys %ctags_lc) {
3021 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3022 if (defined $matched && $matched eq $ctag) {
3023 $title = qq(<span class="match">$title</span>);
3025 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3026 $cloud->{$ctag}{ctag} =
3027 $cgi->a({-href=>href(-replay=>1, action=>$action, ctag_filter=>$ctag)}, $title);
3030 return $cloud;
3033 sub git_show_project_tagcloud {
3034 my ($cloud, $count) = @_;
3035 if (ref $cloud eq 'HTML::TagCloud') {
3036 return $cloud->html_and_css($count);
3037 } else {
3038 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3039 return
3040 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3041 join (', ', map {
3042 $cloud->{$_}->{'ctag'}
3043 } splice(@tags, 0, $count)) .
3044 '</div>';
3048 sub git_get_project_url_list {
3049 my $path = shift;
3051 $git_dir = "$projectroot/$path";
3052 open my $fd, '<', "$git_dir/cloneurl"
3053 or return wantarray ?
3054 @{ config_to_multi(git_get_project_config('url')) } :
3055 config_to_multi(git_get_project_config('url'));
3056 my @git_project_url_list = map { chomp; $_ } <$fd>;
3057 close $fd;
3059 return wantarray ? @git_project_url_list : \@git_project_url_list;
3062 sub git_get_projects_list {
3063 my $filter = shift || '';
3064 my $paranoid = shift;
3065 my @list;
3067 if (-d $projects_list) {
3068 # search in directory
3069 my $dir = $projects_list;
3070 # remove the trailing "/"
3071 $dir =~ s!/+$!!;
3072 my $pfxlen = length("$dir");
3073 my $pfxdepth = ($dir =~ tr!/!!);
3074 # when filtering, search only given subdirectory
3075 if ($filter && !$paranoid) {
3076 $dir .= "/$filter";
3077 $dir =~ s!/+$!!;
3080 File::Find::find({
3081 follow_fast => 1, # follow symbolic links
3082 follow_skip => 2, # ignore duplicates
3083 dangling_symlinks => 0, # ignore dangling symlinks, silently
3084 wanted => sub {
3085 # global variables
3086 our $project_maxdepth;
3087 our $projectroot;
3088 # skip project-list toplevel, if we get it.
3089 return if (m!^[/.]$!);
3090 # only directories can be git repositories
3091 return unless (-d $_);
3092 # don't traverse too deep (Find is super slow on os x)
3093 # $project_maxdepth excludes depth of $projectroot
3094 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3095 $File::Find::prune = 1;
3096 return;
3099 my $path = substr($File::Find::name, $pfxlen + 1);
3100 # paranoidly only filter here
3101 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3102 next;
3104 # we check related file in $projectroot
3105 if (check_export_ok("$projectroot/$path")) {
3106 push @list, { path => $path };
3107 $File::Find::prune = 1;
3110 }, "$dir");
3112 } elsif (-f $projects_list) {
3113 # read from file(url-encoded):
3114 # 'git%2Fgit.git Linus+Torvalds'
3115 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3116 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3117 open my $fd, '<', $projects_list or return;
3118 PROJECT:
3119 while (my $line = <$fd>) {
3120 chomp $line;
3121 my ($path, $owner) = split ' ', $line;
3122 $path = unescape($path);
3123 $owner = unescape($owner);
3124 if (!defined $path) {
3125 next;
3127 # if $filter is rpovided, check if $path begins with $filter
3128 if ($filter && $path !~ m!^\Q$filter\E/!) {
3129 next;
3131 if (check_export_ok("$projectroot/$path")) {
3132 my $pr = {
3133 path => $path
3135 if ($owner) {
3136 $pr->{'owner'} = to_utf8($owner);
3138 push @list, $pr;
3141 close $fd;
3143 return @list;
3146 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3147 # as side effects it sets 'forks' field to list of forks for forked projects
3148 sub filter_forks_from_projects_list {
3149 my $projects = shift;
3151 my %trie; # prefix tree of directories (path components)
3152 # generate trie out of those directories that might contain forks
3153 foreach my $pr (@$projects) {
3154 my $path = $pr->{'path'};
3155 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3156 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3157 next unless ($path); # skip '.git' repository: tests, git-instaweb
3158 next unless (-d "$projectroot/$path"); # containing directory exists
3159 $pr->{'forks'} = []; # there can be 0 or more forks of project
3161 # add to trie
3162 my @dirs = split('/', $path);
3163 # walk the trie, until either runs out of components or out of trie
3164 my $ref = \%trie;
3165 while (scalar @dirs &&
3166 exists($ref->{$dirs[0]})) {
3167 $ref = $ref->{shift @dirs};
3169 # create rest of trie structure from rest of components
3170 foreach my $dir (@dirs) {
3171 $ref = $ref->{$dir} = {};
3173 # create end marker, store $pr as a data
3174 $ref->{''} = $pr if (!exists $ref->{''});
3177 # filter out forks, by finding shortest prefix match for paths
3178 my @filtered;
3179 PROJECT:
3180 foreach my $pr (@$projects) {
3181 # trie lookup
3182 my $ref = \%trie;
3183 DIR:
3184 foreach my $dir (split('/', $pr->{'path'})) {
3185 if (exists $ref->{''}) {
3186 # found [shortest] prefix, is a fork - skip it
3187 push @{$ref->{''}{'forks'}}, $pr;
3188 next PROJECT;
3190 if (!exists $ref->{$dir}) {
3191 # not in trie, cannot have prefix, not a fork
3192 push @filtered, $pr;
3193 next PROJECT;
3195 # If the dir is there, we just walk one step down the trie.
3196 $ref = $ref->{$dir};
3198 # we ran out of trie
3199 # (shouldn't happen: it's either no match, or end marker)
3200 push @filtered, $pr;
3203 return @filtered;
3206 # note: fill_project_list_info must be run first,
3207 # for 'descr_long' and 'ctags' to be filled
3208 sub search_projects_list {
3209 my ($projlist, %opts) = @_;
3210 my $tagfilter = $opts{'tagfilter'};
3211 my $search_re = $opts{'search_regexp'};
3213 return @$projlist
3214 unless ($tagfilter || $search_re);
3216 # searching projects require filling to be run before it;
3217 fill_project_list_info($projlist,
3218 $tagfilter ? 'ctags' : (),
3219 $search_re ? ('path', 'descr') : ());
3220 my @projects;
3221 PROJECT:
3222 foreach my $pr (@$projlist) {
3224 if ($tagfilter) {
3225 next unless ref($pr->{'ctags'}) eq 'HASH';
3226 next unless
3227 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3230 if ($search_re) {
3231 next unless
3232 $pr->{'path'} =~ /$search_re/ ||
3233 $pr->{'descr_long'} =~ /$search_re/;
3236 push @projects, $pr;
3239 return @projects;
3242 our $gitweb_project_owner = undef;
3243 sub git_get_project_list_from_file {
3245 return if (defined $gitweb_project_owner);
3247 $gitweb_project_owner = {};
3248 # read from file (url-encoded):
3249 # 'git%2Fgit.git Linus+Torvalds'
3250 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3251 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3252 if (-f $projects_list) {
3253 open(my $fd, '<', $projects_list);
3254 while (my $line = <$fd>) {
3255 chomp $line;
3256 my ($pr, $ow) = split ' ', $line;
3257 $pr = unescape($pr);
3258 $ow = unescape($ow);
3259 $gitweb_project_owner->{$pr} = to_utf8($ow);
3261 close $fd;
3265 sub git_get_project_owner {
3266 my $project = shift;
3267 my $owner;
3269 return undef unless $project;
3270 $git_dir = "$projectroot/$project";
3272 if (!defined $gitweb_project_owner) {
3273 git_get_project_list_from_file();
3276 if (exists $gitweb_project_owner->{$project}) {
3277 $owner = $gitweb_project_owner->{$project};
3279 if (!defined $owner){
3280 $owner = git_get_project_config('owner');
3282 if (!defined $owner) {
3283 $owner = get_file_owner("$git_dir");
3286 return $owner;
3289 sub git_get_last_activity {
3290 my ($path) = @_;
3291 my $fd;
3293 $git_dir = "$projectroot/$path";
3294 open($fd, "-|", git_cmd(), 'for-each-ref',
3295 '--format=%(committer)',
3296 '--sort=-committerdate',
3297 '--count=1',
3298 map { "refs/$_" } get_branch_refs ()) or return;
3299 my $most_recent = <$fd>;
3300 close $fd or return;
3301 if (defined $most_recent &&
3302 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3303 my $timestamp = $1;
3304 my $age = time - $timestamp;
3305 return ($age, age_string($age));
3307 return (undef, undef);
3310 # Implementation note: when a single remote is wanted, we cannot use 'git
3311 # remote show -n' because that command always work (assuming it's a remote URL
3312 # if it's not defined), and we cannot use 'git remote show' because that would
3313 # try to make a network roundtrip. So the only way to find if that particular
3314 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3315 # and when we find what we want.
3316 sub git_get_remotes_list {
3317 my $wanted = shift;
3318 my %remotes = ();
3320 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3321 return unless $fd;
3322 while (my $remote = <$fd>) {
3323 chomp $remote;
3324 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3325 next if $wanted and not $remote eq $wanted;
3326 my ($url, $key) = ($1, $2);
3328 $remotes{$remote} ||= { 'heads' => () };
3329 $remotes{$remote}{$key} = $url;
3331 close $fd or return;
3332 return wantarray ? %remotes : \%remotes;
3335 # Takes a hash of remotes as first parameter and fills it by adding the
3336 # available remote heads for each of the indicated remotes.
3337 sub fill_remote_heads {
3338 my $remotes = shift;
3339 my @heads = map { "remotes/$_" } keys %$remotes;
3340 my @remoteheads = git_get_heads_list(undef, @heads);
3341 foreach my $remote (keys %$remotes) {
3342 $remotes->{$remote}{'heads'} = [ grep {
3343 $_->{'name'} =~ s!^$remote/!!
3344 } @remoteheads ];
3348 sub git_get_references {
3349 my $type = shift || "";
3350 my %refs;
3351 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3352 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3353 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3354 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3355 or return;
3357 while (my $line = <$fd>) {
3358 chomp $line;
3359 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3360 if (defined $refs{$1}) {
3361 push @{$refs{$1}}, $2;
3362 } else {
3363 $refs{$1} = [ $2 ];
3367 close $fd or return;
3368 return \%refs;
3371 sub git_get_rev_name_tags {
3372 my $hash = shift || return undef;
3374 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3375 or return;
3376 my $name_rev = <$fd>;
3377 close $fd;
3379 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3380 return $1;
3381 } else {
3382 # catches also '$hash undefined' output
3383 return undef;
3387 ## ----------------------------------------------------------------------
3388 ## parse to hash functions
3390 sub parse_date {
3391 my $epoch = shift;
3392 my $tz = shift || "-0000";
3394 my %date;
3395 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3396 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3397 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3398 $date{'hour'} = $hour;
3399 $date{'minute'} = $min;
3400 $date{'mday'} = $mday;
3401 $date{'day'} = $days[$wday];
3402 $date{'month'} = $months[$mon];
3403 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3404 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3405 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3406 $mday, $months[$mon], $hour ,$min;
3407 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3408 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3410 my ($tz_sign, $tz_hour, $tz_min) =
3411 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3412 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3413 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3414 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3415 $date{'hour_local'} = $hour;
3416 $date{'minute_local'} = $min;
3417 $date{'tz_local'} = $tz;
3418 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3419 1900+$year, $mon+1, $mday,
3420 $hour, $min, $sec, $tz);
3421 return %date;
3424 sub parse_tag {
3425 my $tag_id = shift;
3426 my %tag;
3427 my @comment;
3429 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3430 $tag{'id'} = $tag_id;
3431 while (my $line = <$fd>) {
3432 chomp $line;
3433 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3434 $tag{'object'} = $1;
3435 } elsif ($line =~ m/^type (.+)$/) {
3436 $tag{'type'} = $1;
3437 } elsif ($line =~ m/^tag (.+)$/) {
3438 $tag{'name'} = $1;
3439 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3440 $tag{'author'} = $1;
3441 $tag{'author_epoch'} = $2;
3442 $tag{'author_tz'} = $3;
3443 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3444 $tag{'author_name'} = $1;
3445 $tag{'author_email'} = $2;
3446 } else {
3447 $tag{'author_name'} = $tag{'author'};
3449 } elsif ($line =~ m/--BEGIN/) {
3450 push @comment, $line;
3451 last;
3452 } elsif ($line eq "") {
3453 last;
3456 push @comment, <$fd>;
3457 $tag{'comment'} = \@comment;
3458 close $fd or return;
3459 if (!defined $tag{'name'}) {
3460 return
3462 return %tag
3465 sub parse_commit_text {
3466 my ($commit_text, $withparents) = @_;
3467 my @commit_lines = split '\n', $commit_text;
3468 my %co;
3470 pop @commit_lines; # Remove '\0'
3472 if (! @commit_lines) {
3473 return;
3476 my $header = shift @commit_lines;
3477 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3478 return;
3480 ($co{'id'}, my @parents) = split ' ', $header;
3481 while (my $line = shift @commit_lines) {
3482 last if $line eq "\n";
3483 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3484 $co{'tree'} = $1;
3485 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3486 push @parents, $1;
3487 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3488 $co{'author'} = to_utf8($1);
3489 $co{'author_epoch'} = $2;
3490 $co{'author_tz'} = $3;
3491 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3492 $co{'author_name'} = $1;
3493 $co{'author_email'} = $2;
3494 } else {
3495 $co{'author_name'} = $co{'author'};
3497 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3498 $co{'committer'} = to_utf8($1);
3499 $co{'committer_epoch'} = $2;
3500 $co{'committer_tz'} = $3;
3501 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3502 $co{'committer_name'} = $1;
3503 $co{'committer_email'} = $2;
3504 } else {
3505 $co{'committer_name'} = $co{'committer'};
3509 if (!defined $co{'tree'}) {
3510 return;
3512 $co{'parents'} = \@parents;
3513 $co{'parent'} = $parents[0];
3515 foreach my $title (@commit_lines) {
3516 $title =~ s/^ //;
3517 if ($title ne "") {
3518 $co{'title'} = chop_str($title, 80, 5);
3519 # remove leading stuff of merges to make the interesting part visible
3520 if (length($title) > 50) {
3521 $title =~ s/^Automatic //;
3522 $title =~ s/^merge (of|with) /Merge ... /i;
3523 if (length($title) > 50) {
3524 $title =~ s/(http|rsync):\/\///;
3526 if (length($title) > 50) {
3527 $title =~ s/(master|www|rsync)\.//;
3529 if (length($title) > 50) {
3530 $title =~ s/kernel.org:?//;
3532 if (length($title) > 50) {
3533 $title =~ s/\/pub\/scm//;
3536 $co{'title_short'} = chop_str($title, 50, 5);
3537 last;
3540 if (! defined $co{'title'} || $co{'title'} eq "") {
3541 $co{'title'} = $co{'title_short'} = '(no commit message)';
3543 # remove added spaces
3544 foreach my $line (@commit_lines) {
3545 $line =~ s/^ //;
3547 $co{'comment'} = \@commit_lines;
3549 my $age = time - $co{'committer_epoch'};
3550 $co{'age'} = $age;
3551 $co{'age_string'} = age_string($age);
3552 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3553 if ($age > 60*60*24*7*2) {
3554 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3555 $co{'age_string_age'} = $co{'age_string'};
3556 } else {
3557 $co{'age_string_date'} = $co{'age_string'};
3558 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3560 return %co;
3563 sub parse_commit {
3564 my ($commit_id) = @_;
3565 my %co;
3567 local $/ = "\0";
3569 open my $fd, "-|", git_cmd(), "rev-list",
3570 "--parents",
3571 "--header",
3572 "--max-count=1",
3573 $commit_id,
3574 "--",
3575 or die_error(500, "Open git-rev-list failed");
3576 %co = parse_commit_text(<$fd>, 1);
3577 close $fd;
3579 return %co;
3582 sub parse_commits {
3583 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3584 my @cos;
3586 $maxcount ||= 1;
3587 $skip ||= 0;
3589 local $/ = "\0";
3591 open my $fd, "-|", git_cmd(), "rev-list",
3592 "--header",
3593 @args,
3594 ("--max-count=" . $maxcount),
3595 ("--skip=" . $skip),
3596 @extra_options,
3597 $commit_id,
3598 "--",
3599 ($filename ? ($filename) : ())
3600 or die_error(500, "Open git-rev-list failed");
3601 while (my $line = <$fd>) {
3602 my %co = parse_commit_text($line);
3603 push @cos, \%co;
3605 close $fd;
3607 return wantarray ? @cos : \@cos;
3610 # parse line of git-diff-tree "raw" output
3611 sub parse_difftree_raw_line {
3612 my $line = shift;
3613 my %res;
3615 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3616 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3617 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3618 $res{'from_mode'} = $1;
3619 $res{'to_mode'} = $2;
3620 $res{'from_id'} = $3;
3621 $res{'to_id'} = $4;
3622 $res{'status'} = $5;
3623 $res{'similarity'} = $6;
3624 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3625 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3626 } else {
3627 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3630 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3631 # combined diff (for merge commit)
3632 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3633 $res{'nparents'} = length($1);
3634 $res{'from_mode'} = [ split(' ', $2) ];
3635 $res{'to_mode'} = pop @{$res{'from_mode'}};
3636 $res{'from_id'} = [ split(' ', $3) ];
3637 $res{'to_id'} = pop @{$res{'from_id'}};
3638 $res{'status'} = [ split('', $4) ];
3639 $res{'to_file'} = unquote($5);
3641 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3642 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3643 $res{'commit'} = $1;
3646 return wantarray ? %res : \%res;
3649 # wrapper: return parsed line of git-diff-tree "raw" output
3650 # (the argument might be raw line, or parsed info)
3651 sub parsed_difftree_line {
3652 my $line_or_ref = shift;
3654 if (ref($line_or_ref) eq "HASH") {
3655 # pre-parsed (or generated by hand)
3656 return $line_or_ref;
3657 } else {
3658 return parse_difftree_raw_line($line_or_ref);
3662 # parse line of git-ls-tree output
3663 sub parse_ls_tree_line {
3664 my $line = shift;
3665 my %opts = @_;
3666 my %res;
3668 if ($opts{'-l'}) {
3669 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3670 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3672 $res{'mode'} = $1;
3673 $res{'type'} = $2;
3674 $res{'hash'} = $3;
3675 $res{'size'} = $4;
3676 if ($opts{'-z'}) {
3677 $res{'name'} = $5;
3678 } else {
3679 $res{'name'} = unquote($5);
3681 } else {
3682 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3683 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3685 $res{'mode'} = $1;
3686 $res{'type'} = $2;
3687 $res{'hash'} = $3;
3688 if ($opts{'-z'}) {
3689 $res{'name'} = $4;
3690 } else {
3691 $res{'name'} = unquote($4);
3695 return wantarray ? %res : \%res;
3698 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3699 sub parse_from_to_diffinfo {
3700 my ($diffinfo, $from, $to, @parents) = @_;
3702 if ($diffinfo->{'nparents'}) {
3703 # combined diff
3704 $from->{'file'} = [];
3705 $from->{'href'} = [];
3706 fill_from_file_info($diffinfo, @parents)
3707 unless exists $diffinfo->{'from_file'};
3708 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3709 $from->{'file'}[$i] =
3710 defined $diffinfo->{'from_file'}[$i] ?
3711 $diffinfo->{'from_file'}[$i] :
3712 $diffinfo->{'to_file'};
3713 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3714 $from->{'href'}[$i] = href(action=>"blob",
3715 hash_base=>$parents[$i],
3716 hash=>$diffinfo->{'from_id'}[$i],
3717 file_name=>$from->{'file'}[$i]);
3718 } else {
3719 $from->{'href'}[$i] = undef;
3722 } else {
3723 # ordinary (not combined) diff
3724 $from->{'file'} = $diffinfo->{'from_file'};
3725 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3726 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3727 hash=>$diffinfo->{'from_id'},
3728 file_name=>$from->{'file'});
3729 } else {
3730 delete $from->{'href'};
3734 $to->{'file'} = $diffinfo->{'to_file'};
3735 if (!is_deleted($diffinfo)) { # file exists in result
3736 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3737 hash=>$diffinfo->{'to_id'},
3738 file_name=>$to->{'file'});
3739 } else {
3740 delete $to->{'href'};
3744 ## ......................................................................
3745 ## parse to array of hashes functions
3747 sub git_get_heads_list {
3748 my ($limit, @classes) = @_;
3749 @classes = get_branch_refs() unless @classes;
3750 my @patterns = map { "refs/$_" } @classes;
3751 my @headslist;
3753 open my $fd, '-|', git_cmd(), 'for-each-ref',
3754 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3755 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3756 @patterns
3757 or return;
3758 while (my $line = <$fd>) {
3759 my %ref_item;
3761 chomp $line;
3762 my ($refinfo, $committerinfo) = split(/\0/, $line);
3763 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3764 my ($committer, $epoch, $tz) =
3765 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3766 $ref_item{'fullname'} = $name;
3767 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3768 $name =~ s!^refs/($strip_refs|remotes)/!!;
3769 $ref_item{'name'} = $name;
3770 # for refs neither in 'heads' nor 'remotes' we want to
3771 # show their ref dir
3772 my $ref_dir = (defined $1) ? $1 : '';
3773 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3774 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3777 $ref_item{'id'} = $hash;
3778 $ref_item{'title'} = $title || '(no commit message)';
3779 $ref_item{'epoch'} = $epoch;
3780 if ($epoch) {
3781 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3782 } else {
3783 $ref_item{'age'} = "unknown";
3786 push @headslist, \%ref_item;
3788 close $fd;
3790 return wantarray ? @headslist : \@headslist;
3793 sub git_get_tags_list {
3794 my $limit = shift;
3795 my @tagslist;
3797 open my $fd, '-|', git_cmd(), 'for-each-ref',
3798 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3799 '--format=%(objectname) %(objecttype) %(refname) '.
3800 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3801 'refs/tags'
3802 or return;
3803 while (my $line = <$fd>) {
3804 my %ref_item;
3806 chomp $line;
3807 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3808 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3809 my ($creator, $epoch, $tz) =
3810 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3811 $ref_item{'fullname'} = $name;
3812 $name =~ s!^refs/tags/!!;
3814 $ref_item{'type'} = $type;
3815 $ref_item{'id'} = $id;
3816 $ref_item{'name'} = $name;
3817 if ($type eq "tag") {
3818 $ref_item{'subject'} = $title;
3819 $ref_item{'reftype'} = $reftype;
3820 $ref_item{'refid'} = $refid;
3821 } else {
3822 $ref_item{'reftype'} = $type;
3823 $ref_item{'refid'} = $id;
3826 if ($type eq "tag" || $type eq "commit") {
3827 $ref_item{'epoch'} = $epoch;
3828 if ($epoch) {
3829 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3830 } else {
3831 $ref_item{'age'} = "unknown";
3835 push @tagslist, \%ref_item;
3837 close $fd;
3839 return wantarray ? @tagslist : \@tagslist;
3842 ## ----------------------------------------------------------------------
3843 ## filesystem-related functions
3845 sub get_file_owner {
3846 my $path = shift;
3848 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3849 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3850 if (!defined $gcos) {
3851 return undef;
3853 my $owner = $gcos;
3854 $owner =~ s/[,;].*$//;
3855 return to_utf8($owner);
3858 # assume that file exists
3859 sub insert_file {
3860 my $filename = shift;
3862 open my $fd, '<', $filename;
3863 print map { to_utf8($_) } <$fd>;
3864 close $fd;
3867 ## ......................................................................
3868 ## mimetype related functions
3870 sub mimetype_guess_file {
3871 my $filename = shift;
3872 my $mimemap = shift;
3873 -r $mimemap or return undef;
3875 my %mimemap;
3876 open(my $mh, '<', $mimemap) or return undef;
3877 while (<$mh>) {
3878 next if m/^#/; # skip comments
3879 my ($mimetype, @exts) = split(/\s+/);
3880 foreach my $ext (@exts) {
3881 $mimemap{$ext} = $mimetype;
3884 close($mh);
3886 $filename =~ /\.([^.]*)$/;
3887 return $mimemap{$1};
3890 sub mimetype_guess {
3891 my $filename = shift;
3892 my $mime;
3893 $filename =~ /\./ or return undef;
3895 if ($mimetypes_file) {
3896 my $file = $mimetypes_file;
3897 if ($file !~ m!^/!) { # if it is relative path
3898 # it is relative to project
3899 $file = "$projectroot/$project/$file";
3901 $mime = mimetype_guess_file($filename, $file);
3903 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3904 return $mime;
3907 sub blob_mimetype {
3908 my $fd = shift;
3909 my $filename = shift;
3911 if ($filename) {
3912 my $mime = mimetype_guess($filename);
3913 $mime and return $mime;
3916 # just in case
3917 return $default_blob_plain_mimetype unless $fd;
3919 if (-T $fd) {
3920 return 'text/plain';
3921 } elsif (! $filename) {
3922 return 'application/octet-stream';
3923 } elsif ($filename =~ m/\.png$/i) {
3924 return 'image/png';
3925 } elsif ($filename =~ m/\.gif$/i) {
3926 return 'image/gif';
3927 } elsif ($filename =~ m/\.jpe?g$/i) {
3928 return 'image/jpeg';
3929 } else {
3930 return 'application/octet-stream';
3934 sub blob_contenttype {
3935 my ($fd, $file_name, $type) = @_;
3937 $type ||= blob_mimetype($fd, $file_name);
3938 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3939 $type .= "; charset=$default_text_plain_charset";
3942 return $type;
3945 # guess file syntax for syntax highlighting; return undef if no highlighting
3946 # the name of syntax can (in the future) depend on syntax highlighter used
3947 sub guess_file_syntax {
3948 my ($highlight, $mimetype, $file_name) = @_;
3949 return undef unless ($highlight && defined $file_name);
3950 my $basename = basename($file_name, '.in');
3951 return $highlight_basename{$basename}
3952 if exists $highlight_basename{$basename};
3954 $basename =~ /\.([^.]*)$/;
3955 my $ext = $1 or return undef;
3956 return $highlight_ext{$ext}
3957 if exists $highlight_ext{$ext};
3959 return undef;
3962 # run highlighter and return FD of its output,
3963 # or return original FD if no highlighting
3964 sub run_highlighter {
3965 my ($fd, $highlight, $syntax) = @_;
3966 return $fd unless ($highlight && defined $syntax);
3968 close $fd;
3969 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3970 quote_command($highlight_bin).
3971 " --replace-tabs=8 --fragment --syntax $syntax |"
3972 or die_error(500, "Couldn't open file or run syntax highlighter");
3973 return $fd;
3976 ## ======================================================================
3977 ## functions printing HTML: header, footer, error page
3979 sub get_page_title {
3980 my $title = to_utf8($site_name);
3982 unless (defined $project) {
3983 if (defined $project_filter) {
3984 $title .= " - projects in '" . esc_path($project_filter) . "'";
3986 return $title;
3988 $title .= " - " . to_utf8($project);
3990 return $title unless (defined $action);
3991 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3993 return $title unless (defined $file_name);
3994 $title .= " - " . esc_path($file_name);
3995 if ($action eq "tree" && $file_name !~ m|/$|) {
3996 $title .= "/";
3999 return $title;
4002 sub get_content_type_html {
4003 # require explicit support from the UA if we are to send the page as
4004 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4005 # we have to do this because MSIE sometimes globs '*/*', pretending to
4006 # support xhtml+xml but choking when it gets what it asked for.
4007 if (defined $cgi->http('HTTP_ACCEPT') &&
4008 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4009 $cgi->Accept('application/xhtml+xml') != 0) {
4010 return 'application/xhtml+xml';
4011 } else {
4012 return 'text/html';
4016 sub print_feed_meta {
4017 if (defined $project) {
4018 my %href_params = get_feed_info();
4019 if (!exists $href_params{'-title'}) {
4020 $href_params{'-title'} = 'log';
4023 foreach my $format (qw(RSS Atom)) {
4024 my $type = lc($format);
4025 my %link_attr = (
4026 '-rel' => 'alternate',
4027 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4028 '-type' => "application/$type+xml"
4031 $href_params{'extra_options'} = undef;
4032 $href_params{'action'} = $type;
4033 $link_attr{'-href'} = href(%href_params);
4034 print "<link ".
4035 "rel=\"$link_attr{'-rel'}\" ".
4036 "title=\"$link_attr{'-title'}\" ".
4037 "href=\"$link_attr{'-href'}\" ".
4038 "type=\"$link_attr{'-type'}\" ".
4039 "/>\n";
4041 $href_params{'extra_options'} = '--no-merges';
4042 $link_attr{'-href'} = href(%href_params);
4043 $link_attr{'-title'} .= ' (no merges)';
4044 print "<link ".
4045 "rel=\"$link_attr{'-rel'}\" ".
4046 "title=\"$link_attr{'-title'}\" ".
4047 "href=\"$link_attr{'-href'}\" ".
4048 "type=\"$link_attr{'-type'}\" ".
4049 "/>\n";
4052 } else {
4053 printf('<link rel="alternate" title="%s projects list" '.
4054 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4055 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4056 printf('<link rel="alternate" title="%s projects feeds" '.
4057 'href="%s" type="text/x-opml" />'."\n",
4058 esc_attr($site_name), href(project=>undef, action=>"opml"));
4062 sub print_header_links {
4063 my $status = shift;
4065 # print out each stylesheet that exist, providing backwards capability
4066 # for those people who defined $stylesheet in a config file
4067 if (defined $stylesheet) {
4068 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4069 } else {
4070 foreach my $stylesheet (@stylesheets) {
4071 next unless $stylesheet;
4072 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4075 print_feed_meta()
4076 if ($status eq '200 OK');
4077 if (defined $favicon) {
4078 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4082 sub print_nav_breadcrumbs_path {
4083 my $dirprefix = undef;
4084 while (my $part = shift) {
4085 $dirprefix .= "/" if defined $dirprefix;
4086 $dirprefix .= $part;
4087 print $cgi->a({-href => href(project => undef,
4088 project_filter => $dirprefix,
4089 action => "project_list")},
4090 esc_html($part)) . " / ";
4094 sub print_nav_breadcrumbs {
4095 my %opts = @_;
4097 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4098 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4100 if (defined $project) {
4101 my @dirname = split '/', $project;
4102 my $projectbasename = pop @dirname;
4103 print_nav_breadcrumbs_path(@dirname);
4104 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4105 if (defined $action) {
4106 my $action_print = $action ;
4107 if (defined $opts{-action_extra}) {
4108 $action_print = $cgi->a({-href => href(action=>$action)},
4109 $action);
4111 print " / $action_print";
4113 if (defined $opts{-action_extra}) {
4114 print " / $opts{-action_extra}";
4116 print "\n";
4117 } elsif (defined $project_filter) {
4118 print_nav_breadcrumbs_path(split '/', $project_filter);
4122 sub print_search_form {
4123 if (!defined $searchtext) {
4124 $searchtext = "";
4126 my $search_hash;
4127 if (defined $hash_base) {
4128 $search_hash = $hash_base;
4129 } elsif (defined $hash) {
4130 $search_hash = $hash;
4131 } else {
4132 $search_hash = "HEAD";
4134 my $action = $my_uri;
4135 my $use_pathinfo = gitweb_check_feature('pathinfo');
4136 if ($use_pathinfo) {
4137 $action .= "/".esc_url($project);
4139 print $cgi->start_form(-method => "get", -action => $action) .
4140 "<div class=\"search\">\n" .
4141 (!$use_pathinfo &&
4142 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4143 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4144 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4145 $cgi->popup_menu(-name => 'st', -default => 'commit',
4146 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4147 " " . $cgi->a({-href => href(action=>"search_help"),
4148 -title => "search help" }, "?") . " search:\n",
4149 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4150 "<span title=\"Extended regular expression\">" .
4151 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4152 -checked => $search_use_regexp) .
4153 "</span>" .
4154 "</div>" .
4155 $cgi->end_form() . "\n";
4158 sub git_header_html {
4159 my $status = shift || "200 OK";
4160 my $expires = shift;
4161 my %opts = @_;
4163 my $title = get_page_title();
4164 my $content_type = get_content_type_html();
4165 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4166 -status=> $status, -expires => $expires)
4167 unless ($opts{'-no_http_header'});
4168 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4169 print <<EOF;
4170 <?xml version="1.0" encoding="utf-8"?>
4171 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4172 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4173 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4174 <!-- git core binaries version $git_version -->
4175 <head>
4176 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4177 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4178 <meta name="robots" content="index, nofollow"/>
4179 <title>$title</title>
4181 # the stylesheet, favicon etc urls won't work correctly with path_info
4182 # unless we set the appropriate base URL
4183 if ($ENV{'PATH_INFO'}) {
4184 print "<base href=\"".esc_url($base_url)."\" />\n";
4186 print_header_links($status);
4188 if (defined $site_html_head_string) {
4189 print to_utf8($site_html_head_string);
4192 print "</head>\n" .
4193 "<body>\n";
4195 if (defined $site_header && -f $site_header) {
4196 insert_file($site_header);
4199 print "<div class=\"page_header\">\n";
4200 if (defined $logo) {
4201 print $cgi->a({-href => esc_url($logo_url),
4202 -title => $logo_label},
4203 $cgi->img({-src => esc_url($logo),
4204 -width => 72, -height => 27,
4205 -alt => "git",
4206 -class => "logo"}));
4208 print_nav_breadcrumbs(%opts);
4209 print "</div>\n";
4211 my $have_search = gitweb_check_feature('search');
4212 if (defined $project && $have_search) {
4213 print_search_form();
4217 sub git_footer_html {
4218 my $feed_class = 'rss_logo';
4220 print "<div class=\"page_footer\">\n";
4221 if (defined $project) {
4222 my $descr = git_get_project_description($project);
4223 if (defined $descr) {
4224 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4227 my %href_params = get_feed_info();
4228 if (!%href_params) {
4229 $feed_class .= ' generic';
4231 $href_params{'-title'} ||= 'log';
4233 foreach my $format (qw(RSS Atom)) {
4234 $href_params{'action'} = lc($format);
4235 print $cgi->a({-href => href(%href_params),
4236 -title => "$href_params{'-title'} $format feed",
4237 -class => $feed_class}, $format)."\n";
4240 } else {
4241 print $cgi->a({-href => href(project=>undef, action=>"opml",
4242 project_filter => $project_filter),
4243 -class => $feed_class}, "OPML") . " ";
4244 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4245 project_filter => $project_filter),
4246 -class => $feed_class}, "TXT") . "\n";
4248 print "</div>\n"; # class="page_footer"
4250 if (defined $t0 && gitweb_check_feature('timed')) {
4251 print "<div id=\"generating_info\">\n";
4252 print 'This page took '.
4253 '<span id="generating_time" class="time_span">'.
4254 tv_interval($t0, [ gettimeofday() ]).
4255 ' seconds </span>'.
4256 ' and '.
4257 '<span id="generating_cmd">'.
4258 $number_of_git_cmds.
4259 '</span> git commands '.
4260 " to generate.\n";
4261 print "</div>\n"; # class="page_footer"
4264 if (defined $site_footer && -f $site_footer) {
4265 insert_file($site_footer);
4268 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4269 if (defined $action &&
4270 $action eq 'blame_incremental') {
4271 print qq!<script type="text/javascript">\n!.
4272 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4273 qq! "!. href() .qq!");\n!.
4274 qq!</script>\n!;
4275 } else {
4276 my ($jstimezone, $tz_cookie, $datetime_class) =
4277 gitweb_get_feature('javascript-timezone');
4279 print qq!<script type="text/javascript">\n!.
4280 qq!window.onload = function () {\n!;
4281 if (gitweb_check_feature('javascript-actions')) {
4282 print qq! fixLinks();\n!;
4284 if ($jstimezone && $tz_cookie && $datetime_class) {
4285 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4286 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4288 print qq!};\n!.
4289 qq!</script>\n!;
4292 print "</body>\n" .
4293 "</html>";
4296 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4297 # Example: die_error(404, 'Hash not found')
4298 # By convention, use the following status codes (as defined in RFC 2616):
4299 # 400: Invalid or missing CGI parameters, or
4300 # requested object exists but has wrong type.
4301 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4302 # this server or project.
4303 # 404: Requested object/revision/project doesn't exist.
4304 # 500: The server isn't configured properly, or
4305 # an internal error occurred (e.g. failed assertions caused by bugs), or
4306 # an unknown error occurred (e.g. the git binary died unexpectedly).
4307 # 503: The server is currently unavailable (because it is overloaded,
4308 # or down for maintenance). Generally, this is a temporary state.
4309 sub die_error {
4310 my $status = shift || 500;
4311 my $error = esc_html(shift) || "Internal Server Error";
4312 my $extra = shift;
4313 my %opts = @_;
4315 my %http_responses = (
4316 400 => '400 Bad Request',
4317 403 => '403 Forbidden',
4318 404 => '404 Not Found',
4319 500 => '500 Internal Server Error',
4320 503 => '503 Service Unavailable',
4322 git_header_html($http_responses{$status}, undef, %opts);
4323 print <<EOF;
4324 <div class="page_body">
4325 <br /><br />
4326 $status - $error
4327 <br />
4329 if (defined $extra) {
4330 print "<hr />\n" .
4331 "$extra\n";
4333 print "</div>\n";
4335 git_footer_html();
4336 goto DONE_GITWEB
4337 unless ($opts{'-error_handler'});
4340 ## ----------------------------------------------------------------------
4341 ## functions printing or outputting HTML: navigation
4343 sub git_print_page_nav {
4344 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4345 $extra = '' if !defined $extra; # pager or formats
4347 my @navs = qw(summary shortlog log commit commitdiff tree);
4348 if ($suppress) {
4349 @navs = grep { $_ ne $suppress } @navs;
4352 my %arg = map { $_ => {action=>$_} } @navs;
4353 if (defined $head) {
4354 for (qw(commit commitdiff)) {
4355 $arg{$_}{'hash'} = $head;
4357 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4358 for (qw(shortlog log)) {
4359 $arg{$_}{'hash'} = $head;
4364 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4365 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4367 my @actions = gitweb_get_feature('actions');
4368 my %repl = (
4369 '%' => '%',
4370 'n' => $project, # project name
4371 'f' => $git_dir, # project path within filesystem
4372 'h' => $treehead || '', # current hash ('h' parameter)
4373 'b' => $treebase || '', # hash base ('hb' parameter)
4375 while (@actions) {
4376 my ($label, $link, $pos) = splice(@actions,0,3);
4377 # insert
4378 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4379 # munch munch
4380 $link =~ s/%([%nfhb])/$repl{$1}/g;
4381 $arg{$label}{'_href'} = $link;
4384 print "<div class=\"page_nav\">\n" .
4385 (join " | ",
4386 map { $_ eq $current ?
4387 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4388 } @navs);
4389 print "<br/>\n$extra<br/>\n" .
4390 "</div>\n";
4393 # returns a submenu for the nagivation of the refs views (tags, heads,
4394 # remotes) with the current view disabled and the remotes view only
4395 # available if the feature is enabled
4396 sub format_ref_views {
4397 my ($current) = @_;
4398 my @ref_views = qw{tags heads};
4399 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4400 return join " | ", map {
4401 $_ eq $current ? $_ :
4402 $cgi->a({-href => href(action=>$_)}, $_)
4403 } @ref_views
4406 sub format_paging_nav {
4407 my ($action, $page, $has_next_link) = @_;
4408 my $paging_nav;
4411 if ($page > 0) {
4412 $paging_nav .=
4413 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4414 " &sdot; " .
4415 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4416 -accesskey => "p", -title => "Alt-p"}, "prev");
4417 } else {
4418 $paging_nav .= "first &sdot; prev";
4421 if ($has_next_link) {
4422 $paging_nav .= " &sdot; " .
4423 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4424 -accesskey => "n", -title => "Alt-n"}, "next");
4425 } else {
4426 $paging_nav .= " &sdot; next";
4429 return $paging_nav;
4432 ## ......................................................................
4433 ## functions printing or outputting HTML: div
4435 sub git_print_header_div {
4436 my ($action, $title, $hash, $hash_base) = @_;
4437 my %args = ();
4439 $args{'action'} = $action;
4440 $args{'hash'} = $hash if $hash;
4441 $args{'hash_base'} = $hash_base if $hash_base;
4443 print "<div class=\"header\">\n" .
4444 $cgi->a({-href => href(%args), -class => "title"},
4445 $title ? $title : $action) .
4446 "\n</div>\n";
4449 sub format_repo_url {
4450 my ($name, $url) = @_;
4451 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4454 # Group output by placing it in a DIV element and adding a header.
4455 # Options for start_div() can be provided by passing a hash reference as the
4456 # first parameter to the function.
4457 # Options to git_print_header_div() can be provided by passing an array
4458 # reference. This must follow the options to start_div if they are present.
4459 # The content can be a scalar, which is output as-is, a scalar reference, which
4460 # is output after html escaping, an IO handle passed either as *handle or
4461 # *handle{IO}, or a function reference. In the latter case all following
4462 # parameters will be taken as argument to the content function call.
4463 sub git_print_section {
4464 my ($div_args, $header_args, $content);
4465 my $arg = shift;
4466 if (ref($arg) eq 'HASH') {
4467 $div_args = $arg;
4468 $arg = shift;
4470 if (ref($arg) eq 'ARRAY') {
4471 $header_args = $arg;
4472 $arg = shift;
4474 $content = $arg;
4476 print $cgi->start_div($div_args);
4477 git_print_header_div(@$header_args);
4479 if (ref($content) eq 'CODE') {
4480 $content->(@_);
4481 } elsif (ref($content) eq 'SCALAR') {
4482 print esc_html($$content);
4483 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4484 print <$content>;
4485 } elsif (!ref($content) && defined($content)) {
4486 print $content;
4489 print $cgi->end_div;
4492 sub format_timestamp_html {
4493 my $date = shift;
4494 my $strtime = $date->{'rfc2822'};
4496 my (undef, undef, $datetime_class) =
4497 gitweb_get_feature('javascript-timezone');
4498 if ($datetime_class) {
4499 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4502 my $localtime_format = '(%02d:%02d %s)';
4503 if ($date->{'hour_local'} < 6) {
4504 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4506 $strtime .= ' ' .
4507 sprintf($localtime_format,
4508 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4510 return $strtime;
4513 # Outputs the author name and date in long form
4514 sub git_print_authorship {
4515 my $co = shift;
4516 my %opts = @_;
4517 my $tag = $opts{-tag} || 'div';
4518 my $author = $co->{'author_name'};
4520 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4521 print "<$tag class=\"author_date\">" .
4522 format_search_author($author, "author", esc_html($author)) .
4523 " [".format_timestamp_html(\%ad)."]".
4524 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4525 "</$tag>\n";
4528 # Outputs table rows containing the full author or committer information,
4529 # in the format expected for 'commit' view (& similar).
4530 # Parameters are a commit hash reference, followed by the list of people
4531 # to output information for. If the list is empty it defaults to both
4532 # author and committer.
4533 sub git_print_authorship_rows {
4534 my $co = shift;
4535 # too bad we can't use @people = @_ || ('author', 'committer')
4536 my @people = @_;
4537 @people = ('author', 'committer') unless @people;
4538 foreach my $who (@people) {
4539 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4540 print "<tr><td>$who</td><td>" .
4541 format_search_author($co->{"${who}_name"}, $who,
4542 esc_html($co->{"${who}_name"})) . " " .
4543 format_search_author($co->{"${who}_email"}, $who,
4544 esc_html("<" . $co->{"${who}_email"} . ">")) .
4545 "</td><td rowspan=\"2\">" .
4546 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4547 "</td></tr>\n" .
4548 "<tr>" .
4549 "<td></td><td>" .
4550 format_timestamp_html(\%wd) .
4551 "</td>" .
4552 "</tr>\n";
4556 sub git_print_page_path {
4557 my $name = shift;
4558 my $type = shift;
4559 my $hb = shift;
4562 print "<div class=\"page_path\">";
4563 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4564 -title => 'tree root'}, to_utf8("[$project]"));
4565 print " / ";
4566 if (defined $name) {
4567 my @dirname = split '/', $name;
4568 my $basename = pop @dirname;
4569 my $fullname = '';
4571 foreach my $dir (@dirname) {
4572 $fullname .= ($fullname ? '/' : '') . $dir;
4573 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4574 hash_base=>$hb),
4575 -title => $fullname}, esc_path($dir));
4576 print " / ";
4578 if (defined $type && $type eq 'blob') {
4579 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4580 hash_base=>$hb),
4581 -title => $name}, esc_path($basename));
4582 } elsif (defined $type && $type eq 'tree') {
4583 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4584 hash_base=>$hb),
4585 -title => $name}, esc_path($basename));
4586 print " / ";
4587 } else {
4588 print esc_path($basename);
4591 print "<br/></div>\n";
4594 sub git_print_log {
4595 my $log = shift;
4596 my %opts = @_;
4598 if ($opts{'-remove_title'}) {
4599 # remove title, i.e. first line of log
4600 shift @$log;
4602 # remove leading empty lines
4603 while (defined $log->[0] && $log->[0] eq "") {
4604 shift @$log;
4607 # print log
4608 my $skip_blank_line = 0;
4609 foreach my $line (@$log) {
4610 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4611 if (! $opts{'-remove_signoff'}) {
4612 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4613 $skip_blank_line = 1;
4615 next;
4618 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4619 if (! $opts{'-remove_signoff'}) {
4620 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4621 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4622 "</span><br/>\n";
4623 $skip_blank_line = 1;
4625 next;
4628 # print only one empty line
4629 # do not print empty line after signoff
4630 if ($line eq "") {
4631 next if ($skip_blank_line);
4632 $skip_blank_line = 1;
4633 } else {
4634 $skip_blank_line = 0;
4637 print format_log_line_html($line) . "<br/>\n";
4640 if ($opts{'-final_empty_line'}) {
4641 # end with single empty line
4642 print "<br/>\n" unless $skip_blank_line;
4646 # return link target (what link points to)
4647 sub git_get_link_target {
4648 my $hash = shift;
4649 my $link_target;
4651 # read link
4652 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4653 or return;
4655 local $/ = undef;
4656 $link_target = <$fd>;
4658 close $fd
4659 or return;
4661 return $link_target;
4664 # given link target, and the directory (basedir) the link is in,
4665 # return target of link relative to top directory (top tree);
4666 # return undef if it is not possible (including absolute links).
4667 sub normalize_link_target {
4668 my ($link_target, $basedir) = @_;
4670 # absolute symlinks (beginning with '/') cannot be normalized
4671 return if (substr($link_target, 0, 1) eq '/');
4673 # normalize link target to path from top (root) tree (dir)
4674 my $path;
4675 if ($basedir) {
4676 $path = $basedir . '/' . $link_target;
4677 } else {
4678 # we are in top (root) tree (dir)
4679 $path = $link_target;
4682 # remove //, /./, and /../
4683 my @path_parts;
4684 foreach my $part (split('/', $path)) {
4685 # discard '.' and ''
4686 next if (!$part || $part eq '.');
4687 # handle '..'
4688 if ($part eq '..') {
4689 if (@path_parts) {
4690 pop @path_parts;
4691 } else {
4692 # link leads outside repository (outside top dir)
4693 return;
4695 } else {
4696 push @path_parts, $part;
4699 $path = join('/', @path_parts);
4701 return $path;
4704 # print tree entry (row of git_tree), but without encompassing <tr> element
4705 sub git_print_tree_entry {
4706 my ($t, $basedir, $hash_base, $have_blame) = @_;
4708 my %base_key = ();
4709 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4711 # The format of a table row is: mode list link. Where mode is
4712 # the mode of the entry, list is the name of the entry, an href,
4713 # and link is the action links of the entry.
4715 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4716 if (exists $t->{'size'}) {
4717 print "<td class=\"size\">$t->{'size'}</td>\n";
4719 if ($t->{'type'} eq "blob") {
4720 print "<td class=\"list\">" .
4721 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4722 file_name=>"$basedir$t->{'name'}", %base_key),
4723 -class => "list"}, esc_path($t->{'name'}));
4724 if (S_ISLNK(oct $t->{'mode'})) {
4725 my $link_target = git_get_link_target($t->{'hash'});
4726 if ($link_target) {
4727 my $norm_target = normalize_link_target($link_target, $basedir);
4728 if (defined $norm_target) {
4729 print " -> " .
4730 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4731 file_name=>$norm_target),
4732 -title => $norm_target}, esc_path($link_target));
4733 } else {
4734 print " -> " . esc_path($link_target);
4738 print "</td>\n";
4739 print "<td class=\"link\">";
4740 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4741 file_name=>"$basedir$t->{'name'}", %base_key)},
4742 "blob");
4743 if ($have_blame) {
4744 print " | " .
4745 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4746 file_name=>"$basedir$t->{'name'}", %base_key)},
4747 "blame");
4749 if (defined $hash_base) {
4750 print " | " .
4751 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4752 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4753 "history");
4755 print " | " .
4756 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4757 file_name=>"$basedir$t->{'name'}")},
4758 "raw");
4759 print "</td>\n";
4761 } elsif ($t->{'type'} eq "tree") {
4762 print "<td class=\"list\">";
4763 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4764 file_name=>"$basedir$t->{'name'}",
4765 %base_key)},
4766 esc_path($t->{'name'}));
4767 print "</td>\n";
4768 print "<td class=\"link\">";
4769 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4770 file_name=>"$basedir$t->{'name'}",
4771 %base_key)},
4772 "tree");
4773 if (defined $hash_base) {
4774 print " | " .
4775 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4776 file_name=>"$basedir$t->{'name'}")},
4777 "history");
4779 print "</td>\n";
4780 } else {
4781 # unknown object: we can only present history for it
4782 # (this includes 'commit' object, i.e. submodule support)
4783 print "<td class=\"list\">" .
4784 esc_path($t->{'name'}) .
4785 "</td>\n";
4786 print "<td class=\"link\">";
4787 if (defined $hash_base) {
4788 print $cgi->a({-href => href(action=>"history",
4789 hash_base=>$hash_base,
4790 file_name=>"$basedir$t->{'name'}")},
4791 "history");
4793 print "</td>\n";
4797 ## ......................................................................
4798 ## functions printing large fragments of HTML
4800 # get pre-image filenames for merge (combined) diff
4801 sub fill_from_file_info {
4802 my ($diff, @parents) = @_;
4804 $diff->{'from_file'} = [ ];
4805 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4806 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4807 if ($diff->{'status'}[$i] eq 'R' ||
4808 $diff->{'status'}[$i] eq 'C') {
4809 $diff->{'from_file'}[$i] =
4810 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4814 return $diff;
4817 # is current raw difftree line of file deletion
4818 sub is_deleted {
4819 my $diffinfo = shift;
4821 return $diffinfo->{'to_id'} eq ('0' x 40);
4824 # does patch correspond to [previous] difftree raw line
4825 # $diffinfo - hashref of parsed raw diff format
4826 # $patchinfo - hashref of parsed patch diff format
4827 # (the same keys as in $diffinfo)
4828 sub is_patch_split {
4829 my ($diffinfo, $patchinfo) = @_;
4831 return defined $diffinfo && defined $patchinfo
4832 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4836 sub git_difftree_body {
4837 my ($difftree, $hash, @parents) = @_;
4838 my ($parent) = $parents[0];
4839 my $have_blame = gitweb_check_feature('blame');
4840 print "<div class=\"list_head\">\n";
4841 if ($#{$difftree} > 10) {
4842 print(($#{$difftree} + 1) . " files changed:\n");
4844 print "</div>\n";
4846 print "<table class=\"" .
4847 (@parents > 1 ? "combined " : "") .
4848 "diff_tree\">\n";
4850 # header only for combined diff in 'commitdiff' view
4851 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4852 if ($has_header) {
4853 # table header
4854 print "<thead><tr>\n" .
4855 "<th></th><th></th>\n"; # filename, patchN link
4856 for (my $i = 0; $i < @parents; $i++) {
4857 my $par = $parents[$i];
4858 print "<th>" .
4859 $cgi->a({-href => href(action=>"commitdiff",
4860 hash=>$hash, hash_parent=>$par),
4861 -title => 'commitdiff to parent number ' .
4862 ($i+1) . ': ' . substr($par,0,7)},
4863 $i+1) .
4864 "&nbsp;</th>\n";
4866 print "</tr></thead>\n<tbody>\n";
4869 my $alternate = 1;
4870 my $patchno = 0;
4871 foreach my $line (@{$difftree}) {
4872 my $diff = parsed_difftree_line($line);
4874 if ($alternate) {
4875 print "<tr class=\"dark\">\n";
4876 } else {
4877 print "<tr class=\"light\">\n";
4879 $alternate ^= 1;
4881 if (exists $diff->{'nparents'}) { # combined diff
4883 fill_from_file_info($diff, @parents)
4884 unless exists $diff->{'from_file'};
4886 if (!is_deleted($diff)) {
4887 # file exists in the result (child) commit
4888 print "<td>" .
4889 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4890 file_name=>$diff->{'to_file'},
4891 hash_base=>$hash),
4892 -class => "list"}, esc_path($diff->{'to_file'})) .
4893 "</td>\n";
4894 } else {
4895 print "<td>" .
4896 esc_path($diff->{'to_file'}) .
4897 "</td>\n";
4900 if ($action eq 'commitdiff') {
4901 # link to patch
4902 $patchno++;
4903 print "<td class=\"link\">" .
4904 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4905 "patch") .
4906 " | " .
4907 "</td>\n";
4910 my $has_history = 0;
4911 my $not_deleted = 0;
4912 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4913 my $hash_parent = $parents[$i];
4914 my $from_hash = $diff->{'from_id'}[$i];
4915 my $from_path = $diff->{'from_file'}[$i];
4916 my $status = $diff->{'status'}[$i];
4918 $has_history ||= ($status ne 'A');
4919 $not_deleted ||= ($status ne 'D');
4921 if ($status eq 'A') {
4922 print "<td class=\"link\" align=\"right\"> | </td>\n";
4923 } elsif ($status eq 'D') {
4924 print "<td class=\"link\">" .
4925 $cgi->a({-href => href(action=>"blob",
4926 hash_base=>$hash,
4927 hash=>$from_hash,
4928 file_name=>$from_path)},
4929 "blob" . ($i+1)) .
4930 " | </td>\n";
4931 } else {
4932 if ($diff->{'to_id'} eq $from_hash) {
4933 print "<td class=\"link nochange\">";
4934 } else {
4935 print "<td class=\"link\">";
4937 print $cgi->a({-href => href(action=>"blobdiff",
4938 hash=>$diff->{'to_id'},
4939 hash_parent=>$from_hash,
4940 hash_base=>$hash,
4941 hash_parent_base=>$hash_parent,
4942 file_name=>$diff->{'to_file'},
4943 file_parent=>$from_path)},
4944 "diff" . ($i+1)) .
4945 " | </td>\n";
4949 print "<td class=\"link\">";
4950 if ($not_deleted) {
4951 print $cgi->a({-href => href(action=>"blob",
4952 hash=>$diff->{'to_id'},
4953 file_name=>$diff->{'to_file'},
4954 hash_base=>$hash)},
4955 "blob");
4956 print " | " if ($has_history);
4958 if ($has_history) {
4959 print $cgi->a({-href => href(action=>"history",
4960 file_name=>$diff->{'to_file'},
4961 hash_base=>$hash)},
4962 "history");
4964 print "</td>\n";
4966 print "</tr>\n";
4967 next; # instead of 'else' clause, to avoid extra indent
4969 # else ordinary diff
4971 my ($to_mode_oct, $to_mode_str, $to_file_type);
4972 my ($from_mode_oct, $from_mode_str, $from_file_type);
4973 if ($diff->{'to_mode'} ne ('0' x 6)) {
4974 $to_mode_oct = oct $diff->{'to_mode'};
4975 if (S_ISREG($to_mode_oct)) { # only for regular file
4976 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4978 $to_file_type = file_type($diff->{'to_mode'});
4980 if ($diff->{'from_mode'} ne ('0' x 6)) {
4981 $from_mode_oct = oct $diff->{'from_mode'};
4982 if (S_ISREG($from_mode_oct)) { # only for regular file
4983 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4985 $from_file_type = file_type($diff->{'from_mode'});
4988 if ($diff->{'status'} eq "A") { # created
4989 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4990 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4991 $mode_chng .= "]</span>";
4992 print "<td>";
4993 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4994 hash_base=>$hash, file_name=>$diff->{'file'}),
4995 -class => "list"}, esc_path($diff->{'file'}));
4996 print "</td>\n";
4997 print "<td>$mode_chng</td>\n";
4998 print "<td class=\"link\">";
4999 if ($action eq 'commitdiff') {
5000 # link to patch
5001 $patchno++;
5002 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5003 "patch") .
5004 " | ";
5006 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5007 hash_base=>$hash, file_name=>$diff->{'file'})},
5008 "blob");
5009 print "</td>\n";
5011 } elsif ($diff->{'status'} eq "D") { # deleted
5012 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5013 print "<td>";
5014 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5015 hash_base=>$parent, file_name=>$diff->{'file'}),
5016 -class => "list"}, esc_path($diff->{'file'}));
5017 print "</td>\n";
5018 print "<td>$mode_chng</td>\n";
5019 print "<td class=\"link\">";
5020 if ($action eq 'commitdiff') {
5021 # link to patch
5022 $patchno++;
5023 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5024 "patch") .
5025 " | ";
5027 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5028 hash_base=>$parent, file_name=>$diff->{'file'})},
5029 "blob") . " | ";
5030 if ($have_blame) {
5031 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5032 file_name=>$diff->{'file'})},
5033 "blame") . " | ";
5035 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5036 file_name=>$diff->{'file'})},
5037 "history");
5038 print "</td>\n";
5040 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5041 my $mode_chnge = "";
5042 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5043 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5044 if ($from_file_type ne $to_file_type) {
5045 $mode_chnge .= " from $from_file_type to $to_file_type";
5047 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5048 if ($from_mode_str && $to_mode_str) {
5049 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5050 } elsif ($to_mode_str) {
5051 $mode_chnge .= " mode: $to_mode_str";
5054 $mode_chnge .= "]</span>\n";
5056 print "<td>";
5057 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5058 hash_base=>$hash, file_name=>$diff->{'file'}),
5059 -class => "list"}, esc_path($diff->{'file'}));
5060 print "</td>\n";
5061 print "<td>$mode_chnge</td>\n";
5062 print "<td class=\"link\">";
5063 if ($action eq 'commitdiff') {
5064 # link to patch
5065 $patchno++;
5066 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5067 "patch") .
5068 " | ";
5069 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5070 # "commit" view and modified file (not onlu mode changed)
5071 print $cgi->a({-href => href(action=>"blobdiff",
5072 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5073 hash_base=>$hash, hash_parent_base=>$parent,
5074 file_name=>$diff->{'file'})},
5075 "diff") .
5076 " | ";
5078 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5079 hash_base=>$hash, file_name=>$diff->{'file'})},
5080 "blob") . " | ";
5081 if ($have_blame) {
5082 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5083 file_name=>$diff->{'file'})},
5084 "blame") . " | ";
5086 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5087 file_name=>$diff->{'file'})},
5088 "history");
5089 print "</td>\n";
5091 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5092 my %status_name = ('R' => 'moved', 'C' => 'copied');
5093 my $nstatus = $status_name{$diff->{'status'}};
5094 my $mode_chng = "";
5095 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5096 # mode also for directories, so we cannot use $to_mode_str
5097 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5099 print "<td>" .
5100 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5101 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5102 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5103 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5104 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5105 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5106 -class => "list"}, esc_path($diff->{'from_file'})) .
5107 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5108 "<td class=\"link\">";
5109 if ($action eq 'commitdiff') {
5110 # link to patch
5111 $patchno++;
5112 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5113 "patch") .
5114 " | ";
5115 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5116 # "commit" view and modified file (not only pure rename or copy)
5117 print $cgi->a({-href => href(action=>"blobdiff",
5118 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5119 hash_base=>$hash, hash_parent_base=>$parent,
5120 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5121 "diff") .
5122 " | ";
5124 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5125 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5126 "blob") . " | ";
5127 if ($have_blame) {
5128 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5129 file_name=>$diff->{'to_file'})},
5130 "blame") . " | ";
5132 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5133 file_name=>$diff->{'to_file'})},
5134 "history");
5135 print "</td>\n";
5137 } # we should not encounter Unmerged (U) or Unknown (X) status
5138 print "</tr>\n";
5140 print "</tbody>" if $has_header;
5141 print "</table>\n";
5144 # Print context lines and then rem/add lines in a side-by-side manner.
5145 sub print_sidebyside_diff_lines {
5146 my ($ctx, $rem, $add) = @_;
5148 # print context block before add/rem block
5149 if (@$ctx) {
5150 print join '',
5151 '<div class="chunk_block ctx">',
5152 '<div class="old">',
5153 @$ctx,
5154 '</div>',
5155 '<div class="new">',
5156 @$ctx,
5157 '</div>',
5158 '</div>';
5161 if (!@$add) {
5162 # pure removal
5163 print join '',
5164 '<div class="chunk_block rem">',
5165 '<div class="old">',
5166 @$rem,
5167 '</div>',
5168 '</div>';
5169 } elsif (!@$rem) {
5170 # pure addition
5171 print join '',
5172 '<div class="chunk_block add">',
5173 '<div class="new">',
5174 @$add,
5175 '</div>',
5176 '</div>';
5177 } else {
5178 print join '',
5179 '<div class="chunk_block chg">',
5180 '<div class="old">',
5181 @$rem,
5182 '</div>',
5183 '<div class="new">',
5184 @$add,
5185 '</div>',
5186 '</div>';
5190 # Print context lines and then rem/add lines in inline manner.
5191 sub print_inline_diff_lines {
5192 my ($ctx, $rem, $add) = @_;
5194 print @$ctx, @$rem, @$add;
5197 # Format removed and added line, mark changed part and HTML-format them.
5198 # Implementation is based on contrib/diff-highlight
5199 sub format_rem_add_lines_pair {
5200 my ($rem, $add, $num_parents) = @_;
5202 # We need to untabify lines before split()'ing them;
5203 # otherwise offsets would be invalid.
5204 chomp $rem;
5205 chomp $add;
5206 $rem = untabify($rem);
5207 $add = untabify($add);
5209 my @rem = split(//, $rem);
5210 my @add = split(//, $add);
5211 my ($esc_rem, $esc_add);
5212 # Ignore leading +/- characters for each parent.
5213 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5214 my ($prefix_has_nonspace, $suffix_has_nonspace);
5216 my $shorter = (@rem < @add) ? @rem : @add;
5217 while ($prefix_len < $shorter) {
5218 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5220 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5221 $prefix_len++;
5224 while ($prefix_len + $suffix_len < $shorter) {
5225 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5227 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5228 $suffix_len++;
5231 # Mark lines that are different from each other, but have some common
5232 # part that isn't whitespace. If lines are completely different, don't
5233 # mark them because that would make output unreadable, especially if
5234 # diff consists of multiple lines.
5235 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5236 $esc_rem = esc_html_hl_regions($rem, 'marked',
5237 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5238 $esc_add = esc_html_hl_regions($add, 'marked',
5239 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5240 } else {
5241 $esc_rem = esc_html($rem, -nbsp=>1);
5242 $esc_add = esc_html($add, -nbsp=>1);
5245 return format_diff_line(\$esc_rem, 'rem'),
5246 format_diff_line(\$esc_add, 'add');
5249 # HTML-format diff context, removed and added lines.
5250 sub format_ctx_rem_add_lines {
5251 my ($ctx, $rem, $add, $num_parents) = @_;
5252 my (@new_ctx, @new_rem, @new_add);
5253 my $can_highlight = 0;
5254 my $is_combined = ($num_parents > 1);
5256 # Highlight if every removed line has a corresponding added line.
5257 if (@$add > 0 && @$add == @$rem) {
5258 $can_highlight = 1;
5260 # Highlight lines in combined diff only if the chunk contains
5261 # diff between the same version, e.g.
5263 # - a
5264 # - b
5265 # + c
5266 # + d
5268 # Otherwise the highlightling would be confusing.
5269 if ($is_combined) {
5270 for (my $i = 0; $i < @$add; $i++) {
5271 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5272 my $prefix_add = substr($add->[$i], 0, $num_parents);
5274 $prefix_rem =~ s/-/+/g;
5276 if ($prefix_rem ne $prefix_add) {
5277 $can_highlight = 0;
5278 last;
5284 if ($can_highlight) {
5285 for (my $i = 0; $i < @$add; $i++) {
5286 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5287 $rem->[$i], $add->[$i], $num_parents);
5288 push @new_rem, $line_rem;
5289 push @new_add, $line_add;
5291 } else {
5292 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5293 @new_add = map { format_diff_line($_, 'add') } @$add;
5296 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5298 return (\@new_ctx, \@new_rem, \@new_add);
5301 # Print context lines and then rem/add lines.
5302 sub print_diff_lines {
5303 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5304 my $is_combined = $num_parents > 1;
5306 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5307 $num_parents);
5309 if ($diff_style eq 'sidebyside' && !$is_combined) {
5310 print_sidebyside_diff_lines($ctx, $rem, $add);
5311 } else {
5312 # default 'inline' style and unknown styles
5313 print_inline_diff_lines($ctx, $rem, $add);
5317 sub print_diff_chunk {
5318 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5319 my (@ctx, @rem, @add);
5321 # The class of the previous line.
5322 my $prev_class = '';
5324 return unless @chunk;
5326 # incomplete last line might be among removed or added lines,
5327 # or both, or among context lines: find which
5328 for (my $i = 1; $i < @chunk; $i++) {
5329 if ($chunk[$i][0] eq 'incomplete') {
5330 $chunk[$i][0] = $chunk[$i-1][0];
5334 # guardian
5335 push @chunk, ["", ""];
5337 foreach my $line_info (@chunk) {
5338 my ($class, $line) = @$line_info;
5340 # print chunk headers
5341 if ($class && $class eq 'chunk_header') {
5342 print format_diff_line($line, $class, $from, $to);
5343 next;
5346 ## print from accumulator when have some add/rem lines or end
5347 # of chunk (flush context lines), or when have add and rem
5348 # lines and new block is reached (otherwise add/rem lines could
5349 # be reordered)
5350 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5351 (@rem && @add && $class ne $prev_class)) {
5352 print_diff_lines(\@ctx, \@rem, \@add,
5353 $diff_style, $num_parents);
5354 @ctx = @rem = @add = ();
5357 ## adding lines to accumulator
5358 # guardian value
5359 last unless $line;
5360 # rem, add or change
5361 if ($class eq 'rem') {
5362 push @rem, $line;
5363 } elsif ($class eq 'add') {
5364 push @add, $line;
5366 # context line
5367 if ($class eq 'ctx') {
5368 push @ctx, $line;
5371 $prev_class = $class;
5375 sub git_patchset_body {
5376 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5377 my ($hash_parent) = $hash_parents[0];
5379 my $is_combined = (@hash_parents > 1);
5380 my $patch_idx = 0;
5381 my $patch_number = 0;
5382 my $patch_line;
5383 my $diffinfo;
5384 my $to_name;
5385 my (%from, %to);
5386 my @chunk; # for side-by-side diff
5388 print "<div class=\"patchset\">\n";
5390 # skip to first patch
5391 while ($patch_line = <$fd>) {
5392 chomp $patch_line;
5394 last if ($patch_line =~ m/^diff /);
5397 PATCH:
5398 while ($patch_line) {
5400 # parse "git diff" header line
5401 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5402 # $1 is from_name, which we do not use
5403 $to_name = unquote($2);
5404 $to_name =~ s!^b/!!;
5405 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5406 # $1 is 'cc' or 'combined', which we do not use
5407 $to_name = unquote($2);
5408 } else {
5409 $to_name = undef;
5412 # check if current patch belong to current raw line
5413 # and parse raw git-diff line if needed
5414 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5415 # this is continuation of a split patch
5416 print "<div class=\"patch cont\">\n";
5417 } else {
5418 # advance raw git-diff output if needed
5419 $patch_idx++ if defined $diffinfo;
5421 # read and prepare patch information
5422 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5424 # compact combined diff output can have some patches skipped
5425 # find which patch (using pathname of result) we are at now;
5426 if ($is_combined) {
5427 while ($to_name ne $diffinfo->{'to_file'}) {
5428 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5429 format_diff_cc_simplified($diffinfo, @hash_parents) .
5430 "</div>\n"; # class="patch"
5432 $patch_idx++;
5433 $patch_number++;
5435 last if $patch_idx > $#$difftree;
5436 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5440 # modifies %from, %to hashes
5441 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5443 # this is first patch for raw difftree line with $patch_idx index
5444 # we index @$difftree array from 0, but number patches from 1
5445 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5448 # git diff header
5449 #assert($patch_line =~ m/^diff /) if DEBUG;
5450 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5451 $patch_number++;
5452 # print "git diff" header
5453 print format_git_diff_header_line($patch_line, $diffinfo,
5454 \%from, \%to);
5456 # print extended diff header
5457 print "<div class=\"diff extended_header\">\n";
5458 EXTENDED_HEADER:
5459 while ($patch_line = <$fd>) {
5460 chomp $patch_line;
5462 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5464 print format_extended_diff_header_line($patch_line, $diffinfo,
5465 \%from, \%to);
5467 print "</div>\n"; # class="diff extended_header"
5469 # from-file/to-file diff header
5470 if (! $patch_line) {
5471 print "</div>\n"; # class="patch"
5472 last PATCH;
5474 next PATCH if ($patch_line =~ m/^diff /);
5475 #assert($patch_line =~ m/^---/) if DEBUG;
5477 my $last_patch_line = $patch_line;
5478 $patch_line = <$fd>;
5479 chomp $patch_line;
5480 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5482 print format_diff_from_to_header($last_patch_line, $patch_line,
5483 $diffinfo, \%from, \%to,
5484 @hash_parents);
5486 # the patch itself
5487 LINE:
5488 while ($patch_line = <$fd>) {
5489 chomp $patch_line;
5491 next PATCH if ($patch_line =~ m/^diff /);
5493 my $class = diff_line_class($patch_line, \%from, \%to);
5495 if ($class eq 'chunk_header') {
5496 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5497 @chunk = ();
5500 push @chunk, [ $class, $patch_line ];
5503 } continue {
5504 if (@chunk) {
5505 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5506 @chunk = ();
5508 print "</div>\n"; # class="patch"
5511 # for compact combined (--cc) format, with chunk and patch simplification
5512 # the patchset might be empty, but there might be unprocessed raw lines
5513 for (++$patch_idx if $patch_number > 0;
5514 $patch_idx < @$difftree;
5515 ++$patch_idx) {
5516 # read and prepare patch information
5517 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5519 # generate anchor for "patch" links in difftree / whatchanged part
5520 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5521 format_diff_cc_simplified($diffinfo, @hash_parents) .
5522 "</div>\n"; # class="patch"
5524 $patch_number++;
5527 if ($patch_number == 0) {
5528 if (@hash_parents > 1) {
5529 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5530 } else {
5531 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5535 print "</div>\n"; # class="patchset"
5538 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5540 sub git_project_search_form {
5541 my ($searchtext, $search_use_regexp) = @_;
5543 my $limit = '';
5544 if ($project_filter) {
5545 $limit = " in '$project_filter/'";
5548 print "<div class=\"projsearch\">\n";
5549 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5550 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5551 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5552 if (defined $project_filter);
5553 print $cgi->textfield(-name => 's', -value => $searchtext,
5554 -title => "Search project by name and description$limit",
5555 -size => 60) . "\n" .
5556 "<span title=\"Extended regular expression\">" .
5557 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5558 -checked => $search_use_regexp) .
5559 "</span>\n" .
5560 $cgi->submit(-name => 'btnS', -value => 'Search') .
5561 $cgi->end_form() . "\n" .
5562 "<span class=\"projectlist_link\">" .
5563 $cgi->a({-href => href(project => undef, searchtext => undef,
5564 action => 'project_list',
5565 project_filter => $project_filter)},
5566 esc_html("List all projects$limit")) . "</span>\n";
5567 print "</div>\n";
5570 # entry for given @keys needs filling if at least one of keys in list
5571 # is not present in %$project_info
5572 sub project_info_needs_filling {
5573 my ($project_info, @keys) = @_;
5575 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5576 foreach my $key (@keys) {
5577 if (!exists $project_info->{$key}) {
5578 return 1;
5581 return;
5584 sub git_retrieve_cache_file {
5585 my $cache_file = shift;
5587 use Storable qw(retrieve);
5589 if ((my $dump = eval { retrieve($cache_file) })) {
5590 return $$dump[1] if
5591 ref($dump) eq 'ARRAY' &&
5592 @$dump == 2 &&
5593 $$dump[0] eq GITWEB_CACHE_FORMAT &&
5594 ref($$dump[1]) eq 'ARRAY';
5596 return undef;
5599 sub git_store_cache_file {
5600 my ($cache_file, $projlist) = @_;
5602 use File::Basename qw(dirname);
5603 use POSIX qw(:fcntl_h);
5604 use Storable qw(store_fd);
5606 my $cache_d = dirname($cache_file);
5607 my $mask = umask();
5608 umask($mask & ~0070) if $cache_grpshared;
5609 if ((-d $cache_d || mkdir($cache_d, $cache_grpshared ? 0770 : 0700)) &&
5610 sysopen(my $fd, "$cache_file.lock", O_WRONLY|O_CREAT|O_EXCL, $cache_grpshared ? 0660 : 0600)) {
5611 store_fd([GITWEB_CACHE_FORMAT, $projlist], $fd);
5612 close $fd;
5613 rename "$cache_file.lock", $cache_file;
5615 umask($mask) if $cache_grpshared;
5618 # fills project list info (age, description, owner, category, forks, etc.)
5619 # for each project in the list, removing invalid projects from
5620 # returned list, or fill only specified info.
5622 # Invalid projects are removed from the returned list if and only if you
5623 # ask 'age' or 'age_string' to be filled, because they are the only fields
5624 # that run unconditionally git command that requires repository, and
5625 # therefore do always check if project repository is invalid.
5627 # USAGE:
5628 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5629 # ensures that 'descr_long' and 'ctags' fields are filled
5630 # * @project_list = fill_project_list_info(\@project_list)
5631 # ensures that all fields are filled (and invalid projects removed)
5633 # NOTE: modifies $projlist, but does not remove entries from it
5634 sub fill_project_list_info {
5635 my ($projlist, @wanted_keys) = @_;
5637 use File::stat;
5639 my $cache_file = "$cache_dir/$projlist_cache_name";
5641 my @projects;
5642 my $stale = 0;
5643 my $now = time();
5644 my $cache_mtime;
5645 if ($projlist_cache_lifetime && -f $cache_file) {
5646 $cache_mtime = stat($cache_file)->mtime;
5648 if (defined $cache_mtime && # caching is on and $cache_file exists
5649 $cache_mtime + $projlist_cache_lifetime*60 > $now &&
5650 (my $dump = git_retrieve_cache_file($cache_file))) {
5651 # Cache hit.
5652 $stale = $now - $cache_mtime;
5653 @projects = @$dump;
5655 } else { # Cache miss.
5656 if (defined $cache_mtime) {
5657 # Postpone timeout by two minutes so that we get
5658 # enough time to do our job, or to be more exact
5659 # make cache expire after two minutes from now.
5660 my $time = $now - $projlist_cache_lifetime*60 + 120;
5661 utime $time, $time, $cache_file;
5663 @projects = fill_project_list_info_uncached($projlist, @wanted_keys);
5664 git_store_cache_file($cache_file, \@projects) if $projlist_cache_lifetime;
5667 if ($projlist_cache_lifetime && $stale > 0) {
5668 print "<div class=\"stale_info\">Cached version (${stale}s old)</div>\n";
5671 return @projects;
5674 sub fill_project_list_info_uncached {
5675 my ($projlist, @wanted_keys) = @_;
5676 my @projects;
5677 my $filter_set = sub { return @_; };
5678 if (@wanted_keys) {
5679 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5680 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5683 my $show_ctags = gitweb_check_feature('ctags');
5684 PROJECT:
5685 foreach my $pr (@$projlist) {
5686 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5687 my (@activity) = git_get_last_activity($pr->{'path'});
5688 unless (@activity) {
5689 next PROJECT;
5691 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5693 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5694 my $descr = git_get_project_description($pr->{'path'}) || "";
5695 $descr = to_utf8($descr);
5696 $pr->{'descr_long'} = $descr;
5697 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5699 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5700 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5702 if ($show_ctags &&
5703 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5704 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5706 if ($projects_list_group_categories &&
5707 project_info_needs_filling($pr, $filter_set->('category'))) {
5708 my $cat = git_get_project_category($pr->{'path'}) ||
5709 $project_list_default_category;
5710 $pr->{'category'} = to_utf8($cat);
5713 push @projects, $pr;
5716 return @projects;
5719 sub sort_projects_list {
5720 my ($projlist, $order) = @_;
5722 sub order_str {
5723 my $key = shift;
5724 return sub { $a->{$key} cmp $b->{$key} };
5727 sub order_num_then_undef {
5728 my $key = shift;
5729 return sub {
5730 defined $a->{$key} ?
5731 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5732 (defined $b->{$key} ? 1 : 0)
5736 my %orderings = (
5737 project => order_str('path'),
5738 descr => order_str('descr_long'),
5739 owner => order_str('owner'),
5740 age => order_num_then_undef('age'),
5743 my $ordering = $orderings{$order};
5744 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5747 # returns a hash of categories, containing the list of project
5748 # belonging to each category
5749 sub build_projlist_by_category {
5750 my ($projlist, $from, $to) = @_;
5751 my %categories;
5753 $from = 0 unless defined $from;
5754 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5756 for (my $i = $from; $i <= $to; $i++) {
5757 my $pr = $projlist->[$i];
5758 push @{$categories{ $pr->{'category'} }}, $pr;
5761 return wantarray ? %categories : \%categories;
5764 # print 'sort by' <th> element, generating 'sort by $name' replay link
5765 # if that order is not selected
5766 sub print_sort_th {
5767 print format_sort_th(@_);
5770 sub format_sort_th {
5771 my ($name, $order, $header) = @_;
5772 my $sort_th = "";
5773 $header ||= ucfirst($name);
5775 if ($order eq $name) {
5776 $sort_th .= "<th>$header</th>\n";
5777 } else {
5778 $sort_th .= "<th>" .
5779 $cgi->a({-href => href(-replay=>1, order=>$name),
5780 -class => "header"}, $header) .
5781 "</th>\n";
5784 return $sort_th;
5787 sub git_project_list_rows {
5788 my ($projlist, $from, $to, $check_forks) = @_;
5790 $from = 0 unless defined $from;
5791 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5793 my $alternate = 1;
5794 for (my $i = $from; $i <= $to; $i++) {
5795 my $pr = $projlist->[$i];
5797 if ($alternate) {
5798 print "<tr class=\"dark\">\n";
5799 } else {
5800 print "<tr class=\"light\">\n";
5802 $alternate ^= 1;
5804 if ($check_forks) {
5805 print "<td>";
5806 if ($pr->{'forks'}) {
5807 my $nforks = scalar @{$pr->{'forks'}};
5808 if ($nforks > 0) {
5809 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5810 -title => "$nforks forks"}, "+");
5811 } else {
5812 print $cgi->span({-title => "$nforks forks"}, "+");
5815 print "</td>\n";
5817 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5818 -class => "list"},
5819 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5820 "</td>\n" .
5821 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5822 -class => "list",
5823 -title => $pr->{'descr_long'}},
5824 $search_regexp
5825 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5826 $pr->{'descr'}, $search_regexp)
5827 : esc_html($pr->{'descr'})) .
5828 "</td>\n";
5829 unless ($omit_owner) {
5830 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5832 unless ($omit_age_column) {
5833 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5834 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5836 print"<td class=\"link\">" .
5837 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5838 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5839 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5840 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5841 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5842 "</td>\n" .
5843 "</tr>\n";
5847 sub git_project_list_body {
5848 # actually uses global variable $project
5849 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action) = @_;
5850 my @projects = @$projlist;
5852 my $check_forks = gitweb_check_feature('forks');
5853 my $show_ctags = gitweb_check_feature('ctags');
5854 my $tagfilter = $show_ctags ? $input_params{'ctag_filter'} : undef;
5855 $check_forks = undef
5856 if ($tagfilter || $search_regexp);
5858 # filtering out forks before filling info allows to do less work
5859 @projects = filter_forks_from_projects_list(\@projects)
5860 if ($check_forks);
5861 # search_projects_list pre-fills required info
5862 @projects = search_projects_list(\@projects,
5863 'search_regexp' => $search_regexp,
5864 'tagfilter' => $tagfilter)
5865 if ($tagfilter || $search_regexp);
5866 # fill the rest
5867 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5868 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5869 push @all_fields, 'owner' unless($omit_owner);
5870 @projects = fill_project_list_info(\@projects, @all_fields);
5872 $order ||= $default_projects_order;
5873 $from = 0 unless defined $from;
5874 $to = $#projects if (!defined $to || $#projects < $to);
5876 # short circuit
5877 if ($from > $to) {
5878 print "<center>\n".
5879 "<b>No such projects found</b><br />\n".
5880 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5881 "</center>\n<br />\n";
5882 return;
5885 @projects = sort_projects_list(\@projects, $order);
5887 if ($show_ctags) {
5888 my $ctags = git_gather_all_ctags(\@projects);
5889 my $cloud = git_populate_project_tagcloud($ctags, $ctags_action||'project_list');
5890 print git_show_project_tagcloud($cloud, 64);
5893 print "<table class=\"project_list\">\n";
5894 unless ($no_header) {
5895 print "<tr>\n";
5896 if ($check_forks) {
5897 print "<th></th>\n";
5899 print_sort_th('project', $order, 'Project');
5900 print_sort_th('descr', $order, 'Description');
5901 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5902 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5903 print "<th></th>\n" . # for links
5904 "</tr>\n";
5907 if ($projects_list_group_categories) {
5908 # only display categories with projects in the $from-$to window
5909 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5910 my %categories = build_projlist_by_category(\@projects, $from, $to);
5911 foreach my $cat (sort keys %categories) {
5912 unless ($cat eq "") {
5913 print "<tr>\n";
5914 if ($check_forks) {
5915 print "<td></td>\n";
5917 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5918 print "</tr>\n";
5921 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5923 } else {
5924 git_project_list_rows(\@projects, $from, $to, $check_forks);
5927 if (defined $extra) {
5928 print "<tr>\n";
5929 if ($check_forks) {
5930 print "<td></td>\n";
5932 print "<td colspan=\"5\">$extra</td>\n" .
5933 "</tr>\n";
5935 print "</table>\n";
5938 sub git_log_body {
5939 # uses global variable $project
5940 my ($commitlist, $from, $to, $refs, $extra) = @_;
5942 $from = 0 unless defined $from;
5943 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5945 for (my $i = 0; $i <= $to; $i++) {
5946 my %co = %{$commitlist->[$i]};
5947 next if !%co;
5948 my $commit = $co{'id'};
5949 my $ref = format_ref_marker($refs, $commit);
5950 git_print_header_div('commit',
5951 "<span class=\"age\">$co{'age_string'}</span>" .
5952 esc_html($co{'title'}) . $ref,
5953 $commit);
5954 print "<div class=\"title_text\">\n" .
5955 "<div class=\"log_link\">\n" .
5956 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5957 " | " .
5958 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5959 " | " .
5960 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5961 "<br/>\n" .
5962 "</div>\n";
5963 git_print_authorship(\%co, -tag => 'span');
5964 print "<br/>\n</div>\n";
5966 print "<div class=\"log_body\">\n";
5967 git_print_log($co{'comment'}, -final_empty_line=> 1);
5968 print "</div>\n";
5970 if ($extra) {
5971 print "<div class=\"page_nav\">\n";
5972 print "$extra\n";
5973 print "</div>\n";
5977 sub git_shortlog_body {
5978 # uses global variable $project
5979 my ($commitlist, $from, $to, $refs, $extra) = @_;
5981 $from = 0 unless defined $from;
5982 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5984 print "<table class=\"shortlog\">\n";
5985 my $alternate = 1;
5986 for (my $i = $from; $i <= $to; $i++) {
5987 my %co = %{$commitlist->[$i]};
5988 my $commit = $co{'id'};
5989 my $ref = format_ref_marker($refs, $commit);
5990 if ($alternate) {
5991 print "<tr class=\"dark\">\n";
5992 } else {
5993 print "<tr class=\"light\">\n";
5995 $alternate ^= 1;
5996 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5997 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5998 format_author_html('td', \%co, 10) . "<td>";
5999 print format_subject_html($co{'title'}, $co{'title_short'},
6000 href(action=>"commit", hash=>$commit), $ref);
6001 print "</td>\n" .
6002 "<td class=\"link\">" .
6003 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
6004 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
6005 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
6006 my $snapshot_links = format_snapshot_links($commit);
6007 if (defined $snapshot_links) {
6008 print " | " . $snapshot_links;
6010 print "</td>\n" .
6011 "</tr>\n";
6013 if (defined $extra) {
6014 print "<tr>\n" .
6015 "<td colspan=\"4\">$extra</td>\n" .
6016 "</tr>\n";
6018 print "</table>\n";
6021 sub git_history_body {
6022 # Warning: assumes constant type (blob or tree) during history
6023 my ($commitlist, $from, $to, $refs, $extra,
6024 $file_name, $file_hash, $ftype) = @_;
6026 $from = 0 unless defined $from;
6027 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
6029 print "<table class=\"history\">\n";
6030 my $alternate = 1;
6031 for (my $i = $from; $i <= $to; $i++) {
6032 my %co = %{$commitlist->[$i]};
6033 if (!%co) {
6034 next;
6036 my $commit = $co{'id'};
6038 my $ref = format_ref_marker($refs, $commit);
6040 if ($alternate) {
6041 print "<tr class=\"dark\">\n";
6042 } else {
6043 print "<tr class=\"light\">\n";
6045 $alternate ^= 1;
6046 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6047 # shortlog: format_author_html('td', \%co, 10)
6048 format_author_html('td', \%co, 15, 3) . "<td>";
6049 # originally git_history used chop_str($co{'title'}, 50)
6050 print format_subject_html($co{'title'}, $co{'title_short'},
6051 href(action=>"commit", hash=>$commit), $ref);
6052 print "</td>\n" .
6053 "<td class=\"link\">" .
6054 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
6055 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
6057 if ($ftype eq 'blob') {
6058 my $blob_current = $file_hash;
6059 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6060 if (defined $blob_current && defined $blob_parent &&
6061 $blob_current ne $blob_parent) {
6062 print " | " .
6063 $cgi->a({-href => href(action=>"blobdiff",
6064 hash=>$blob_current, hash_parent=>$blob_parent,
6065 hash_base=>$hash_base, hash_parent_base=>$commit,
6066 file_name=>$file_name)},
6067 "diff to current");
6070 print "</td>\n" .
6071 "</tr>\n";
6073 if (defined $extra) {
6074 print "<tr>\n" .
6075 "<td colspan=\"4\">$extra</td>\n" .
6076 "</tr>\n";
6078 print "</table>\n";
6081 sub git_tags_body {
6082 # uses global variable $project
6083 my ($taglist, $from, $to, $extra) = @_;
6084 $from = 0 unless defined $from;
6085 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6087 print "<table class=\"tags\">\n";
6088 my $alternate = 1;
6089 for (my $i = $from; $i <= $to; $i++) {
6090 my $entry = $taglist->[$i];
6091 my %tag = %$entry;
6092 my $comment = $tag{'subject'};
6093 my $comment_short;
6094 if (defined $comment) {
6095 $comment_short = chop_str($comment, 30, 5);
6097 if ($alternate) {
6098 print "<tr class=\"dark\">\n";
6099 } else {
6100 print "<tr class=\"light\">\n";
6102 $alternate ^= 1;
6103 if (defined $tag{'age'}) {
6104 print "<td><i>$tag{'age'}</i></td>\n";
6105 } else {
6106 print "<td></td>\n";
6108 print "<td>" .
6109 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6110 -class => "list name"}, esc_html($tag{'name'})) .
6111 "</td>\n" .
6112 "<td>";
6113 if (defined $comment) {
6114 print format_subject_html($comment, $comment_short,
6115 href(action=>"tag", hash=>$tag{'id'}));
6117 print "</td>\n" .
6118 "<td class=\"selflink\">";
6119 if ($tag{'type'} eq "tag") {
6120 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6121 } else {
6122 print "&nbsp;";
6124 print "</td>\n" .
6125 "<td class=\"link\">" . " | " .
6126 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6127 if ($tag{'reftype'} eq "commit") {
6128 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6129 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6130 } elsif ($tag{'reftype'} eq "blob") {
6131 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6133 print "</td>\n" .
6134 "</tr>";
6136 if (defined $extra) {
6137 print "<tr>\n" .
6138 "<td colspan=\"5\">$extra</td>\n" .
6139 "</tr>\n";
6141 print "</table>\n";
6144 sub git_heads_body {
6145 # uses global variable $project
6146 my ($headlist, $head_at, $from, $to, $extra) = @_;
6147 $from = 0 unless defined $from;
6148 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6150 print "<table class=\"heads\">\n";
6151 my $alternate = 1;
6152 for (my $i = $from; $i <= $to; $i++) {
6153 my $entry = $headlist->[$i];
6154 my %ref = %$entry;
6155 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6156 if ($alternate) {
6157 print "<tr class=\"dark\">\n";
6158 } else {
6159 print "<tr class=\"light\">\n";
6161 $alternate ^= 1;
6162 print "<td><i>$ref{'age'}</i></td>\n" .
6163 ($curr ? "<td class=\"current_head\">" : "<td>") .
6164 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6165 -class => "list name"},esc_html($ref{'name'})) .
6166 "</td>\n" .
6167 "<td class=\"link\">" .
6168 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6169 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6170 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6171 "</td>\n" .
6172 "</tr>";
6174 if (defined $extra) {
6175 print "<tr>\n" .
6176 "<td colspan=\"3\">$extra</td>\n" .
6177 "</tr>\n";
6179 print "</table>\n";
6182 # Display a single remote block
6183 sub git_remote_block {
6184 my ($remote, $rdata, $limit, $head) = @_;
6186 my $heads = $rdata->{'heads'};
6187 my $fetch = $rdata->{'fetch'};
6188 my $push = $rdata->{'push'};
6190 my $urls_table = "<table class=\"projects_list\">\n" ;
6192 if (defined $fetch) {
6193 if ($fetch eq $push) {
6194 $urls_table .= format_repo_url("URL", $fetch);
6195 } else {
6196 $urls_table .= format_repo_url("Fetch URL", $fetch);
6197 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6199 } elsif (defined $push) {
6200 $urls_table .= format_repo_url("Push URL", $push);
6201 } else {
6202 $urls_table .= format_repo_url("", "No remote URL");
6205 $urls_table .= "</table>\n";
6207 my $dots;
6208 if (defined $limit && $limit < @$heads) {
6209 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6212 print $urls_table;
6213 git_heads_body($heads, $head, 0, $limit, $dots);
6216 # Display a list of remote names with the respective fetch and push URLs
6217 sub git_remotes_list {
6218 my ($remotedata, $limit) = @_;
6219 print "<table class=\"heads\">\n";
6220 my $alternate = 1;
6221 my @remotes = sort keys %$remotedata;
6223 my $limited = $limit && $limit < @remotes;
6225 $#remotes = $limit - 1 if $limited;
6227 while (my $remote = shift @remotes) {
6228 my $rdata = $remotedata->{$remote};
6229 my $fetch = $rdata->{'fetch'};
6230 my $push = $rdata->{'push'};
6231 if ($alternate) {
6232 print "<tr class=\"dark\">\n";
6233 } else {
6234 print "<tr class=\"light\">\n";
6236 $alternate ^= 1;
6237 print "<td>" .
6238 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6239 -class=> "list name"},esc_html($remote)) .
6240 "</td>";
6241 print "<td class=\"link\">" .
6242 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6243 " | " .
6244 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6245 "</td>";
6247 print "</tr>\n";
6250 if ($limited) {
6251 print "<tr>\n" .
6252 "<td colspan=\"3\">" .
6253 $cgi->a({-href => href(action=>"remotes")}, "...") .
6254 "</td>\n" . "</tr>\n";
6257 print "</table>";
6260 # Display remote heads grouped by remote, unless there are too many
6261 # remotes, in which case we only display the remote names
6262 sub git_remotes_body {
6263 my ($remotedata, $limit, $head) = @_;
6264 if ($limit and $limit < keys %$remotedata) {
6265 git_remotes_list($remotedata, $limit);
6266 } else {
6267 fill_remote_heads($remotedata);
6268 while (my ($remote, $rdata) = each %$remotedata) {
6269 git_print_section({-class=>"remote", -id=>$remote},
6270 ["remotes", $remote, $remote], sub {
6271 git_remote_block($remote, $rdata, $limit, $head);
6277 sub git_search_message {
6278 my %co = @_;
6280 my $greptype;
6281 if ($searchtype eq 'commit') {
6282 $greptype = "--grep=";
6283 } elsif ($searchtype eq 'author') {
6284 $greptype = "--author=";
6285 } elsif ($searchtype eq 'committer') {
6286 $greptype = "--committer=";
6288 $greptype .= $searchtext;
6289 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6290 $greptype, '--regexp-ignore-case',
6291 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6293 my $paging_nav = '';
6294 if ($page > 0) {
6295 $paging_nav .=
6296 $cgi->a({-href => href(-replay=>1, page=>undef)},
6297 "first") .
6298 " &sdot; " .
6299 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6300 -accesskey => "p", -title => "Alt-p"}, "prev");
6301 } else {
6302 $paging_nav .= "first &sdot; prev";
6304 my $next_link = '';
6305 if ($#commitlist >= 100) {
6306 $next_link =
6307 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6308 -accesskey => "n", -title => "Alt-n"}, "next");
6309 $paging_nav .= " &sdot; $next_link";
6310 } else {
6311 $paging_nav .= " &sdot; next";
6314 git_header_html();
6316 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6317 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6318 if ($page == 0 && !@commitlist) {
6319 print "<p>No match.</p>\n";
6320 } else {
6321 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6324 git_footer_html();
6327 sub git_search_changes {
6328 my %co = @_;
6330 local $/ = "\n";
6331 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6332 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6333 ($search_use_regexp ? '--pickaxe-regex' : ())
6334 or die_error(500, "Open git-log failed");
6336 git_header_html();
6338 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6339 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6341 print "<table class=\"pickaxe search\">\n";
6342 my $alternate = 1;
6343 undef %co;
6344 my @files;
6345 while (my $line = <$fd>) {
6346 chomp $line;
6347 next unless $line;
6349 my %set = parse_difftree_raw_line($line);
6350 if (defined $set{'commit'}) {
6351 # finish previous commit
6352 if (%co) {
6353 print "</td>\n" .
6354 "<td class=\"link\">" .
6355 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6356 "commit") .
6357 " | " .
6358 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6359 hash_base=>$co{'id'})},
6360 "tree") .
6361 "</td>\n" .
6362 "</tr>\n";
6365 if ($alternate) {
6366 print "<tr class=\"dark\">\n";
6367 } else {
6368 print "<tr class=\"light\">\n";
6370 $alternate ^= 1;
6371 %co = parse_commit($set{'commit'});
6372 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6373 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6374 "<td><i>$author</i></td>\n" .
6375 "<td>" .
6376 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6377 -class => "list subject"},
6378 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6379 } elsif (defined $set{'to_id'}) {
6380 next if ($set{'to_id'} =~ m/^0{40}$/);
6382 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6383 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6384 -class => "list"},
6385 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6386 "<br/>\n";
6389 close $fd;
6391 # finish last commit (warning: repetition!)
6392 if (%co) {
6393 print "</td>\n" .
6394 "<td class=\"link\">" .
6395 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6396 "commit") .
6397 " | " .
6398 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6399 hash_base=>$co{'id'})},
6400 "tree") .
6401 "</td>\n" .
6402 "</tr>\n";
6405 print "</table>\n";
6407 git_footer_html();
6410 sub git_search_files {
6411 my %co = @_;
6413 local $/ = "\n";
6414 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6415 $search_use_regexp ? ('-E', '-i') : '-F',
6416 $searchtext, $co{'tree'}
6417 or die_error(500, "Open git-grep failed");
6419 git_header_html();
6421 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6422 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6424 print "<table class=\"grep_search\">\n";
6425 my $alternate = 1;
6426 my $matches = 0;
6427 my $lastfile = '';
6428 my $file_href;
6429 while (my $line = <$fd>) {
6430 chomp $line;
6431 my ($file, $lno, $ltext, $binary);
6432 last if ($matches++ > 1000);
6433 if ($line =~ /^Binary file (.+) matches$/) {
6434 $file = $1;
6435 $binary = 1;
6436 } else {
6437 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6438 $file =~ s/^$co{'tree'}://;
6440 if ($file ne $lastfile) {
6441 $lastfile and print "</td></tr>\n";
6442 if ($alternate++) {
6443 print "<tr class=\"dark\">\n";
6444 } else {
6445 print "<tr class=\"light\">\n";
6447 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6448 file_name=>$file);
6449 print "<td class=\"list\">".
6450 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6451 print "</td><td>\n";
6452 $lastfile = $file;
6454 if ($binary) {
6455 print "<div class=\"binary\">Binary file</div>\n";
6456 } else {
6457 $ltext = untabify($ltext);
6458 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6459 $ltext = esc_html($1, -nbsp=>1);
6460 $ltext .= '<span class="match">';
6461 $ltext .= esc_html($2, -nbsp=>1);
6462 $ltext .= '</span>';
6463 $ltext .= esc_html($3, -nbsp=>1);
6464 } else {
6465 $ltext = esc_html($ltext, -nbsp=>1);
6467 print "<div class=\"pre\">" .
6468 $cgi->a({-href => $file_href.'#l'.$lno,
6469 -class => "linenr"}, sprintf('%4i', $lno)) .
6470 ' ' . $ltext . "</div>\n";
6473 if ($lastfile) {
6474 print "</td></tr>\n";
6475 if ($matches > 1000) {
6476 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6478 } else {
6479 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6481 close $fd;
6483 print "</table>\n";
6485 git_footer_html();
6488 sub git_search_grep_body {
6489 my ($commitlist, $from, $to, $extra) = @_;
6490 $from = 0 unless defined $from;
6491 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6493 print "<table class=\"commit_search\">\n";
6494 my $alternate = 1;
6495 for (my $i = $from; $i <= $to; $i++) {
6496 my %co = %{$commitlist->[$i]};
6497 if (!%co) {
6498 next;
6500 my $commit = $co{'id'};
6501 if ($alternate) {
6502 print "<tr class=\"dark\">\n";
6503 } else {
6504 print "<tr class=\"light\">\n";
6506 $alternate ^= 1;
6507 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6508 format_author_html('td', \%co, 15, 5) .
6509 "<td>" .
6510 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6511 -class => "list subject"},
6512 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6513 my $comment = $co{'comment'};
6514 foreach my $line (@$comment) {
6515 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6516 my ($lead, $match, $trail) = ($1, $2, $3);
6517 $match = chop_str($match, 70, 5, 'center');
6518 my $contextlen = int((80 - length($match))/2);
6519 $contextlen = 30 if ($contextlen > 30);
6520 $lead = chop_str($lead, $contextlen, 10, 'left');
6521 $trail = chop_str($trail, $contextlen, 10, 'right');
6523 $lead = esc_html($lead);
6524 $match = esc_html($match);
6525 $trail = esc_html($trail);
6527 print "$lead<span class=\"match\">$match</span>$trail<br />";
6530 print "</td>\n" .
6531 "<td class=\"link\">" .
6532 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6533 " | " .
6534 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6535 " | " .
6536 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6537 print "</td>\n" .
6538 "</tr>\n";
6540 if (defined $extra) {
6541 print "<tr>\n" .
6542 "<td colspan=\"3\">$extra</td>\n" .
6543 "</tr>\n";
6545 print "</table>\n";
6548 ## ======================================================================
6549 ## ======================================================================
6550 ## actions
6552 sub git_project_list_load {
6553 my $empty_list_ok = shift;
6554 my $order = $input_params{'order'};
6555 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6556 die_error(400, "Unknown order parameter");
6559 my @list = git_get_projects_list($project_filter, $strict_export);
6560 if (!@list) {
6561 die_error(404, "No projects found") unless $empty_list_ok;
6564 return (\@list, $order);
6567 sub git_frontpage {
6568 my ($projlist, $order);
6570 if ($frontpage_no_project_list) {
6571 $project = undef;
6572 $project_filter = undef;
6573 } else {
6574 ($projlist, $order) = git_project_list_load(1);
6576 git_header_html();
6577 if (defined $home_text && -f $home_text) {
6578 print "<div class=\"index_include\">\n";
6579 insert_file($home_text);
6580 print "</div>\n";
6582 git_project_search_form($searchtext, $search_use_regexp);
6583 if ($frontpage_no_project_list) {
6584 my $show_ctags = gitweb_check_feature('ctags');
6585 if ($frontpage_no_project_list == 1 and $show_ctags) {
6586 my @projects = git_get_projects_list($project_filter, $strict_export);
6587 @projects = filter_forks_from_projects_list(\@projects) if gitweb_check_feature('forks');
6588 @projects = fill_project_list_info(\@projects, 'ctags');
6589 my $ctags = git_gather_all_ctags(\@projects);
6590 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6591 print git_show_project_tagcloud($cloud, 64);
6593 } else {
6594 git_project_list_body($projlist, $order);
6596 git_footer_html();
6599 sub git_project_list {
6600 my ($projlist, $order) = git_project_list_load();
6601 git_header_html();
6602 if (not $frontpage_no_project_list && 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();
6608 git_project_list_body($projlist, $order);
6609 git_footer_html();
6612 sub git_forks {
6613 my $order = $input_params{'order'};
6614 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6615 die_error(400, "Unknown order parameter");
6618 my $filter = $project;
6619 $filter =~ s/\.git$//;
6620 my @list = git_get_projects_list($filter);
6621 if (!@list) {
6622 die_error(404, "No forks found");
6625 git_header_html();
6626 git_print_page_nav('','');
6627 git_print_header_div('summary', "$project forks");
6628 git_project_list_body(\@list, $order, undef, undef, undef, undef, 'forks');
6629 git_footer_html();
6632 sub git_project_index {
6633 my @projects = git_get_projects_list($project_filter, $strict_export);
6634 if (!@projects) {
6635 die_error(404, "No projects found");
6638 print $cgi->header(
6639 -type => 'text/plain',
6640 -charset => 'utf-8',
6641 -content_disposition => 'inline; filename="index.aux"');
6643 foreach my $pr (@projects) {
6644 if (!exists $pr->{'owner'}) {
6645 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6648 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6649 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6650 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6651 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6652 $path =~ s/ /\+/g;
6653 $owner =~ s/ /\+/g;
6655 print "$path $owner\n";
6659 sub git_summary {
6660 my $descr = git_get_project_description($project) || "none";
6661 my %co = parse_commit("HEAD");
6662 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6663 my $head = $co{'id'};
6664 my $remote_heads = gitweb_check_feature('remote_heads');
6666 my $owner = git_get_project_owner($project);
6668 my $refs = git_get_references();
6669 # These get_*_list functions return one more to allow us to see if
6670 # there are more ...
6671 my @taglist = git_get_tags_list(16);
6672 my @headlist = git_get_heads_list(16);
6673 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6674 my @forklist;
6675 my $check_forks = gitweb_check_feature('forks');
6677 if ($check_forks) {
6678 # find forks of a project
6679 my $filter = $project;
6680 $filter =~ s/\.git$//;
6681 @forklist = git_get_projects_list($filter);
6682 # filter out forks of forks
6683 @forklist = filter_forks_from_projects_list(\@forklist)
6684 if (@forklist);
6687 git_header_html();
6688 git_print_page_nav('summary','', $head);
6690 print "<div class=\"title\">&nbsp;</div>\n";
6691 print "<table class=\"projects_list\">\n" .
6692 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6693 if ($owner and not $omit_owner) {
6694 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6696 if (defined $cd{'rfc2822'}) {
6697 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6698 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6701 # use per project git URL list in $projectroot/$project/cloneurl
6702 # or make project git URL from git base URL and project name
6703 my $url_tag = "URL";
6704 my @url_list = git_get_project_url_list($project);
6705 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6706 foreach my $git_url (@url_list) {
6707 next unless $git_url;
6708 print format_repo_url($url_tag, $git_url);
6709 $url_tag = "";
6712 # Tag cloud
6713 my $show_ctags = gitweb_check_feature('ctags');
6714 if ($show_ctags) {
6715 my $ctags = git_get_project_ctags($project);
6716 if (%$ctags || $show_ctags !~ /^\d+$/) {
6717 # without ability to add tags, don't show if there are none
6718 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6719 print "<tr id=\"metadata_ctags\">" .
6720 "<td style=\"vertical-align:middle\">content tags<br />";
6721 print "</td>\n<td>" unless %$ctags;
6722 print "<form action=\"$show_ctags\" method=\"post\">" .
6723 "<input type=\"hidden\" name=\"p\" value=\"$project\"/>" .
6724 "add: <input type=\"text\" name=\"t\" size=\"10\" /></form>"
6725 unless $show_ctags =~ /^\d+$/;
6726 print "</td>\n<td>" if %$ctags;
6727 print git_show_project_tagcloud($cloud, 48)."</td>" .
6728 "</tr>\n";
6732 print "</table>\n";
6734 # If XSS prevention is on, we don't include README.html.
6735 # TODO: Allow a readme in some safe format.
6736 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6737 print "<div class=\"title\">readme</div>\n" .
6738 "<div class=\"readme\">\n";
6739 insert_file("$projectroot/$project/README.html");
6740 print "\n</div>\n"; # class="readme"
6743 # we need to request one more than 16 (0..15) to check if
6744 # those 16 are all
6745 my @commitlist = $head ? parse_commits($head, 17) : ();
6746 if (@commitlist) {
6747 git_print_header_div('shortlog');
6748 git_shortlog_body(\@commitlist, 0, 15, $refs,
6749 $#commitlist <= 15 ? undef :
6750 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6753 if (@taglist) {
6754 git_print_header_div('tags');
6755 git_tags_body(\@taglist, 0, 15,
6756 $#taglist <= 15 ? undef :
6757 $cgi->a({-href => href(action=>"tags")}, "..."));
6760 if (@headlist) {
6761 git_print_header_div('heads');
6762 git_heads_body(\@headlist, $head, 0, 15,
6763 $#headlist <= 15 ? undef :
6764 $cgi->a({-href => href(action=>"heads")}, "..."));
6767 if (%remotedata) {
6768 git_print_header_div('remotes');
6769 git_remotes_body(\%remotedata, 15, $head);
6772 if (@forklist) {
6773 git_print_header_div('forks');
6774 git_project_list_body(\@forklist, 'age', 0, 15,
6775 $#forklist <= 15 ? undef :
6776 $cgi->a({-href => href(action=>"forks")}, "..."),
6777 'no_header', 'forks');
6780 git_footer_html();
6783 sub git_tag {
6784 my %tag = parse_tag($hash);
6786 if (! %tag) {
6787 die_error(404, "Unknown tag object");
6790 my $head = git_get_head_hash($project);
6791 git_header_html();
6792 git_print_page_nav('','', $head,undef,$head);
6793 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6794 print "<div class=\"title_text\">\n" .
6795 "<table class=\"object_header\">\n" .
6796 "<tr>\n" .
6797 "<td>object</td>\n" .
6798 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6799 $tag{'object'}) . "</td>\n" .
6800 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6801 $tag{'type'}) . "</td>\n" .
6802 "</tr>\n";
6803 if (defined($tag{'author'})) {
6804 git_print_authorship_rows(\%tag, 'author');
6806 print "</table>\n\n" .
6807 "</div>\n";
6808 print "<div class=\"page_body\">";
6809 my $comment = $tag{'comment'};
6810 foreach my $line (@$comment) {
6811 chomp $line;
6812 print esc_html($line, -nbsp=>1) . "<br/>\n";
6814 print "</div>\n";
6815 git_footer_html();
6818 sub git_blame_common {
6819 my $format = shift || 'porcelain';
6820 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6821 $format = 'incremental';
6822 $action = 'blame_incremental'; # for page title etc
6825 # permissions
6826 gitweb_check_feature('blame')
6827 or die_error(403, "Blame view not allowed");
6829 # error checking
6830 die_error(400, "No file name given") unless $file_name;
6831 $hash_base ||= git_get_head_hash($project);
6832 die_error(404, "Couldn't find base commit") unless $hash_base;
6833 my %co = parse_commit($hash_base)
6834 or die_error(404, "Commit not found");
6835 my $ftype = "blob";
6836 if (!defined $hash) {
6837 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6838 or die_error(404, "Error looking up file");
6839 } else {
6840 $ftype = git_get_type($hash);
6841 if ($ftype !~ "blob") {
6842 die_error(400, "Object is not a blob");
6846 my $fd;
6847 if ($format eq 'incremental') {
6848 # get file contents (as base)
6849 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6850 or die_error(500, "Open git-cat-file failed");
6851 } elsif ($format eq 'data') {
6852 # run git-blame --incremental
6853 open $fd, "-|", git_cmd(), "blame", "--incremental",
6854 $hash_base, "--", $file_name
6855 or die_error(500, "Open git-blame --incremental failed");
6856 } else {
6857 # run git-blame --porcelain
6858 open $fd, "-|", git_cmd(), "blame", '-p',
6859 $hash_base, '--', $file_name
6860 or die_error(500, "Open git-blame --porcelain failed");
6862 binmode $fd, ':utf8';
6864 # incremental blame data returns early
6865 if ($format eq 'data') {
6866 print $cgi->header(
6867 -type=>"text/plain", -charset => "utf-8",
6868 -status=> "200 OK");
6869 local $| = 1; # output autoflush
6870 while (my $line = <$fd>) {
6871 print to_utf8($line);
6873 close $fd
6874 or print "ERROR $!\n";
6876 print 'END';
6877 if (defined $t0 && gitweb_check_feature('timed')) {
6878 print ' '.
6879 tv_interval($t0, [ gettimeofday() ]).
6880 ' '.$number_of_git_cmds;
6882 print "\n";
6884 return;
6887 # page header
6888 git_header_html();
6889 my $formats_nav =
6890 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6891 "blob") .
6892 " | ";
6893 if ($format eq 'incremental') {
6894 $formats_nav .=
6895 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6896 "blame") . " (non-incremental)";
6897 } else {
6898 $formats_nav .=
6899 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6900 "blame") . " (incremental)";
6902 $formats_nav .=
6903 " | " .
6904 $cgi->a({-href => href(action=>"history", -replay=>1)},
6905 "history") .
6906 " | " .
6907 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6908 "HEAD");
6909 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6910 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6911 git_print_page_path($file_name, $ftype, $hash_base);
6913 # page body
6914 if ($format eq 'incremental') {
6915 print "<noscript>\n<div class=\"error\"><center><b>\n".
6916 "This page requires JavaScript to run.\n Use ".
6917 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6918 'this page').
6919 " instead.\n".
6920 "</b></center></div>\n</noscript>\n";
6922 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6925 print qq!<div class="page_body">\n!;
6926 print qq!<div id="progress_info">... / ...</div>\n!
6927 if ($format eq 'incremental');
6928 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6929 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6930 qq!<thead>\n!.
6931 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6932 qq!</thead>\n!.
6933 qq!<tbody>\n!;
6935 my @rev_color = qw(light dark);
6936 my $num_colors = scalar(@rev_color);
6937 my $current_color = 0;
6939 if ($format eq 'incremental') {
6940 my $color_class = $rev_color[$current_color];
6942 #contents of a file
6943 my $linenr = 0;
6944 LINE:
6945 while (my $line = <$fd>) {
6946 chomp $line;
6947 $linenr++;
6949 print qq!<tr id="l$linenr" class="$color_class">!.
6950 qq!<td class="sha1"><a href=""> </a></td>!.
6951 qq!<td class="linenr">!.
6952 qq!<a class="linenr" href="">$linenr</a></td>!;
6953 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6954 print qq!</tr>\n!;
6957 } else { # porcelain, i.e. ordinary blame
6958 my %metainfo = (); # saves information about commits
6960 # blame data
6961 LINE:
6962 while (my $line = <$fd>) {
6963 chomp $line;
6964 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6965 # no <lines in group> for subsequent lines in group of lines
6966 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6967 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6968 if (!exists $metainfo{$full_rev}) {
6969 $metainfo{$full_rev} = { 'nprevious' => 0 };
6971 my $meta = $metainfo{$full_rev};
6972 my $data;
6973 while ($data = <$fd>) {
6974 chomp $data;
6975 last if ($data =~ s/^\t//); # contents of line
6976 if ($data =~ /^(\S+)(?: (.*))?$/) {
6977 $meta->{$1} = $2 unless exists $meta->{$1};
6979 if ($data =~ /^previous /) {
6980 $meta->{'nprevious'}++;
6983 my $short_rev = substr($full_rev, 0, 8);
6984 my $author = $meta->{'author'};
6985 my %date =
6986 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6987 my $date = $date{'iso-tz'};
6988 if ($group_size) {
6989 $current_color = ($current_color + 1) % $num_colors;
6991 my $tr_class = $rev_color[$current_color];
6992 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6993 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6994 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6995 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6996 if ($group_size) {
6997 print "<td class=\"sha1\"";
6998 print " title=\"". esc_html($author) . ", $date\"";
6999 print " rowspan=\"$group_size\"" if ($group_size > 1);
7000 print ">";
7001 print $cgi->a({-href => href(action=>"commit",
7002 hash=>$full_rev,
7003 file_name=>$file_name)},
7004 esc_html($short_rev));
7005 if ($group_size >= 2) {
7006 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
7007 if (@author_initials) {
7008 print "<br />" .
7009 esc_html(join('', @author_initials));
7010 # or join('.', ...)
7013 print "</td>\n";
7015 # 'previous' <sha1 of parent commit> <filename at commit>
7016 if (exists $meta->{'previous'} &&
7017 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
7018 $meta->{'parent'} = $1;
7019 $meta->{'file_parent'} = unquote($2);
7021 my $linenr_commit =
7022 exists($meta->{'parent'}) ?
7023 $meta->{'parent'} : $full_rev;
7024 my $linenr_filename =
7025 exists($meta->{'file_parent'}) ?
7026 $meta->{'file_parent'} : unquote($meta->{'filename'});
7027 my $blamed = href(action => 'blame',
7028 file_name => $linenr_filename,
7029 hash_base => $linenr_commit);
7030 print "<td class=\"linenr\">";
7031 print $cgi->a({ -href => "$blamed#l$orig_lineno",
7032 -class => "linenr" },
7033 esc_html($lineno));
7034 print "</td>";
7035 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
7036 print "</tr>\n";
7037 } # end while
7041 # footer
7042 print "</tbody>\n".
7043 "</table>\n"; # class="blame"
7044 print "</div>\n"; # class="blame_body"
7045 close $fd
7046 or print "Reading blob failed\n";
7048 git_footer_html();
7051 sub git_blame {
7052 git_blame_common();
7055 sub git_blame_incremental {
7056 git_blame_common('incremental');
7059 sub git_blame_data {
7060 git_blame_common('data');
7063 sub git_tags {
7064 my $head = git_get_head_hash($project);
7065 git_header_html();
7066 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
7067 git_print_header_div('summary', $project);
7069 my @tagslist = git_get_tags_list();
7070 if (@tagslist) {
7071 git_tags_body(\@tagslist);
7073 git_footer_html();
7076 sub git_heads {
7077 my $head = git_get_head_hash($project);
7078 git_header_html();
7079 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
7080 git_print_header_div('summary', $project);
7082 my @headslist = git_get_heads_list();
7083 if (@headslist) {
7084 git_heads_body(\@headslist, $head);
7086 git_footer_html();
7089 # used both for single remote view and for list of all the remotes
7090 sub git_remotes {
7091 gitweb_check_feature('remote_heads')
7092 or die_error(403, "Remote heads view is disabled");
7094 my $head = git_get_head_hash($project);
7095 my $remote = $input_params{'hash'};
7097 my $remotedata = git_get_remotes_list($remote);
7098 die_error(500, "Unable to get remote information") unless defined $remotedata;
7100 unless (%$remotedata) {
7101 die_error(404, defined $remote ?
7102 "Remote $remote not found" :
7103 "No remotes found");
7106 git_header_html(undef, undef, -action_extra => $remote);
7107 git_print_page_nav('', '', $head, undef, $head,
7108 format_ref_views($remote ? '' : 'remotes'));
7110 fill_remote_heads($remotedata);
7111 if (defined $remote) {
7112 git_print_header_div('remotes', "$remote remote for $project");
7113 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7114 } else {
7115 git_print_header_div('summary', "$project remotes");
7116 git_remotes_body($remotedata, undef, $head);
7119 git_footer_html();
7122 sub git_blob_plain {
7123 my $type = shift;
7124 my $expires;
7126 if (!defined $hash) {
7127 if (defined $file_name) {
7128 my $base = $hash_base || git_get_head_hash($project);
7129 $hash = git_get_hash_by_path($base, $file_name, "blob")
7130 or die_error(404, "Cannot find file");
7131 } else {
7132 die_error(400, "No file name defined");
7134 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7135 # blobs defined by non-textual hash id's can be cached
7136 $expires = "+1d";
7139 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7140 or die_error(500, "Open git-cat-file blob '$hash' failed");
7142 # content-type (can include charset)
7143 $type = blob_contenttype($fd, $file_name, $type);
7145 # "save as" filename, even when no $file_name is given
7146 my $save_as = "$hash";
7147 if (defined $file_name) {
7148 $save_as = $file_name;
7149 } elsif ($type =~ m/^text\//) {
7150 $save_as .= '.txt';
7153 # With XSS prevention on, blobs of all types except a few known safe
7154 # ones are served with "Content-Disposition: attachment" to make sure
7155 # they don't run in our security domain. For certain image types,
7156 # blob view writes an <img> tag referring to blob_plain view, and we
7157 # want to be sure not to break that by serving the image as an
7158 # attachment (though Firefox 3 doesn't seem to care).
7159 my $sandbox = $prevent_xss &&
7160 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7162 # serve text/* as text/plain
7163 if ($prevent_xss &&
7164 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7165 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7166 my $rest = $1;
7167 $rest = defined $rest ? $rest : '';
7168 $type = "text/plain$rest";
7171 print $cgi->header(
7172 -type => $type,
7173 -expires => $expires,
7174 -content_disposition =>
7175 ($sandbox ? 'attachment' : 'inline')
7176 . '; filename="' . $save_as . '"');
7177 local $/ = undef;
7178 binmode STDOUT, ':raw';
7179 print <$fd>;
7180 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7181 close $fd;
7184 sub git_blob {
7185 my $expires;
7187 if (!defined $hash) {
7188 if (defined $file_name) {
7189 my $base = $hash_base || git_get_head_hash($project);
7190 $hash = git_get_hash_by_path($base, $file_name, "blob")
7191 or die_error(404, "Cannot find file");
7192 } else {
7193 die_error(400, "No file name defined");
7195 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7196 # blobs defined by non-textual hash id's can be cached
7197 $expires = "+1d";
7200 my $have_blame = gitweb_check_feature('blame');
7201 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7202 or die_error(500, "Couldn't cat $file_name, $hash");
7203 my $mimetype = blob_mimetype($fd, $file_name);
7204 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7205 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7206 close $fd;
7207 return git_blob_plain($mimetype);
7209 # we can have blame only for text/* mimetype
7210 $have_blame &&= ($mimetype =~ m!^text/!);
7212 my $highlight = gitweb_check_feature('highlight');
7213 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7214 $fd = run_highlighter($fd, $highlight, $syntax)
7215 if $syntax;
7217 git_header_html(undef, $expires);
7218 my $formats_nav = '';
7219 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7220 if (defined $file_name) {
7221 if ($have_blame) {
7222 $formats_nav .=
7223 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7224 "blame") .
7225 " | ";
7227 $formats_nav .=
7228 $cgi->a({-href => href(action=>"history", -replay=>1)},
7229 "history") .
7230 " | " .
7231 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7232 "raw") .
7233 " | " .
7234 $cgi->a({-href => href(action=>"blob",
7235 hash_base=>"HEAD", file_name=>$file_name)},
7236 "HEAD");
7237 } else {
7238 $formats_nav .=
7239 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7240 "raw");
7242 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7243 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7244 } else {
7245 print "<div class=\"page_nav\">\n" .
7246 "<br/><br/></div>\n" .
7247 "<div class=\"title\">".esc_html($hash)."</div>\n";
7249 git_print_page_path($file_name, "blob", $hash_base);
7250 print "<div class=\"page_body\">\n";
7251 if ($mimetype =~ m!^image/!) {
7252 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7253 if ($file_name) {
7254 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7256 print qq! src="! .
7257 href(action=>"blob_plain", hash=>$hash,
7258 hash_base=>$hash_base, file_name=>$file_name) .
7259 qq!" />\n!;
7260 } else {
7261 my $nr;
7262 while (my $line = <$fd>) {
7263 chomp $line;
7264 $nr++;
7265 $line = untabify($line);
7266 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7267 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7268 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7271 close $fd
7272 or print "Reading blob failed.\n";
7273 print "</div>";
7274 git_footer_html();
7277 sub git_tree {
7278 if (!defined $hash_base) {
7279 $hash_base = "HEAD";
7281 if (!defined $hash) {
7282 if (defined $file_name) {
7283 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7284 } else {
7285 $hash = $hash_base;
7288 die_error(404, "No such tree") unless defined($hash);
7290 my $show_sizes = gitweb_check_feature('show-sizes');
7291 my $have_blame = gitweb_check_feature('blame');
7293 my @entries = ();
7295 local $/ = "\0";
7296 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7297 ($show_sizes ? '-l' : ()), @extra_options, $hash
7298 or die_error(500, "Open git-ls-tree failed");
7299 @entries = map { chomp; $_ } <$fd>;
7300 close $fd
7301 or die_error(404, "Reading tree failed");
7304 my $refs = git_get_references();
7305 my $ref = format_ref_marker($refs, $hash_base);
7306 git_header_html();
7307 my $basedir = '';
7308 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7309 my @views_nav = ();
7310 if (defined $file_name) {
7311 push @views_nav,
7312 $cgi->a({-href => href(action=>"history", -replay=>1)},
7313 "history"),
7314 $cgi->a({-href => href(action=>"tree",
7315 hash_base=>"HEAD", file_name=>$file_name)},
7316 "HEAD"),
7318 my $snapshot_links = format_snapshot_links($hash);
7319 if (defined $snapshot_links) {
7320 # FIXME: Should be available when we have no hash base as well.
7321 push @views_nav, $snapshot_links;
7323 git_print_page_nav('tree','', $hash_base, undef, undef,
7324 join(' | ', @views_nav));
7325 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7326 } else {
7327 undef $hash_base;
7328 print "<div class=\"page_nav\">\n";
7329 print "<br/><br/></div>\n";
7330 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7332 if (defined $file_name) {
7333 $basedir = $file_name;
7334 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7335 $basedir .= '/';
7337 git_print_page_path($file_name, 'tree', $hash_base);
7339 print "<div class=\"page_body\">\n";
7340 print "<table class=\"tree\">\n";
7341 my $alternate = 1;
7342 # '..' (top directory) link if possible
7343 if (defined $hash_base &&
7344 defined $file_name && $file_name =~ m![^/]+$!) {
7345 if ($alternate) {
7346 print "<tr class=\"dark\">\n";
7347 } else {
7348 print "<tr class=\"light\">\n";
7350 $alternate ^= 1;
7352 my $up = $file_name;
7353 $up =~ s!/?[^/]+$!!;
7354 undef $up unless $up;
7355 # based on git_print_tree_entry
7356 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7357 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7358 print '<td class="list">';
7359 print $cgi->a({-href => href(action=>"tree",
7360 hash_base=>$hash_base,
7361 file_name=>$up)},
7362 "..");
7363 print "</td>\n";
7364 print "<td class=\"link\"></td>\n";
7366 print "</tr>\n";
7368 foreach my $line (@entries) {
7369 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7371 if ($alternate) {
7372 print "<tr class=\"dark\">\n";
7373 } else {
7374 print "<tr class=\"light\">\n";
7376 $alternate ^= 1;
7378 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7380 print "</tr>\n";
7382 print "</table>\n" .
7383 "</div>";
7384 git_footer_html();
7387 sub sanitize_for_filename {
7388 my $name = shift;
7390 $name =~ s!/!-!g;
7391 $name =~ s/[^[:alnum:]_.-]//g;
7393 return $name;
7396 sub snapshot_name {
7397 my ($project, $hash) = @_;
7399 # path/to/project.git -> project
7400 # path/to/project/.git -> project
7401 my $name = to_utf8($project);
7402 $name =~ s,([^/])/*\.git$,$1,;
7403 $name = sanitize_for_filename(basename($name));
7405 my $ver = $hash;
7406 if ($hash =~ /^[0-9a-fA-F]+$/) {
7407 # shorten SHA-1 hash
7408 my $full_hash = git_get_full_hash($project, $hash);
7409 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7410 $ver = git_get_short_hash($project, $hash);
7412 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7413 # tags don't need shortened SHA-1 hash
7414 $ver = $1;
7415 } else {
7416 # branches and other need shortened SHA-1 hash
7417 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7418 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7419 my $ref_dir = (defined $1) ? $1 : '';
7420 $ver = $2;
7422 $ref_dir = sanitize_for_filename($ref_dir);
7423 # for refs neither in heads nor remotes we want to
7424 # add a ref dir to archive name
7425 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7426 $ver = $ref_dir . '-' . $ver;
7429 $ver .= '-' . git_get_short_hash($project, $hash);
7431 # special case of sanitization for filename - we change
7432 # slashes to dots instead of dashes
7433 # in case of hierarchical branch names
7434 $ver =~ s!/!.!g;
7435 $ver =~ s/[^[:alnum:]_.-]//g;
7437 # name = project-version_string
7438 $name = "$name-$ver";
7440 return wantarray ? ($name, $name) : $name;
7443 sub exit_if_unmodified_since {
7444 my ($latest_epoch) = @_;
7445 our $cgi;
7447 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7448 if (defined $if_modified) {
7449 my $since;
7450 if (eval { require HTTP::Date; 1; }) {
7451 $since = HTTP::Date::str2time($if_modified);
7452 } elsif (eval { require Time::ParseDate; 1; }) {
7453 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7455 if (defined $since && $latest_epoch <= $since) {
7456 my %latest_date = parse_date($latest_epoch);
7457 print $cgi->header(
7458 -last_modified => $latest_date{'rfc2822'},
7459 -status => '304 Not Modified');
7460 goto DONE_GITWEB;
7465 sub git_snapshot {
7466 my $format = $input_params{'snapshot_format'};
7467 if (!@snapshot_fmts) {
7468 die_error(403, "Snapshots not allowed");
7470 # default to first supported snapshot format
7471 $format ||= $snapshot_fmts[0];
7472 if ($format !~ m/^[a-z0-9]+$/) {
7473 die_error(400, "Invalid snapshot format parameter");
7474 } elsif (!exists($known_snapshot_formats{$format})) {
7475 die_error(400, "Unknown snapshot format");
7476 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7477 die_error(403, "Snapshot format not allowed");
7478 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7479 die_error(403, "Unsupported snapshot format");
7482 my $type = git_get_type("$hash^{}");
7483 if (!$type) {
7484 die_error(404, 'Object does not exist');
7485 } elsif ($type eq 'blob') {
7486 die_error(400, 'Object is not a tree-ish');
7489 my ($name, $prefix) = snapshot_name($project, $hash);
7490 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7492 my %co = parse_commit($hash);
7493 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7495 my $cmd = quote_command(
7496 git_cmd(), 'archive',
7497 "--format=$known_snapshot_formats{$format}{'format'}",
7498 "--prefix=$prefix/", $hash);
7499 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7500 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7503 $filename =~ s/(["\\])/\\$1/g;
7504 my %latest_date;
7505 if (%co) {
7506 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7509 print $cgi->header(
7510 -type => $known_snapshot_formats{$format}{'type'},
7511 -content_disposition => 'inline; filename="' . $filename . '"',
7512 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7513 -status => '200 OK');
7515 open my $fd, "-|", $cmd
7516 or die_error(500, "Execute git-archive failed");
7517 binmode STDOUT, ':raw';
7518 print <$fd>;
7519 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7520 close $fd;
7523 sub git_log_generic {
7524 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7526 my $head = git_get_head_hash($project);
7527 if (!defined $base) {
7528 $base = $head;
7530 if (!defined $page) {
7531 $page = 0;
7533 my $refs = git_get_references();
7535 my $commit_hash = $base;
7536 if (defined $parent) {
7537 $commit_hash = "$parent..$base";
7539 my @commitlist =
7540 parse_commits($commit_hash, 101, (100 * $page),
7541 defined $file_name ? ($file_name, "--full-history") : ());
7543 my $ftype;
7544 if (!defined $file_hash && defined $file_name) {
7545 # some commits could have deleted file in question,
7546 # and not have it in tree, but one of them has to have it
7547 for (my $i = 0; $i < @commitlist; $i++) {
7548 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7549 last if defined $file_hash;
7552 if (defined $file_hash) {
7553 $ftype = git_get_type($file_hash);
7555 if (defined $file_name && !defined $ftype) {
7556 die_error(500, "Unknown type of object");
7558 my %co;
7559 if (defined $file_name) {
7560 %co = parse_commit($base)
7561 or die_error(404, "Unknown commit object");
7565 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7566 my $next_link = '';
7567 if ($#commitlist >= 100) {
7568 $next_link =
7569 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7570 -accesskey => "n", -title => "Alt-n"}, "next");
7572 my $patch_max = gitweb_get_feature('patches');
7573 if ($patch_max && !defined $file_name) {
7574 if ($patch_max < 0 || @commitlist <= $patch_max) {
7575 $paging_nav .= " &sdot; " .
7576 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7577 "patches");
7581 git_header_html();
7582 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7583 if (defined $file_name) {
7584 git_print_header_div('commit', esc_html($co{'title'}), $base);
7585 } else {
7586 git_print_header_div('summary', $project)
7588 git_print_page_path($file_name, $ftype, $hash_base)
7589 if (defined $file_name);
7591 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7592 $file_name, $file_hash, $ftype);
7594 git_footer_html();
7597 sub git_log {
7598 git_log_generic('log', \&git_log_body,
7599 $hash, $hash_parent);
7602 sub git_commit {
7603 $hash ||= $hash_base || "HEAD";
7604 my %co = parse_commit($hash)
7605 or die_error(404, "Unknown commit object");
7607 my $parent = $co{'parent'};
7608 my $parents = $co{'parents'}; # listref
7610 # we need to prepare $formats_nav before any parameter munging
7611 my $formats_nav;
7612 if (!defined $parent) {
7613 # --root commitdiff
7614 $formats_nav .= '(initial)';
7615 } elsif (@$parents == 1) {
7616 # single parent commit
7617 $formats_nav .=
7618 '(parent: ' .
7619 $cgi->a({-href => href(action=>"commit",
7620 hash=>$parent)},
7621 esc_html(substr($parent, 0, 7))) .
7622 ')';
7623 } else {
7624 # merge commit
7625 $formats_nav .=
7626 '(merge: ' .
7627 join(' ', map {
7628 $cgi->a({-href => href(action=>"commit",
7629 hash=>$_)},
7630 esc_html(substr($_, 0, 7)));
7631 } @$parents ) .
7632 ')';
7634 if (gitweb_check_feature('patches') && @$parents <= 1) {
7635 $formats_nav .= " | " .
7636 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7637 "patch");
7640 if (!defined $parent) {
7641 $parent = "--root";
7643 my @difftree;
7644 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7645 @diff_opts,
7646 (@$parents <= 1 ? $parent : '-c'),
7647 $hash, "--"
7648 or die_error(500, "Open git-diff-tree failed");
7649 @difftree = map { chomp; $_ } <$fd>;
7650 close $fd or die_error(404, "Reading git-diff-tree failed");
7652 # non-textual hash id's can be cached
7653 my $expires;
7654 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7655 $expires = "+1d";
7657 my $refs = git_get_references();
7658 my $ref = format_ref_marker($refs, $co{'id'});
7660 git_header_html(undef, $expires);
7661 git_print_page_nav('commit', '',
7662 $hash, $co{'tree'}, $hash,
7663 $formats_nav);
7665 if (defined $co{'parent'}) {
7666 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7667 } else {
7668 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7670 print "<div class=\"title_text\">\n" .
7671 "<table class=\"object_header\">\n";
7672 git_print_authorship_rows(\%co);
7673 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7674 print "<tr>" .
7675 "<td>tree</td>" .
7676 "<td class=\"sha1\">" .
7677 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7678 class => "list"}, $co{'tree'}) .
7679 "</td>" .
7680 "<td class=\"link\">" .
7681 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7682 "tree");
7683 my $snapshot_links = format_snapshot_links($hash);
7684 if (defined $snapshot_links) {
7685 print " | " . $snapshot_links;
7687 print "</td>" .
7688 "</tr>\n";
7690 foreach my $par (@$parents) {
7691 print "<tr>" .
7692 "<td>parent</td>" .
7693 "<td class=\"sha1\">" .
7694 $cgi->a({-href => href(action=>"commit", hash=>$par),
7695 class => "list"}, $par) .
7696 "</td>" .
7697 "<td class=\"link\">" .
7698 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7699 " | " .
7700 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7701 "</td>" .
7702 "</tr>\n";
7704 print "</table>".
7705 "</div>\n";
7707 print "<div class=\"page_body\">\n";
7708 git_print_log($co{'comment'});
7709 print "</div>\n";
7711 git_difftree_body(\@difftree, $hash, @$parents);
7713 git_footer_html();
7716 sub git_object {
7717 # object is defined by:
7718 # - hash or hash_base alone
7719 # - hash_base and file_name
7720 my $type;
7722 # - hash or hash_base alone
7723 if ($hash || ($hash_base && !defined $file_name)) {
7724 my $object_id = $hash || $hash_base;
7726 open my $fd, "-|", quote_command(
7727 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7728 or die_error(404, "Object does not exist");
7729 $type = <$fd>;
7730 chomp $type;
7731 close $fd
7732 or die_error(404, "Object does not exist");
7734 # - hash_base and file_name
7735 } elsif ($hash_base && defined $file_name) {
7736 $file_name =~ s,/+$,,;
7738 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7739 or die_error(404, "Base object does not exist");
7741 # here errors should not happen
7742 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7743 or die_error(500, "Open git-ls-tree failed");
7744 my $line = <$fd>;
7745 close $fd;
7747 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7748 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7749 die_error(404, "File or directory for given base does not exist");
7751 $type = $2;
7752 $hash = $3;
7753 } else {
7754 die_error(400, "Not enough information to find object");
7757 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7758 hash=>$hash, hash_base=>$hash_base,
7759 file_name=>$file_name),
7760 -status => '302 Found');
7763 sub git_blobdiff {
7764 my $format = shift || 'html';
7765 my $diff_style = $input_params{'diff_style'} || 'inline';
7767 my $fd;
7768 my @difftree;
7769 my %diffinfo;
7770 my $expires;
7772 # preparing $fd and %diffinfo for git_patchset_body
7773 # new style URI
7774 if (defined $hash_base && defined $hash_parent_base) {
7775 if (defined $file_name) {
7776 # read raw output
7777 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7778 $hash_parent_base, $hash_base,
7779 "--", (defined $file_parent ? $file_parent : ()), $file_name
7780 or die_error(500, "Open git-diff-tree failed");
7781 @difftree = map { chomp; $_ } <$fd>;
7782 close $fd
7783 or die_error(404, "Reading git-diff-tree failed");
7784 @difftree
7785 or die_error(404, "Blob diff not found");
7787 } elsif (defined $hash &&
7788 $hash =~ /[0-9a-fA-F]{40}/) {
7789 # try to find filename from $hash
7791 # read filtered raw output
7792 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7793 $hash_parent_base, $hash_base, "--"
7794 or die_error(500, "Open git-diff-tree failed");
7795 @difftree =
7796 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7797 # $hash == to_id
7798 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7799 map { chomp; $_ } <$fd>;
7800 close $fd
7801 or die_error(404, "Reading git-diff-tree failed");
7802 @difftree
7803 or die_error(404, "Blob diff not found");
7805 } else {
7806 die_error(400, "Missing one of the blob diff parameters");
7809 if (@difftree > 1) {
7810 die_error(400, "Ambiguous blob diff specification");
7813 %diffinfo = parse_difftree_raw_line($difftree[0]);
7814 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7815 $file_name ||= $diffinfo{'to_file'};
7817 $hash_parent ||= $diffinfo{'from_id'};
7818 $hash ||= $diffinfo{'to_id'};
7820 # non-textual hash id's can be cached
7821 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7822 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7823 $expires = '+1d';
7826 # open patch output
7827 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7828 '-p', ($format eq 'html' ? "--full-index" : ()),
7829 $hash_parent_base, $hash_base,
7830 "--", (defined $file_parent ? $file_parent : ()), $file_name
7831 or die_error(500, "Open git-diff-tree failed");
7834 # old/legacy style URI -- not generated anymore since 1.4.3.
7835 if (!%diffinfo) {
7836 die_error('404 Not Found', "Missing one of the blob diff parameters")
7839 # header
7840 if ($format eq 'html') {
7841 my $formats_nav =
7842 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7843 "raw");
7844 $formats_nav .= diff_style_nav($diff_style);
7845 git_header_html(undef, $expires);
7846 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7847 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7848 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7849 } else {
7850 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7851 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7853 if (defined $file_name) {
7854 git_print_page_path($file_name, "blob", $hash_base);
7855 } else {
7856 print "<div class=\"page_path\"></div>\n";
7859 } elsif ($format eq 'plain') {
7860 print $cgi->header(
7861 -type => 'text/plain',
7862 -charset => 'utf-8',
7863 -expires => $expires,
7864 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7866 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7868 } else {
7869 die_error(400, "Unknown blobdiff format");
7872 # patch
7873 if ($format eq 'html') {
7874 print "<div class=\"page_body\">\n";
7876 git_patchset_body($fd, $diff_style,
7877 [ \%diffinfo ], $hash_base, $hash_parent_base);
7878 close $fd;
7880 print "</div>\n"; # class="page_body"
7881 git_footer_html();
7883 } else {
7884 while (my $line = <$fd>) {
7885 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7886 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7888 print $line;
7890 last if $line =~ m!^\+\+\+!;
7892 local $/ = undef;
7893 print <$fd>;
7894 close $fd;
7898 sub git_blobdiff_plain {
7899 git_blobdiff('plain');
7902 # assumes that it is added as later part of already existing navigation,
7903 # so it returns "| foo | bar" rather than just "foo | bar"
7904 sub diff_style_nav {
7905 my ($diff_style, $is_combined) = @_;
7906 $diff_style ||= 'inline';
7908 return "" if ($is_combined);
7910 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7911 my %styles = @styles;
7912 @styles =
7913 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7915 return join '',
7916 map { " | ".$_ }
7917 map {
7918 $_ eq $diff_style ? $styles{$_} :
7919 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7920 } @styles;
7923 sub git_commitdiff {
7924 my %params = @_;
7925 my $format = $params{-format} || 'html';
7926 my $diff_style = $input_params{'diff_style'} || 'inline';
7928 my ($patch_max) = gitweb_get_feature('patches');
7929 if ($format eq 'patch') {
7930 die_error(403, "Patch view not allowed") unless $patch_max;
7933 $hash ||= $hash_base || "HEAD";
7934 my %co = parse_commit($hash)
7935 or die_error(404, "Unknown commit object");
7937 # choose format for commitdiff for merge
7938 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7939 $hash_parent = '--cc';
7941 # we need to prepare $formats_nav before almost any parameter munging
7942 my $formats_nav;
7943 if ($format eq 'html') {
7944 $formats_nav =
7945 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7946 "raw");
7947 if ($patch_max && @{$co{'parents'}} <= 1) {
7948 $formats_nav .= " | " .
7949 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7950 "patch");
7952 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7954 if (defined $hash_parent &&
7955 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7956 # commitdiff with two commits given
7957 my $hash_parent_short = $hash_parent;
7958 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7959 $hash_parent_short = substr($hash_parent, 0, 7);
7961 $formats_nav .=
7962 ' (from';
7963 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7964 if ($co{'parents'}[$i] eq $hash_parent) {
7965 $formats_nav .= ' parent ' . ($i+1);
7966 last;
7969 $formats_nav .= ': ' .
7970 $cgi->a({-href => href(-replay=>1,
7971 hash=>$hash_parent, hash_base=>undef)},
7972 esc_html($hash_parent_short)) .
7973 ')';
7974 } elsif (!$co{'parent'}) {
7975 # --root commitdiff
7976 $formats_nav .= ' (initial)';
7977 } elsif (scalar @{$co{'parents'}} == 1) {
7978 # single parent commit
7979 $formats_nav .=
7980 ' (parent: ' .
7981 $cgi->a({-href => href(-replay=>1,
7982 hash=>$co{'parent'}, hash_base=>undef)},
7983 esc_html(substr($co{'parent'}, 0, 7))) .
7984 ')';
7985 } else {
7986 # merge commit
7987 if ($hash_parent eq '--cc') {
7988 $formats_nav .= ' | ' .
7989 $cgi->a({-href => href(-replay=>1,
7990 hash=>$hash, hash_parent=>'-c')},
7991 'combined');
7992 } else { # $hash_parent eq '-c'
7993 $formats_nav .= ' | ' .
7994 $cgi->a({-href => href(-replay=>1,
7995 hash=>$hash, hash_parent=>'--cc')},
7996 'compact');
7998 $formats_nav .=
7999 ' (merge: ' .
8000 join(' ', map {
8001 $cgi->a({-href => href(-replay=>1,
8002 hash=>$_, hash_base=>undef)},
8003 esc_html(substr($_, 0, 7)));
8004 } @{$co{'parents'}} ) .
8005 ')';
8009 my $hash_parent_param = $hash_parent;
8010 if (!defined $hash_parent_param) {
8011 # --cc for multiple parents, --root for parentless
8012 $hash_parent_param =
8013 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
8016 # read commitdiff
8017 my $fd;
8018 my @difftree;
8019 if ($format eq 'html') {
8020 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8021 "--no-commit-id", "--patch-with-raw", "--full-index",
8022 $hash_parent_param, $hash, "--"
8023 or die_error(500, "Open git-diff-tree failed");
8025 while (my $line = <$fd>) {
8026 chomp $line;
8027 # empty line ends raw part of diff-tree output
8028 last unless $line;
8029 push @difftree, scalar parse_difftree_raw_line($line);
8032 } elsif ($format eq 'plain') {
8033 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8034 '-p', $hash_parent_param, $hash, "--"
8035 or die_error(500, "Open git-diff-tree failed");
8036 } elsif ($format eq 'patch') {
8037 # For commit ranges, we limit the output to the number of
8038 # patches specified in the 'patches' feature.
8039 # For single commits, we limit the output to a single patch,
8040 # diverging from the git-format-patch default.
8041 my @commit_spec = ();
8042 if ($hash_parent) {
8043 if ($patch_max > 0) {
8044 push @commit_spec, "-$patch_max";
8046 push @commit_spec, '-n', "$hash_parent..$hash";
8047 } else {
8048 if ($params{-single}) {
8049 push @commit_spec, '-1';
8050 } else {
8051 if ($patch_max > 0) {
8052 push @commit_spec, "-$patch_max";
8054 push @commit_spec, "-n";
8056 push @commit_spec, '--root', $hash;
8058 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
8059 '--encoding=utf8', '--stdout', @commit_spec
8060 or die_error(500, "Open git-format-patch failed");
8061 } else {
8062 die_error(400, "Unknown commitdiff format");
8065 # non-textual hash id's can be cached
8066 my $expires;
8067 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8068 $expires = "+1d";
8071 # write commit message
8072 if ($format eq 'html') {
8073 my $refs = git_get_references();
8074 my $ref = format_ref_marker($refs, $co{'id'});
8076 git_header_html(undef, $expires);
8077 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
8078 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
8079 print "<div class=\"title_text\">\n" .
8080 "<table class=\"object_header\">\n";
8081 git_print_authorship_rows(\%co);
8082 print "</table>".
8083 "</div>\n";
8084 print "<div class=\"page_body\">\n";
8085 if (@{$co{'comment'}} > 1) {
8086 print "<div class=\"log\">\n";
8087 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
8088 print "</div>\n"; # class="log"
8091 } elsif ($format eq 'plain') {
8092 my $refs = git_get_references("tags");
8093 my $tagname = git_get_rev_name_tags($hash);
8094 my $filename = basename($project) . "-$hash.patch";
8096 print $cgi->header(
8097 -type => 'text/plain',
8098 -charset => 'utf-8',
8099 -expires => $expires,
8100 -content_disposition => 'inline; filename="' . "$filename" . '"');
8101 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8102 print "From: " . to_utf8($co{'author'}) . "\n";
8103 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8104 print "Subject: " . to_utf8($co{'title'}) . "\n";
8106 print "X-Git-Tag: $tagname\n" if $tagname;
8107 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8109 foreach my $line (@{$co{'comment'}}) {
8110 print to_utf8($line) . "\n";
8112 print "---\n\n";
8113 } elsif ($format eq 'patch') {
8114 my $filename = basename($project) . "-$hash.patch";
8116 print $cgi->header(
8117 -type => 'text/plain',
8118 -charset => 'utf-8',
8119 -expires => $expires,
8120 -content_disposition => 'inline; filename="' . "$filename" . '"');
8123 # write patch
8124 if ($format eq 'html') {
8125 my $use_parents = !defined $hash_parent ||
8126 $hash_parent eq '-c' || $hash_parent eq '--cc';
8127 git_difftree_body(\@difftree, $hash,
8128 $use_parents ? @{$co{'parents'}} : $hash_parent);
8129 print "<br/>\n";
8131 git_patchset_body($fd, $diff_style,
8132 \@difftree, $hash,
8133 $use_parents ? @{$co{'parents'}} : $hash_parent);
8134 close $fd;
8135 print "</div>\n"; # class="page_body"
8136 git_footer_html();
8138 } elsif ($format eq 'plain') {
8139 local $/ = undef;
8140 print <$fd>;
8141 close $fd
8142 or print "Reading git-diff-tree failed\n";
8143 } elsif ($format eq 'patch') {
8144 local $/ = undef;
8145 print <$fd>;
8146 close $fd
8147 or print "Reading git-format-patch failed\n";
8151 sub git_commitdiff_plain {
8152 git_commitdiff(-format => 'plain');
8155 # format-patch-style patches
8156 sub git_patch {
8157 git_commitdiff(-format => 'patch', -single => 1);
8160 sub git_patches {
8161 git_commitdiff(-format => 'patch');
8164 sub git_history {
8165 git_log_generic('history', \&git_history_body,
8166 $hash_base, $hash_parent_base,
8167 $file_name, $hash);
8170 sub git_search {
8171 $searchtype ||= 'commit';
8173 # check if appropriate features are enabled
8174 gitweb_check_feature('search')
8175 or die_error(403, "Search is disabled");
8176 if ($searchtype eq 'pickaxe') {
8177 # pickaxe may take all resources of your box and run for several minutes
8178 # with every query - so decide by yourself how public you make this feature
8179 gitweb_check_feature('pickaxe')
8180 or die_error(403, "Pickaxe search is disabled");
8182 if ($searchtype eq 'grep') {
8183 # grep search might be potentially CPU-intensive, too
8184 gitweb_check_feature('grep')
8185 or die_error(403, "Grep search is disabled");
8188 if (!defined $searchtext) {
8189 die_error(400, "Text field is empty");
8191 if (!defined $hash) {
8192 $hash = git_get_head_hash($project);
8194 my %co = parse_commit($hash);
8195 if (!%co) {
8196 die_error(404, "Unknown commit object");
8198 if (!defined $page) {
8199 $page = 0;
8202 if ($searchtype eq 'commit' ||
8203 $searchtype eq 'author' ||
8204 $searchtype eq 'committer') {
8205 git_search_message(%co);
8206 } elsif ($searchtype eq 'pickaxe') {
8207 git_search_changes(%co);
8208 } elsif ($searchtype eq 'grep') {
8209 git_search_files(%co);
8210 } else {
8211 die_error(400, "Unknown search type");
8215 sub git_search_help {
8216 git_header_html();
8217 git_print_page_nav('','', $hash,$hash,$hash);
8218 print <<EOT;
8219 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8220 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8221 the pattern entered is recognized as the POSIX extended
8222 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8223 insensitive).</p>
8224 <dl>
8225 <dt><b>commit</b></dt>
8226 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8228 my $have_grep = gitweb_check_feature('grep');
8229 if ($have_grep) {
8230 print <<EOT;
8231 <dt><b>grep</b></dt>
8232 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8233 a different one) are searched for the given pattern. On large trees, this search can take
8234 a while and put some strain on the server, so please use it with some consideration. Note that
8235 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8236 case-sensitive.</dd>
8239 print <<EOT;
8240 <dt><b>author</b></dt>
8241 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8242 <dt><b>committer</b></dt>
8243 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8245 my $have_pickaxe = gitweb_check_feature('pickaxe');
8246 if ($have_pickaxe) {
8247 print <<EOT;
8248 <dt><b>pickaxe</b></dt>
8249 <dd>All commits that caused the string to appear or disappear from any file (changes that
8250 added, removed or "modified" the string) will be listed. This search can take a while and
8251 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8252 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8255 print "</dl>\n";
8256 git_footer_html();
8259 sub git_shortlog {
8260 git_log_generic('shortlog', \&git_shortlog_body,
8261 $hash, $hash_parent);
8264 ## ......................................................................
8265 ## feeds (RSS, Atom; OPML)
8267 sub git_feed {
8268 my $format = shift || 'atom';
8269 my $have_blame = gitweb_check_feature('blame');
8271 # Atom: http://www.atomenabled.org/developers/syndication/
8272 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8273 if ($format ne 'rss' && $format ne 'atom') {
8274 die_error(400, "Unknown web feed format");
8277 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8278 my $head = $hash || 'HEAD';
8279 my @commitlist = parse_commits($head, 150, 0, $file_name);
8281 my %latest_commit;
8282 my %latest_date;
8283 my $content_type = "application/$format+xml";
8284 if (defined $cgi->http('HTTP_ACCEPT') &&
8285 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8286 # browser (feed reader) prefers text/xml
8287 $content_type = 'text/xml';
8289 if (defined($commitlist[0])) {
8290 %latest_commit = %{$commitlist[0]};
8291 my $latest_epoch = $latest_commit{'committer_epoch'};
8292 exit_if_unmodified_since($latest_epoch);
8293 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8295 print $cgi->header(
8296 -type => $content_type,
8297 -charset => 'utf-8',
8298 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8299 -status => '200 OK');
8301 # Optimization: skip generating the body if client asks only
8302 # for Last-Modified date.
8303 return if ($cgi->request_method() eq 'HEAD');
8305 # header variables
8306 my $title = "$site_name - $project/$action";
8307 my $feed_type = 'log';
8308 if (defined $hash) {
8309 $title .= " - '$hash'";
8310 $feed_type = 'branch log';
8311 if (defined $file_name) {
8312 $title .= " :: $file_name";
8313 $feed_type = 'history';
8315 } elsif (defined $file_name) {
8316 $title .= " - $file_name";
8317 $feed_type = 'history';
8319 $title .= " $feed_type";
8320 $title = esc_html($title);
8321 my $descr = git_get_project_description($project);
8322 if (defined $descr) {
8323 $descr = esc_html($descr);
8324 } else {
8325 $descr = "$project " .
8326 ($format eq 'rss' ? 'RSS' : 'Atom') .
8327 " feed";
8329 my $owner = git_get_project_owner($project);
8330 $owner = esc_html($owner);
8332 #header
8333 my $alt_url;
8334 if (defined $file_name) {
8335 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8336 } elsif (defined $hash) {
8337 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8338 } else {
8339 $alt_url = href(-full=>1, action=>"summary");
8341 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8342 if ($format eq 'rss') {
8343 print <<XML;
8344 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8345 <channel>
8347 print "<title>$title</title>\n" .
8348 "<link>$alt_url</link>\n" .
8349 "<description>$descr</description>\n" .
8350 "<language>en</language>\n" .
8351 # project owner is responsible for 'editorial' content
8352 "<managingEditor>$owner</managingEditor>\n";
8353 if (defined $logo || defined $favicon) {
8354 # prefer the logo to the favicon, since RSS
8355 # doesn't allow both
8356 my $img = esc_url($logo || $favicon);
8357 print "<image>\n" .
8358 "<url>$img</url>\n" .
8359 "<title>$title</title>\n" .
8360 "<link>$alt_url</link>\n" .
8361 "</image>\n";
8363 if (%latest_date) {
8364 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8365 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8367 print "<generator>gitweb v.$version/$git_version</generator>\n";
8368 } elsif ($format eq 'atom') {
8369 print <<XML;
8370 <feed xmlns="http://www.w3.org/2005/Atom">
8372 print "<title>$title</title>\n" .
8373 "<subtitle>$descr</subtitle>\n" .
8374 '<link rel="alternate" type="text/html" href="' .
8375 $alt_url . '" />' . "\n" .
8376 '<link rel="self" type="' . $content_type . '" href="' .
8377 $cgi->self_url() . '" />' . "\n" .
8378 "<id>" . href(-full=>1) . "</id>\n" .
8379 # use project owner for feed author
8380 "<author><name>$owner</name></author>\n";
8381 if (defined $favicon) {
8382 print "<icon>" . esc_url($favicon) . "</icon>\n";
8384 if (defined $logo) {
8385 # not twice as wide as tall: 72 x 27 pixels
8386 print "<logo>" . esc_url($logo) . "</logo>\n";
8388 if (! %latest_date) {
8389 # dummy date to keep the feed valid until commits trickle in:
8390 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8391 } else {
8392 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8394 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8397 # contents
8398 for (my $i = 0; $i <= $#commitlist; $i++) {
8399 my %co = %{$commitlist[$i]};
8400 my $commit = $co{'id'};
8401 # we read 150, we always show 30 and the ones more recent than 48 hours
8402 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8403 last;
8405 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8407 # get list of changed files
8408 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8409 $co{'parent'} || "--root",
8410 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8411 or next;
8412 my @difftree = map { chomp; $_ } <$fd>;
8413 close $fd
8414 or next;
8416 # print element (entry, item)
8417 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8418 if ($format eq 'rss') {
8419 print "<item>\n" .
8420 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8421 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8422 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8423 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8424 "<link>$co_url</link>\n" .
8425 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8426 "<content:encoded>" .
8427 "<![CDATA[\n";
8428 } elsif ($format eq 'atom') {
8429 print "<entry>\n" .
8430 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8431 "<updated>$cd{'iso-8601'}</updated>\n" .
8432 "<author>\n" .
8433 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8434 if ($co{'author_email'}) {
8435 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8437 print "</author>\n" .
8438 # use committer for contributor
8439 "<contributor>\n" .
8440 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8441 if ($co{'committer_email'}) {
8442 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8444 print "</contributor>\n" .
8445 "<published>$cd{'iso-8601'}</published>\n" .
8446 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8447 "<id>$co_url</id>\n" .
8448 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8449 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8451 my $comment = $co{'comment'};
8452 print "<pre>\n";
8453 foreach my $line (@$comment) {
8454 $line = esc_html($line);
8455 print "$line\n";
8457 print "</pre><ul>\n";
8458 foreach my $difftree_line (@difftree) {
8459 my %difftree = parse_difftree_raw_line($difftree_line);
8460 next if !$difftree{'from_id'};
8462 my $file = $difftree{'file'} || $difftree{'to_file'};
8464 print "<li>" .
8465 "[" .
8466 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8467 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8468 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8469 file_name=>$file, file_parent=>$difftree{'from_file'}),
8470 -title => "diff"}, 'D');
8471 if ($have_blame) {
8472 print $cgi->a({-href => href(-full=>1, action=>"blame",
8473 file_name=>$file, hash_base=>$commit),
8474 -title => "blame"}, 'B');
8476 # if this is not a feed of a file history
8477 if (!defined $file_name || $file_name ne $file) {
8478 print $cgi->a({-href => href(-full=>1, action=>"history",
8479 file_name=>$file, hash=>$commit),
8480 -title => "history"}, 'H');
8482 $file = esc_path($file);
8483 print "] ".
8484 "$file</li>\n";
8486 if ($format eq 'rss') {
8487 print "</ul>]]>\n" .
8488 "</content:encoded>\n" .
8489 "</item>\n";
8490 } elsif ($format eq 'atom') {
8491 print "</ul>\n</div>\n" .
8492 "</content>\n" .
8493 "</entry>\n";
8497 # end of feed
8498 if ($format eq 'rss') {
8499 print "</channel>\n</rss>\n";
8500 } elsif ($format eq 'atom') {
8501 print "</feed>\n";
8505 sub git_rss {
8506 git_feed('rss');
8509 sub git_atom {
8510 git_feed('atom');
8513 sub git_opml {
8514 my @list = git_get_projects_list($project_filter, $strict_export);
8515 if (!@list) {
8516 die_error(404, "No projects found");
8519 print $cgi->header(
8520 -type => 'text/xml',
8521 -charset => 'utf-8',
8522 -content_disposition => 'inline; filename="opml.xml"');
8524 my $title = esc_html($site_name);
8525 my $filter = " within subdirectory ";
8526 if (defined $project_filter) {
8527 $filter .= esc_html($project_filter);
8528 } else {
8529 $filter = "";
8531 print <<XML;
8532 <?xml version="1.0" encoding="utf-8"?>
8533 <opml version="1.0">
8534 <head>
8535 <title>$title OPML Export$filter</title>
8536 </head>
8537 <body>
8538 <outline text="git RSS feeds">
8541 foreach my $pr (@list) {
8542 my %proj = %$pr;
8543 my $head = git_get_head_hash($proj{'path'});
8544 if (!defined $head) {
8545 next;
8547 $git_dir = "$projectroot/$proj{'path'}";
8548 my %co = parse_commit($head);
8549 if (!%co) {
8550 next;
8553 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8554 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8555 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8556 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8558 print <<XML;
8559 </outline>
8560 </body>
8561 </opml>