Merge commit 'refs/top-bases/t/projlist-cache/caching' into t/projlist-cache/caching
[git/gitweb.git] / gitweb / gitweb.perl
blob01f0f7dacb58ee2ab1ba102db3514a10f4ccda45
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 print "</div>\n";
5565 # entry for given @keys needs filling if at least one of keys in list
5566 # is not present in %$project_info
5567 sub project_info_needs_filling {
5568 my ($project_info, @keys) = @_;
5570 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5571 foreach my $key (@keys) {
5572 if (!exists $project_info->{$key}) {
5573 return 1;
5576 return;
5579 sub git_retrieve_cache_file {
5580 my $cache_file = shift;
5582 use Storable qw(retrieve);
5584 if ((my $dump = eval { retrieve($cache_file) })) {
5585 return $$dump[1] if
5586 ref($dump) eq 'ARRAY' &&
5587 @$dump == 2 &&
5588 $$dump[0] eq GITWEB_CACHE_FORMAT &&
5589 ref($$dump[1]) eq 'ARRAY';
5591 return undef;
5594 sub git_store_cache_file {
5595 my ($cache_file, $projlist) = @_;
5597 use File::Basename qw(dirname);
5598 use POSIX qw(:fcntl_h);
5599 use Storable qw(store_fd);
5601 my $cache_d = dirname($cache_file);
5602 my $mask = umask();
5603 umask($mask & ~0070) if $cache_grpshared;
5604 if ((-d $cache_d || mkdir($cache_d, $cache_grpshared ? 0770 : 0700)) &&
5605 sysopen(my $fd, "$cache_file.lock", O_WRONLY|O_CREAT|O_EXCL, $cache_grpshared ? 0660 : 0600)) {
5606 store_fd([GITWEB_CACHE_FORMAT, $projlist], $fd);
5607 close $fd;
5608 rename "$cache_file.lock", $cache_file;
5610 umask($mask) if $cache_grpshared;
5613 # fills project list info (age, description, owner, category, forks, etc.)
5614 # for each project in the list, removing invalid projects from
5615 # returned list, or fill only specified info.
5617 # Invalid projects are removed from the returned list if and only if you
5618 # ask 'age' or 'age_string' to be filled, because they are the only fields
5619 # that run unconditionally git command that requires repository, and
5620 # therefore do always check if project repository is invalid.
5622 # USAGE:
5623 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5624 # ensures that 'descr_long' and 'ctags' fields are filled
5625 # * @project_list = fill_project_list_info(\@project_list)
5626 # ensures that all fields are filled (and invalid projects removed)
5628 # NOTE: modifies $projlist, but does not remove entries from it
5629 sub fill_project_list_info {
5630 my ($projlist, @wanted_keys) = @_;
5632 use File::stat;
5634 my $cache_file = "$cache_dir/$projlist_cache_name";
5636 my @projects;
5637 my $stale = 0;
5638 my $now = time();
5639 my $cache_mtime;
5640 if ($projlist_cache_lifetime && -f $cache_file) {
5641 $cache_mtime = stat($cache_file)->mtime;
5643 if (defined $cache_mtime && # caching is on and $cache_file exists
5644 $cache_mtime + $projlist_cache_lifetime*60 > $now &&
5645 (my $dump = git_retrieve_cache_file($cache_file))) {
5646 # Cache hit.
5647 $stale = $now - $cache_mtime;
5648 @projects = @$dump;
5650 } else { # Cache miss.
5651 if (defined $cache_mtime) {
5652 # Postpone timeout by two minutes so that we get
5653 # enough time to do our job, or to be more exact
5654 # make cache expire after two minutes from now.
5655 my $time = $now - $projlist_cache_lifetime*60 + 120;
5656 utime $time, $time, $cache_file;
5658 @projects = fill_project_list_info_uncached($projlist, @wanted_keys);
5659 git_store_cache_file($cache_file, \@projects) if $projlist_cache_lifetime;
5662 if ($projlist_cache_lifetime && $stale > 0) {
5663 print "<div class=\"stale_info\">Cached version (${stale}s old)</div>\n";
5666 return @projects;
5669 sub fill_project_list_info_uncached {
5670 my ($projlist, @wanted_keys) = @_;
5671 my @projects;
5672 my $filter_set = sub { return @_; };
5673 if (@wanted_keys) {
5674 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5675 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5678 my $show_ctags = gitweb_check_feature('ctags');
5679 PROJECT:
5680 foreach my $pr (@$projlist) {
5681 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5682 my (@activity) = git_get_last_activity($pr->{'path'});
5683 unless (@activity) {
5684 next PROJECT;
5686 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5688 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5689 my $descr = git_get_project_description($pr->{'path'}) || "";
5690 $descr = to_utf8($descr);
5691 $pr->{'descr_long'} = $descr;
5692 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5694 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5695 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5697 if ($show_ctags &&
5698 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5699 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5701 if ($projects_list_group_categories &&
5702 project_info_needs_filling($pr, $filter_set->('category'))) {
5703 my $cat = git_get_project_category($pr->{'path'}) ||
5704 $project_list_default_category;
5705 $pr->{'category'} = to_utf8($cat);
5708 push @projects, $pr;
5711 return @projects;
5714 sub sort_projects_list {
5715 my ($projlist, $order) = @_;
5717 sub order_str {
5718 my $key = shift;
5719 return sub { $a->{$key} cmp $b->{$key} };
5722 sub order_num_then_undef {
5723 my $key = shift;
5724 return sub {
5725 defined $a->{$key} ?
5726 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5727 (defined $b->{$key} ? 1 : 0)
5731 my %orderings = (
5732 project => order_str('path'),
5733 descr => order_str('descr_long'),
5734 owner => order_str('owner'),
5735 age => order_num_then_undef('age'),
5738 my $ordering = $orderings{$order};
5739 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5742 # returns a hash of categories, containing the list of project
5743 # belonging to each category
5744 sub build_projlist_by_category {
5745 my ($projlist, $from, $to) = @_;
5746 my %categories;
5748 $from = 0 unless defined $from;
5749 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5751 for (my $i = $from; $i <= $to; $i++) {
5752 my $pr = $projlist->[$i];
5753 push @{$categories{ $pr->{'category'} }}, $pr;
5756 return wantarray ? %categories : \%categories;
5759 # print 'sort by' <th> element, generating 'sort by $name' replay link
5760 # if that order is not selected
5761 sub print_sort_th {
5762 print format_sort_th(@_);
5765 sub format_sort_th {
5766 my ($name, $order, $header) = @_;
5767 my $sort_th = "";
5768 $header ||= ucfirst($name);
5770 if ($order eq $name) {
5771 $sort_th .= "<th>$header</th>\n";
5772 } else {
5773 $sort_th .= "<th>" .
5774 $cgi->a({-href => href(-replay=>1, order=>$name),
5775 -class => "header"}, $header) .
5776 "</th>\n";
5779 return $sort_th;
5782 sub git_project_list_rows {
5783 my ($projlist, $from, $to, $check_forks) = @_;
5785 $from = 0 unless defined $from;
5786 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5788 my $alternate = 1;
5789 for (my $i = $from; $i <= $to; $i++) {
5790 my $pr = $projlist->[$i];
5792 if ($alternate) {
5793 print "<tr class=\"dark\">\n";
5794 } else {
5795 print "<tr class=\"light\">\n";
5797 $alternate ^= 1;
5799 if ($check_forks) {
5800 print "<td>";
5801 if ($pr->{'forks'}) {
5802 my $nforks = scalar @{$pr->{'forks'}};
5803 if ($nforks > 0) {
5804 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5805 -title => "$nforks forks"}, "+");
5806 } else {
5807 print $cgi->span({-title => "$nforks forks"}, "+");
5810 print "</td>\n";
5812 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5813 -class => "list"},
5814 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5815 "</td>\n" .
5816 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5817 -class => "list",
5818 -title => $pr->{'descr_long'}},
5819 $search_regexp
5820 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5821 $pr->{'descr'}, $search_regexp)
5822 : esc_html($pr->{'descr'})) .
5823 "</td>\n";
5824 unless ($omit_owner) {
5825 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5827 unless ($omit_age_column) {
5828 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5829 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5831 print"<td class=\"link\">" .
5832 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5833 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5834 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5835 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5836 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5837 "</td>\n" .
5838 "</tr>\n";
5842 sub git_project_list_body {
5843 # actually uses global variable $project
5844 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action) = @_;
5845 my @projects = @$projlist;
5847 my $check_forks = gitweb_check_feature('forks');
5848 my $show_ctags = gitweb_check_feature('ctags');
5849 my $tagfilter = $show_ctags ? $input_params{'ctag_filter'} : undef;
5850 $check_forks = undef
5851 if ($tagfilter || $search_regexp);
5853 # filtering out forks before filling info allows to do less work
5854 @projects = filter_forks_from_projects_list(\@projects)
5855 if ($check_forks);
5856 # search_projects_list pre-fills required info
5857 @projects = search_projects_list(\@projects,
5858 'search_regexp' => $search_regexp,
5859 'tagfilter' => $tagfilter)
5860 if ($tagfilter || $search_regexp);
5861 # fill the rest
5862 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5863 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5864 push @all_fields, 'owner' unless($omit_owner);
5865 @projects = fill_project_list_info(\@projects, @all_fields);
5867 $order ||= $default_projects_order;
5868 $from = 0 unless defined $from;
5869 $to = $#projects if (!defined $to || $#projects < $to);
5871 # short circuit
5872 if ($from > $to) {
5873 print "<center>\n".
5874 "<b>No such projects found</b><br />\n".
5875 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5876 "</center>\n<br />\n";
5877 return;
5880 @projects = sort_projects_list(\@projects, $order);
5882 if ($show_ctags) {
5883 my $ctags = git_gather_all_ctags(\@projects);
5884 my $cloud = git_populate_project_tagcloud($ctags, $ctags_action||'project_list');
5885 print git_show_project_tagcloud($cloud, 64);
5888 print "<table class=\"project_list\">\n";
5889 unless ($no_header) {
5890 print "<tr>\n";
5891 if ($check_forks) {
5892 print "<th></th>\n";
5894 print_sort_th('project', $order, 'Project');
5895 print_sort_th('descr', $order, 'Description');
5896 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5897 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5898 print "<th></th>\n" . # for links
5899 "</tr>\n";
5902 if ($projects_list_group_categories) {
5903 # only display categories with projects in the $from-$to window
5904 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5905 my %categories = build_projlist_by_category(\@projects, $from, $to);
5906 foreach my $cat (sort keys %categories) {
5907 unless ($cat eq "") {
5908 print "<tr>\n";
5909 if ($check_forks) {
5910 print "<td></td>\n";
5912 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5913 print "</tr>\n";
5916 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5918 } else {
5919 git_project_list_rows(\@projects, $from, $to, $check_forks);
5922 if (defined $extra) {
5923 print "<tr>\n";
5924 if ($check_forks) {
5925 print "<td></td>\n";
5927 print "<td colspan=\"5\">$extra</td>\n" .
5928 "</tr>\n";
5930 print "</table>\n";
5933 sub git_log_body {
5934 # uses global variable $project
5935 my ($commitlist, $from, $to, $refs, $extra) = @_;
5937 $from = 0 unless defined $from;
5938 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5940 for (my $i = 0; $i <= $to; $i++) {
5941 my %co = %{$commitlist->[$i]};
5942 next if !%co;
5943 my $commit = $co{'id'};
5944 my $ref = format_ref_marker($refs, $commit);
5945 git_print_header_div('commit',
5946 "<span class=\"age\">$co{'age_string'}</span>" .
5947 esc_html($co{'title'}) . $ref,
5948 $commit);
5949 print "<div class=\"title_text\">\n" .
5950 "<div class=\"log_link\">\n" .
5951 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5952 " | " .
5953 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5954 " | " .
5955 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5956 "<br/>\n" .
5957 "</div>\n";
5958 git_print_authorship(\%co, -tag => 'span');
5959 print "<br/>\n</div>\n";
5961 print "<div class=\"log_body\">\n";
5962 git_print_log($co{'comment'}, -final_empty_line=> 1);
5963 print "</div>\n";
5965 if ($extra) {
5966 print "<div class=\"page_nav\">\n";
5967 print "$extra\n";
5968 print "</div>\n";
5972 sub git_shortlog_body {
5973 # uses global variable $project
5974 my ($commitlist, $from, $to, $refs, $extra) = @_;
5976 $from = 0 unless defined $from;
5977 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5979 print "<table class=\"shortlog\">\n";
5980 my $alternate = 1;
5981 for (my $i = $from; $i <= $to; $i++) {
5982 my %co = %{$commitlist->[$i]};
5983 my $commit = $co{'id'};
5984 my $ref = format_ref_marker($refs, $commit);
5985 if ($alternate) {
5986 print "<tr class=\"dark\">\n";
5987 } else {
5988 print "<tr class=\"light\">\n";
5990 $alternate ^= 1;
5991 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5992 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5993 format_author_html('td', \%co, 10) . "<td>";
5994 print format_subject_html($co{'title'}, $co{'title_short'},
5995 href(action=>"commit", hash=>$commit), $ref);
5996 print "</td>\n" .
5997 "<td class=\"link\">" .
5998 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5999 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
6000 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
6001 my $snapshot_links = format_snapshot_links($commit);
6002 if (defined $snapshot_links) {
6003 print " | " . $snapshot_links;
6005 print "</td>\n" .
6006 "</tr>\n";
6008 if (defined $extra) {
6009 print "<tr>\n" .
6010 "<td colspan=\"4\">$extra</td>\n" .
6011 "</tr>\n";
6013 print "</table>\n";
6016 sub git_history_body {
6017 # Warning: assumes constant type (blob or tree) during history
6018 my ($commitlist, $from, $to, $refs, $extra,
6019 $file_name, $file_hash, $ftype) = @_;
6021 $from = 0 unless defined $from;
6022 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
6024 print "<table class=\"history\">\n";
6025 my $alternate = 1;
6026 for (my $i = $from; $i <= $to; $i++) {
6027 my %co = %{$commitlist->[$i]};
6028 if (!%co) {
6029 next;
6031 my $commit = $co{'id'};
6033 my $ref = format_ref_marker($refs, $commit);
6035 if ($alternate) {
6036 print "<tr class=\"dark\">\n";
6037 } else {
6038 print "<tr class=\"light\">\n";
6040 $alternate ^= 1;
6041 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6042 # shortlog: format_author_html('td', \%co, 10)
6043 format_author_html('td', \%co, 15, 3) . "<td>";
6044 # originally git_history used chop_str($co{'title'}, 50)
6045 print format_subject_html($co{'title'}, $co{'title_short'},
6046 href(action=>"commit", hash=>$commit), $ref);
6047 print "</td>\n" .
6048 "<td class=\"link\">" .
6049 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
6050 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
6052 if ($ftype eq 'blob') {
6053 my $blob_current = $file_hash;
6054 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6055 if (defined $blob_current && defined $blob_parent &&
6056 $blob_current ne $blob_parent) {
6057 print " | " .
6058 $cgi->a({-href => href(action=>"blobdiff",
6059 hash=>$blob_current, hash_parent=>$blob_parent,
6060 hash_base=>$hash_base, hash_parent_base=>$commit,
6061 file_name=>$file_name)},
6062 "diff to current");
6065 print "</td>\n" .
6066 "</tr>\n";
6068 if (defined $extra) {
6069 print "<tr>\n" .
6070 "<td colspan=\"4\">$extra</td>\n" .
6071 "</tr>\n";
6073 print "</table>\n";
6076 sub git_tags_body {
6077 # uses global variable $project
6078 my ($taglist, $from, $to, $extra) = @_;
6079 $from = 0 unless defined $from;
6080 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6082 print "<table class=\"tags\">\n";
6083 my $alternate = 1;
6084 for (my $i = $from; $i <= $to; $i++) {
6085 my $entry = $taglist->[$i];
6086 my %tag = %$entry;
6087 my $comment = $tag{'subject'};
6088 my $comment_short;
6089 if (defined $comment) {
6090 $comment_short = chop_str($comment, 30, 5);
6092 if ($alternate) {
6093 print "<tr class=\"dark\">\n";
6094 } else {
6095 print "<tr class=\"light\">\n";
6097 $alternate ^= 1;
6098 if (defined $tag{'age'}) {
6099 print "<td><i>$tag{'age'}</i></td>\n";
6100 } else {
6101 print "<td></td>\n";
6103 print "<td>" .
6104 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6105 -class => "list name"}, esc_html($tag{'name'})) .
6106 "</td>\n" .
6107 "<td>";
6108 if (defined $comment) {
6109 print format_subject_html($comment, $comment_short,
6110 href(action=>"tag", hash=>$tag{'id'}));
6112 print "</td>\n" .
6113 "<td class=\"selflink\">";
6114 if ($tag{'type'} eq "tag") {
6115 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6116 } else {
6117 print "&nbsp;";
6119 print "</td>\n" .
6120 "<td class=\"link\">" . " | " .
6121 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6122 if ($tag{'reftype'} eq "commit") {
6123 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6124 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6125 } elsif ($tag{'reftype'} eq "blob") {
6126 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6128 print "</td>\n" .
6129 "</tr>";
6131 if (defined $extra) {
6132 print "<tr>\n" .
6133 "<td colspan=\"5\">$extra</td>\n" .
6134 "</tr>\n";
6136 print "</table>\n";
6139 sub git_heads_body {
6140 # uses global variable $project
6141 my ($headlist, $head_at, $from, $to, $extra) = @_;
6142 $from = 0 unless defined $from;
6143 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6145 print "<table class=\"heads\">\n";
6146 my $alternate = 1;
6147 for (my $i = $from; $i <= $to; $i++) {
6148 my $entry = $headlist->[$i];
6149 my %ref = %$entry;
6150 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6151 if ($alternate) {
6152 print "<tr class=\"dark\">\n";
6153 } else {
6154 print "<tr class=\"light\">\n";
6156 $alternate ^= 1;
6157 print "<td><i>$ref{'age'}</i></td>\n" .
6158 ($curr ? "<td class=\"current_head\">" : "<td>") .
6159 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6160 -class => "list name"},esc_html($ref{'name'})) .
6161 "</td>\n" .
6162 "<td class=\"link\">" .
6163 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6164 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6165 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6166 "</td>\n" .
6167 "</tr>";
6169 if (defined $extra) {
6170 print "<tr>\n" .
6171 "<td colspan=\"3\">$extra</td>\n" .
6172 "</tr>\n";
6174 print "</table>\n";
6177 # Display a single remote block
6178 sub git_remote_block {
6179 my ($remote, $rdata, $limit, $head) = @_;
6181 my $heads = $rdata->{'heads'};
6182 my $fetch = $rdata->{'fetch'};
6183 my $push = $rdata->{'push'};
6185 my $urls_table = "<table class=\"projects_list\">\n" ;
6187 if (defined $fetch) {
6188 if ($fetch eq $push) {
6189 $urls_table .= format_repo_url("URL", $fetch);
6190 } else {
6191 $urls_table .= format_repo_url("Fetch URL", $fetch);
6192 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6194 } elsif (defined $push) {
6195 $urls_table .= format_repo_url("Push URL", $push);
6196 } else {
6197 $urls_table .= format_repo_url("", "No remote URL");
6200 $urls_table .= "</table>\n";
6202 my $dots;
6203 if (defined $limit && $limit < @$heads) {
6204 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6207 print $urls_table;
6208 git_heads_body($heads, $head, 0, $limit, $dots);
6211 # Display a list of remote names with the respective fetch and push URLs
6212 sub git_remotes_list {
6213 my ($remotedata, $limit) = @_;
6214 print "<table class=\"heads\">\n";
6215 my $alternate = 1;
6216 my @remotes = sort keys %$remotedata;
6218 my $limited = $limit && $limit < @remotes;
6220 $#remotes = $limit - 1 if $limited;
6222 while (my $remote = shift @remotes) {
6223 my $rdata = $remotedata->{$remote};
6224 my $fetch = $rdata->{'fetch'};
6225 my $push = $rdata->{'push'};
6226 if ($alternate) {
6227 print "<tr class=\"dark\">\n";
6228 } else {
6229 print "<tr class=\"light\">\n";
6231 $alternate ^= 1;
6232 print "<td>" .
6233 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6234 -class=> "list name"},esc_html($remote)) .
6235 "</td>";
6236 print "<td class=\"link\">" .
6237 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6238 " | " .
6239 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6240 "</td>";
6242 print "</tr>\n";
6245 if ($limited) {
6246 print "<tr>\n" .
6247 "<td colspan=\"3\">" .
6248 $cgi->a({-href => href(action=>"remotes")}, "...") .
6249 "</td>\n" . "</tr>\n";
6252 print "</table>";
6255 # Display remote heads grouped by remote, unless there are too many
6256 # remotes, in which case we only display the remote names
6257 sub git_remotes_body {
6258 my ($remotedata, $limit, $head) = @_;
6259 if ($limit and $limit < keys %$remotedata) {
6260 git_remotes_list($remotedata, $limit);
6261 } else {
6262 fill_remote_heads($remotedata);
6263 while (my ($remote, $rdata) = each %$remotedata) {
6264 git_print_section({-class=>"remote", -id=>$remote},
6265 ["remotes", $remote, $remote], sub {
6266 git_remote_block($remote, $rdata, $limit, $head);
6272 sub git_search_message {
6273 my %co = @_;
6275 my $greptype;
6276 if ($searchtype eq 'commit') {
6277 $greptype = "--grep=";
6278 } elsif ($searchtype eq 'author') {
6279 $greptype = "--author=";
6280 } elsif ($searchtype eq 'committer') {
6281 $greptype = "--committer=";
6283 $greptype .= $searchtext;
6284 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6285 $greptype, '--regexp-ignore-case',
6286 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6288 my $paging_nav = '';
6289 if ($page > 0) {
6290 $paging_nav .=
6291 $cgi->a({-href => href(-replay=>1, page=>undef)},
6292 "first") .
6293 " &sdot; " .
6294 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6295 -accesskey => "p", -title => "Alt-p"}, "prev");
6296 } else {
6297 $paging_nav .= "first &sdot; prev";
6299 my $next_link = '';
6300 if ($#commitlist >= 100) {
6301 $next_link =
6302 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6303 -accesskey => "n", -title => "Alt-n"}, "next");
6304 $paging_nav .= " &sdot; $next_link";
6305 } else {
6306 $paging_nav .= " &sdot; next";
6309 git_header_html();
6311 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6312 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6313 if ($page == 0 && !@commitlist) {
6314 print "<p>No match.</p>\n";
6315 } else {
6316 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6319 git_footer_html();
6322 sub git_search_changes {
6323 my %co = @_;
6325 local $/ = "\n";
6326 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6327 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6328 ($search_use_regexp ? '--pickaxe-regex' : ())
6329 or die_error(500, "Open git-log failed");
6331 git_header_html();
6333 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6334 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6336 print "<table class=\"pickaxe search\">\n";
6337 my $alternate = 1;
6338 undef %co;
6339 my @files;
6340 while (my $line = <$fd>) {
6341 chomp $line;
6342 next unless $line;
6344 my %set = parse_difftree_raw_line($line);
6345 if (defined $set{'commit'}) {
6346 # finish previous commit
6347 if (%co) {
6348 print "</td>\n" .
6349 "<td class=\"link\">" .
6350 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6351 "commit") .
6352 " | " .
6353 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6354 hash_base=>$co{'id'})},
6355 "tree") .
6356 "</td>\n" .
6357 "</tr>\n";
6360 if ($alternate) {
6361 print "<tr class=\"dark\">\n";
6362 } else {
6363 print "<tr class=\"light\">\n";
6365 $alternate ^= 1;
6366 %co = parse_commit($set{'commit'});
6367 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6368 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6369 "<td><i>$author</i></td>\n" .
6370 "<td>" .
6371 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6372 -class => "list subject"},
6373 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6374 } elsif (defined $set{'to_id'}) {
6375 next if ($set{'to_id'} =~ m/^0{40}$/);
6377 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6378 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6379 -class => "list"},
6380 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6381 "<br/>\n";
6384 close $fd;
6386 # finish last commit (warning: repetition!)
6387 if (%co) {
6388 print "</td>\n" .
6389 "<td class=\"link\">" .
6390 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6391 "commit") .
6392 " | " .
6393 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6394 hash_base=>$co{'id'})},
6395 "tree") .
6396 "</td>\n" .
6397 "</tr>\n";
6400 print "</table>\n";
6402 git_footer_html();
6405 sub git_search_files {
6406 my %co = @_;
6408 local $/ = "\n";
6409 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6410 $search_use_regexp ? ('-E', '-i') : '-F',
6411 $searchtext, $co{'tree'}
6412 or die_error(500, "Open git-grep failed");
6414 git_header_html();
6416 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6417 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6419 print "<table class=\"grep_search\">\n";
6420 my $alternate = 1;
6421 my $matches = 0;
6422 my $lastfile = '';
6423 my $file_href;
6424 while (my $line = <$fd>) {
6425 chomp $line;
6426 my ($file, $lno, $ltext, $binary);
6427 last if ($matches++ > 1000);
6428 if ($line =~ /^Binary file (.+) matches$/) {
6429 $file = $1;
6430 $binary = 1;
6431 } else {
6432 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6433 $file =~ s/^$co{'tree'}://;
6435 if ($file ne $lastfile) {
6436 $lastfile and print "</td></tr>\n";
6437 if ($alternate++) {
6438 print "<tr class=\"dark\">\n";
6439 } else {
6440 print "<tr class=\"light\">\n";
6442 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6443 file_name=>$file);
6444 print "<td class=\"list\">".
6445 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6446 print "</td><td>\n";
6447 $lastfile = $file;
6449 if ($binary) {
6450 print "<div class=\"binary\">Binary file</div>\n";
6451 } else {
6452 $ltext = untabify($ltext);
6453 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6454 $ltext = esc_html($1, -nbsp=>1);
6455 $ltext .= '<span class="match">';
6456 $ltext .= esc_html($2, -nbsp=>1);
6457 $ltext .= '</span>';
6458 $ltext .= esc_html($3, -nbsp=>1);
6459 } else {
6460 $ltext = esc_html($ltext, -nbsp=>1);
6462 print "<div class=\"pre\">" .
6463 $cgi->a({-href => $file_href.'#l'.$lno,
6464 -class => "linenr"}, sprintf('%4i', $lno)) .
6465 ' ' . $ltext . "</div>\n";
6468 if ($lastfile) {
6469 print "</td></tr>\n";
6470 if ($matches > 1000) {
6471 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6473 } else {
6474 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6476 close $fd;
6478 print "</table>\n";
6480 git_footer_html();
6483 sub git_search_grep_body {
6484 my ($commitlist, $from, $to, $extra) = @_;
6485 $from = 0 unless defined $from;
6486 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6488 print "<table class=\"commit_search\">\n";
6489 my $alternate = 1;
6490 for (my $i = $from; $i <= $to; $i++) {
6491 my %co = %{$commitlist->[$i]};
6492 if (!%co) {
6493 next;
6495 my $commit = $co{'id'};
6496 if ($alternate) {
6497 print "<tr class=\"dark\">\n";
6498 } else {
6499 print "<tr class=\"light\">\n";
6501 $alternate ^= 1;
6502 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6503 format_author_html('td', \%co, 15, 5) .
6504 "<td>" .
6505 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6506 -class => "list subject"},
6507 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6508 my $comment = $co{'comment'};
6509 foreach my $line (@$comment) {
6510 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6511 my ($lead, $match, $trail) = ($1, $2, $3);
6512 $match = chop_str($match, 70, 5, 'center');
6513 my $contextlen = int((80 - length($match))/2);
6514 $contextlen = 30 if ($contextlen > 30);
6515 $lead = chop_str($lead, $contextlen, 10, 'left');
6516 $trail = chop_str($trail, $contextlen, 10, 'right');
6518 $lead = esc_html($lead);
6519 $match = esc_html($match);
6520 $trail = esc_html($trail);
6522 print "$lead<span class=\"match\">$match</span>$trail<br />";
6525 print "</td>\n" .
6526 "<td class=\"link\">" .
6527 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6528 " | " .
6529 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6530 " | " .
6531 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6532 print "</td>\n" .
6533 "</tr>\n";
6535 if (defined $extra) {
6536 print "<tr>\n" .
6537 "<td colspan=\"3\">$extra</td>\n" .
6538 "</tr>\n";
6540 print "</table>\n";
6543 ## ======================================================================
6544 ## ======================================================================
6545 ## actions
6547 sub git_project_list_load {
6548 my $empty_list_ok = shift;
6549 my $order = $input_params{'order'};
6550 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6551 die_error(400, "Unknown order parameter");
6554 my @list = git_get_projects_list($project_filter, $strict_export);
6555 if (!@list) {
6556 die_error(404, "No projects found") unless $empty_list_ok;
6559 return (\@list, $order);
6562 sub git_frontpage {
6563 my ($projlist, $order);
6564 ($projlist, $order) = git_project_list_load(1) if not $frontpage_no_project_list;
6566 my $limit = '';
6567 if ($project_filter) {
6568 $limit = " in '$project_filter/'";
6570 my $browse_link = "<p class=\"projectlist_link\">" .
6571 $cgi->a({-href => href(project => undef, searchtext => undef,
6572 action=>'project_list', project_filter => $project_filter)},
6573 esc_html("Browse all projects$limit")) . "</p>\n";
6575 git_header_html();
6576 if (defined $home_text && -f $home_text) {
6577 print "<div class=\"index_include\">\n";
6578 insert_file($home_text);
6579 print "</div>\n";
6581 git_project_search_form($searchtext, $search_use_regexp);
6582 if (not $frontpage_no_project_list) {
6583 print $browse_link;
6584 git_project_list_body($projlist, $order);
6585 } else {
6586 my $show_ctags = gitweb_check_feature('ctags');
6587 if ($frontpage_no_project_list == 1 and $show_ctags) {
6588 my @projects = git_get_projects_list($project_filter, $strict_export);
6589 @projects = filter_forks_from_projects_list(\@projects) if gitweb_check_feature('forks');
6590 @projects = fill_project_list_info(\@projects, 'ctags');
6591 my $ctags = git_gather_all_ctags(\@projects);
6592 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6593 print git_show_project_tagcloud($cloud, 64);
6595 print $browse_link;
6597 git_footer_html();
6600 sub git_project_list {
6601 my ($projlist, $order) = git_project_list_load();
6602 git_header_html();
6603 git_project_search_form();
6604 git_project_list_body($projlist, $order);
6605 git_footer_html();
6608 sub git_forks {
6609 my $order = $input_params{'order'};
6610 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6611 die_error(400, "Unknown order parameter");
6614 my $filter = $project;
6615 $filter =~ s/\.git$//;
6616 my @list = git_get_projects_list($filter);
6617 if (!@list) {
6618 die_error(404, "No forks found");
6621 git_header_html();
6622 git_print_page_nav('','');
6623 git_print_header_div('summary', "$project forks");
6624 git_project_list_body(\@list, $order, undef, undef, undef, undef, 'forks');
6625 git_footer_html();
6628 sub git_project_index {
6629 my @projects = git_get_projects_list($project_filter, $strict_export);
6630 if (!@projects) {
6631 die_error(404, "No projects found");
6634 print $cgi->header(
6635 -type => 'text/plain',
6636 -charset => 'utf-8',
6637 -content_disposition => 'inline; filename="index.aux"');
6639 foreach my $pr (@projects) {
6640 if (!exists $pr->{'owner'}) {
6641 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6644 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6645 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6646 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6647 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6648 $path =~ s/ /\+/g;
6649 $owner =~ s/ /\+/g;
6651 print "$path $owner\n";
6655 sub git_summary {
6656 my $descr = git_get_project_description($project) || "none";
6657 my %co = parse_commit("HEAD");
6658 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6659 my $head = $co{'id'};
6660 my $remote_heads = gitweb_check_feature('remote_heads');
6662 my $owner = git_get_project_owner($project);
6664 my $refs = git_get_references();
6665 # These get_*_list functions return one more to allow us to see if
6666 # there are more ...
6667 my @taglist = git_get_tags_list(16);
6668 my @headlist = git_get_heads_list(16);
6669 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6670 my @forklist;
6671 my $check_forks = gitweb_check_feature('forks');
6673 if ($check_forks) {
6674 # find forks of a project
6675 my $filter = $project;
6676 $filter =~ s/\.git$//;
6677 @forklist = git_get_projects_list($filter);
6678 # filter out forks of forks
6679 @forklist = filter_forks_from_projects_list(\@forklist)
6680 if (@forklist);
6683 git_header_html();
6684 git_print_page_nav('summary','', $head);
6686 print "<div class=\"title\">&nbsp;</div>\n";
6687 print "<table class=\"projects_list\">\n" .
6688 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6689 if ($owner and not $omit_owner) {
6690 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6692 if (defined $cd{'rfc2822'}) {
6693 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6694 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6697 # use per project git URL list in $projectroot/$project/cloneurl
6698 # or make project git URL from git base URL and project name
6699 my $url_tag = "URL";
6700 my @url_list = git_get_project_url_list($project);
6701 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6702 foreach my $git_url (@url_list) {
6703 next unless $git_url;
6704 print format_repo_url($url_tag, $git_url);
6705 $url_tag = "";
6708 # Tag cloud
6709 my $show_ctags = gitweb_check_feature('ctags');
6710 if ($show_ctags) {
6711 my $ctags = git_get_project_ctags($project);
6712 if (%$ctags || $show_ctags !~ /^\d+$/) {
6713 # without ability to add tags, don't show if there are none
6714 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6715 print "<tr id=\"metadata_ctags\">" .
6716 "<td style=\"vertical-align:middle\">content tags<br />";
6717 print "</td>\n<td>" unless %$ctags;
6718 print "<form action=\"$show_ctags\" method=\"post\">" .
6719 "<input type=\"hidden\" name=\"p\" value=\"$project\"/>" .
6720 "add: <input type=\"text\" name=\"t\" size=\"10\" /></form>"
6721 unless $show_ctags =~ /^\d+$/;
6722 print "</td>\n<td>" if %$ctags;
6723 print git_show_project_tagcloud($cloud, 48)."</td>" .
6724 "</tr>\n";
6728 print "</table>\n";
6730 # If XSS prevention is on, we don't include README.html.
6731 # TODO: Allow a readme in some safe format.
6732 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6733 print "<div class=\"title\">readme</div>\n" .
6734 "<div class=\"readme\">\n";
6735 insert_file("$projectroot/$project/README.html");
6736 print "\n</div>\n"; # class="readme"
6739 # we need to request one more than 16 (0..15) to check if
6740 # those 16 are all
6741 my @commitlist = $head ? parse_commits($head, 17) : ();
6742 if (@commitlist) {
6743 git_print_header_div('shortlog');
6744 git_shortlog_body(\@commitlist, 0, 15, $refs,
6745 $#commitlist <= 15 ? undef :
6746 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6749 if (@taglist) {
6750 git_print_header_div('tags');
6751 git_tags_body(\@taglist, 0, 15,
6752 $#taglist <= 15 ? undef :
6753 $cgi->a({-href => href(action=>"tags")}, "..."));
6756 if (@headlist) {
6757 git_print_header_div('heads');
6758 git_heads_body(\@headlist, $head, 0, 15,
6759 $#headlist <= 15 ? undef :
6760 $cgi->a({-href => href(action=>"heads")}, "..."));
6763 if (%remotedata) {
6764 git_print_header_div('remotes');
6765 git_remotes_body(\%remotedata, 15, $head);
6768 if (@forklist) {
6769 git_print_header_div('forks');
6770 git_project_list_body(\@forklist, 'age', 0, 15,
6771 $#forklist <= 15 ? undef :
6772 $cgi->a({-href => href(action=>"forks")}, "..."),
6773 'no_header', 'forks');
6776 git_footer_html();
6779 sub git_tag {
6780 my %tag = parse_tag($hash);
6782 if (! %tag) {
6783 die_error(404, "Unknown tag object");
6786 my $head = git_get_head_hash($project);
6787 git_header_html();
6788 git_print_page_nav('','', $head,undef,$head);
6789 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6790 print "<div class=\"title_text\">\n" .
6791 "<table class=\"object_header\">\n" .
6792 "<tr>\n" .
6793 "<td>object</td>\n" .
6794 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6795 $tag{'object'}) . "</td>\n" .
6796 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6797 $tag{'type'}) . "</td>\n" .
6798 "</tr>\n";
6799 if (defined($tag{'author'})) {
6800 git_print_authorship_rows(\%tag, 'author');
6802 print "</table>\n\n" .
6803 "</div>\n";
6804 print "<div class=\"page_body\">";
6805 my $comment = $tag{'comment'};
6806 foreach my $line (@$comment) {
6807 chomp $line;
6808 print esc_html($line, -nbsp=>1) . "<br/>\n";
6810 print "</div>\n";
6811 git_footer_html();
6814 sub git_blame_common {
6815 my $format = shift || 'porcelain';
6816 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6817 $format = 'incremental';
6818 $action = 'blame_incremental'; # for page title etc
6821 # permissions
6822 gitweb_check_feature('blame')
6823 or die_error(403, "Blame view not allowed");
6825 # error checking
6826 die_error(400, "No file name given") unless $file_name;
6827 $hash_base ||= git_get_head_hash($project);
6828 die_error(404, "Couldn't find base commit") unless $hash_base;
6829 my %co = parse_commit($hash_base)
6830 or die_error(404, "Commit not found");
6831 my $ftype = "blob";
6832 if (!defined $hash) {
6833 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6834 or die_error(404, "Error looking up file");
6835 } else {
6836 $ftype = git_get_type($hash);
6837 if ($ftype !~ "blob") {
6838 die_error(400, "Object is not a blob");
6842 my $fd;
6843 if ($format eq 'incremental') {
6844 # get file contents (as base)
6845 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6846 or die_error(500, "Open git-cat-file failed");
6847 } elsif ($format eq 'data') {
6848 # run git-blame --incremental
6849 open $fd, "-|", git_cmd(), "blame", "--incremental",
6850 $hash_base, "--", $file_name
6851 or die_error(500, "Open git-blame --incremental failed");
6852 } else {
6853 # run git-blame --porcelain
6854 open $fd, "-|", git_cmd(), "blame", '-p',
6855 $hash_base, '--', $file_name
6856 or die_error(500, "Open git-blame --porcelain failed");
6858 binmode $fd, ':utf8';
6860 # incremental blame data returns early
6861 if ($format eq 'data') {
6862 print $cgi->header(
6863 -type=>"text/plain", -charset => "utf-8",
6864 -status=> "200 OK");
6865 local $| = 1; # output autoflush
6866 while (my $line = <$fd>) {
6867 print to_utf8($line);
6869 close $fd
6870 or print "ERROR $!\n";
6872 print 'END';
6873 if (defined $t0 && gitweb_check_feature('timed')) {
6874 print ' '.
6875 tv_interval($t0, [ gettimeofday() ]).
6876 ' '.$number_of_git_cmds;
6878 print "\n";
6880 return;
6883 # page header
6884 git_header_html();
6885 my $formats_nav =
6886 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6887 "blob") .
6888 " | ";
6889 if ($format eq 'incremental') {
6890 $formats_nav .=
6891 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6892 "blame") . " (non-incremental)";
6893 } else {
6894 $formats_nav .=
6895 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6896 "blame") . " (incremental)";
6898 $formats_nav .=
6899 " | " .
6900 $cgi->a({-href => href(action=>"history", -replay=>1)},
6901 "history") .
6902 " | " .
6903 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6904 "HEAD");
6905 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6906 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6907 git_print_page_path($file_name, $ftype, $hash_base);
6909 # page body
6910 if ($format eq 'incremental') {
6911 print "<noscript>\n<div class=\"error\"><center><b>\n".
6912 "This page requires JavaScript to run.\n Use ".
6913 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6914 'this page').
6915 " instead.\n".
6916 "</b></center></div>\n</noscript>\n";
6918 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6921 print qq!<div class="page_body">\n!;
6922 print qq!<div id="progress_info">... / ...</div>\n!
6923 if ($format eq 'incremental');
6924 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6925 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6926 qq!<thead>\n!.
6927 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6928 qq!</thead>\n!.
6929 qq!<tbody>\n!;
6931 my @rev_color = qw(light dark);
6932 my $num_colors = scalar(@rev_color);
6933 my $current_color = 0;
6935 if ($format eq 'incremental') {
6936 my $color_class = $rev_color[$current_color];
6938 #contents of a file
6939 my $linenr = 0;
6940 LINE:
6941 while (my $line = <$fd>) {
6942 chomp $line;
6943 $linenr++;
6945 print qq!<tr id="l$linenr" class="$color_class">!.
6946 qq!<td class="sha1"><a href=""> </a></td>!.
6947 qq!<td class="linenr">!.
6948 qq!<a class="linenr" href="">$linenr</a></td>!;
6949 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6950 print qq!</tr>\n!;
6953 } else { # porcelain, i.e. ordinary blame
6954 my %metainfo = (); # saves information about commits
6956 # blame data
6957 LINE:
6958 while (my $line = <$fd>) {
6959 chomp $line;
6960 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6961 # no <lines in group> for subsequent lines in group of lines
6962 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6963 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6964 if (!exists $metainfo{$full_rev}) {
6965 $metainfo{$full_rev} = { 'nprevious' => 0 };
6967 my $meta = $metainfo{$full_rev};
6968 my $data;
6969 while ($data = <$fd>) {
6970 chomp $data;
6971 last if ($data =~ s/^\t//); # contents of line
6972 if ($data =~ /^(\S+)(?: (.*))?$/) {
6973 $meta->{$1} = $2 unless exists $meta->{$1};
6975 if ($data =~ /^previous /) {
6976 $meta->{'nprevious'}++;
6979 my $short_rev = substr($full_rev, 0, 8);
6980 my $author = $meta->{'author'};
6981 my %date =
6982 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6983 my $date = $date{'iso-tz'};
6984 if ($group_size) {
6985 $current_color = ($current_color + 1) % $num_colors;
6987 my $tr_class = $rev_color[$current_color];
6988 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6989 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6990 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6991 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6992 if ($group_size) {
6993 print "<td class=\"sha1\"";
6994 print " title=\"". esc_html($author) . ", $date\"";
6995 print " rowspan=\"$group_size\"" if ($group_size > 1);
6996 print ">";
6997 print $cgi->a({-href => href(action=>"commit",
6998 hash=>$full_rev,
6999 file_name=>$file_name)},
7000 esc_html($short_rev));
7001 if ($group_size >= 2) {
7002 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
7003 if (@author_initials) {
7004 print "<br />" .
7005 esc_html(join('', @author_initials));
7006 # or join('.', ...)
7009 print "</td>\n";
7011 # 'previous' <sha1 of parent commit> <filename at commit>
7012 if (exists $meta->{'previous'} &&
7013 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
7014 $meta->{'parent'} = $1;
7015 $meta->{'file_parent'} = unquote($2);
7017 my $linenr_commit =
7018 exists($meta->{'parent'}) ?
7019 $meta->{'parent'} : $full_rev;
7020 my $linenr_filename =
7021 exists($meta->{'file_parent'}) ?
7022 $meta->{'file_parent'} : unquote($meta->{'filename'});
7023 my $blamed = href(action => 'blame',
7024 file_name => $linenr_filename,
7025 hash_base => $linenr_commit);
7026 print "<td class=\"linenr\">";
7027 print $cgi->a({ -href => "$blamed#l$orig_lineno",
7028 -class => "linenr" },
7029 esc_html($lineno));
7030 print "</td>";
7031 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
7032 print "</tr>\n";
7033 } # end while
7037 # footer
7038 print "</tbody>\n".
7039 "</table>\n"; # class="blame"
7040 print "</div>\n"; # class="blame_body"
7041 close $fd
7042 or print "Reading blob failed\n";
7044 git_footer_html();
7047 sub git_blame {
7048 git_blame_common();
7051 sub git_blame_incremental {
7052 git_blame_common('incremental');
7055 sub git_blame_data {
7056 git_blame_common('data');
7059 sub git_tags {
7060 my $head = git_get_head_hash($project);
7061 git_header_html();
7062 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
7063 git_print_header_div('summary', $project);
7065 my @tagslist = git_get_tags_list();
7066 if (@tagslist) {
7067 git_tags_body(\@tagslist);
7069 git_footer_html();
7072 sub git_heads {
7073 my $head = git_get_head_hash($project);
7074 git_header_html();
7075 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
7076 git_print_header_div('summary', $project);
7078 my @headslist = git_get_heads_list();
7079 if (@headslist) {
7080 git_heads_body(\@headslist, $head);
7082 git_footer_html();
7085 # used both for single remote view and for list of all the remotes
7086 sub git_remotes {
7087 gitweb_check_feature('remote_heads')
7088 or die_error(403, "Remote heads view is disabled");
7090 my $head = git_get_head_hash($project);
7091 my $remote = $input_params{'hash'};
7093 my $remotedata = git_get_remotes_list($remote);
7094 die_error(500, "Unable to get remote information") unless defined $remotedata;
7096 unless (%$remotedata) {
7097 die_error(404, defined $remote ?
7098 "Remote $remote not found" :
7099 "No remotes found");
7102 git_header_html(undef, undef, -action_extra => $remote);
7103 git_print_page_nav('', '', $head, undef, $head,
7104 format_ref_views($remote ? '' : 'remotes'));
7106 fill_remote_heads($remotedata);
7107 if (defined $remote) {
7108 git_print_header_div('remotes', "$remote remote for $project");
7109 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7110 } else {
7111 git_print_header_div('summary', "$project remotes");
7112 git_remotes_body($remotedata, undef, $head);
7115 git_footer_html();
7118 sub git_blob_plain {
7119 my $type = shift;
7120 my $expires;
7122 if (!defined $hash) {
7123 if (defined $file_name) {
7124 my $base = $hash_base || git_get_head_hash($project);
7125 $hash = git_get_hash_by_path($base, $file_name, "blob")
7126 or die_error(404, "Cannot find file");
7127 } else {
7128 die_error(400, "No file name defined");
7130 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7131 # blobs defined by non-textual hash id's can be cached
7132 $expires = "+1d";
7135 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7136 or die_error(500, "Open git-cat-file blob '$hash' failed");
7138 # content-type (can include charset)
7139 $type = blob_contenttype($fd, $file_name, $type);
7141 # "save as" filename, even when no $file_name is given
7142 my $save_as = "$hash";
7143 if (defined $file_name) {
7144 $save_as = $file_name;
7145 } elsif ($type =~ m/^text\//) {
7146 $save_as .= '.txt';
7149 # With XSS prevention on, blobs of all types except a few known safe
7150 # ones are served with "Content-Disposition: attachment" to make sure
7151 # they don't run in our security domain. For certain image types,
7152 # blob view writes an <img> tag referring to blob_plain view, and we
7153 # want to be sure not to break that by serving the image as an
7154 # attachment (though Firefox 3 doesn't seem to care).
7155 my $sandbox = $prevent_xss &&
7156 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7158 # serve text/* as text/plain
7159 if ($prevent_xss &&
7160 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7161 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7162 my $rest = $1;
7163 $rest = defined $rest ? $rest : '';
7164 $type = "text/plain$rest";
7167 print $cgi->header(
7168 -type => $type,
7169 -expires => $expires,
7170 -content_disposition =>
7171 ($sandbox ? 'attachment' : 'inline')
7172 . '; filename="' . $save_as . '"');
7173 local $/ = undef;
7174 binmode STDOUT, ':raw';
7175 print <$fd>;
7176 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7177 close $fd;
7180 sub git_blob {
7181 my $expires;
7183 if (!defined $hash) {
7184 if (defined $file_name) {
7185 my $base = $hash_base || git_get_head_hash($project);
7186 $hash = git_get_hash_by_path($base, $file_name, "blob")
7187 or die_error(404, "Cannot find file");
7188 } else {
7189 die_error(400, "No file name defined");
7191 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7192 # blobs defined by non-textual hash id's can be cached
7193 $expires = "+1d";
7196 my $have_blame = gitweb_check_feature('blame');
7197 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7198 or die_error(500, "Couldn't cat $file_name, $hash");
7199 my $mimetype = blob_mimetype($fd, $file_name);
7200 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7201 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7202 close $fd;
7203 return git_blob_plain($mimetype);
7205 # we can have blame only for text/* mimetype
7206 $have_blame &&= ($mimetype =~ m!^text/!);
7208 my $highlight = gitweb_check_feature('highlight');
7209 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7210 $fd = run_highlighter($fd, $highlight, $syntax)
7211 if $syntax;
7213 git_header_html(undef, $expires);
7214 my $formats_nav = '';
7215 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7216 if (defined $file_name) {
7217 if ($have_blame) {
7218 $formats_nav .=
7219 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7220 "blame") .
7221 " | ";
7223 $formats_nav .=
7224 $cgi->a({-href => href(action=>"history", -replay=>1)},
7225 "history") .
7226 " | " .
7227 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7228 "raw") .
7229 " | " .
7230 $cgi->a({-href => href(action=>"blob",
7231 hash_base=>"HEAD", file_name=>$file_name)},
7232 "HEAD");
7233 } else {
7234 $formats_nav .=
7235 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7236 "raw");
7238 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7239 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7240 } else {
7241 print "<div class=\"page_nav\">\n" .
7242 "<br/><br/></div>\n" .
7243 "<div class=\"title\">".esc_html($hash)."</div>\n";
7245 git_print_page_path($file_name, "blob", $hash_base);
7246 print "<div class=\"page_body\">\n";
7247 if ($mimetype =~ m!^image/!) {
7248 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7249 if ($file_name) {
7250 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7252 print qq! src="! .
7253 href(action=>"blob_plain", hash=>$hash,
7254 hash_base=>$hash_base, file_name=>$file_name) .
7255 qq!" />\n!;
7256 } else {
7257 my $nr;
7258 while (my $line = <$fd>) {
7259 chomp $line;
7260 $nr++;
7261 $line = untabify($line);
7262 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7263 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7264 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7267 close $fd
7268 or print "Reading blob failed.\n";
7269 print "</div>";
7270 git_footer_html();
7273 sub git_tree {
7274 if (!defined $hash_base) {
7275 $hash_base = "HEAD";
7277 if (!defined $hash) {
7278 if (defined $file_name) {
7279 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7280 } else {
7281 $hash = $hash_base;
7284 die_error(404, "No such tree") unless defined($hash);
7286 my $show_sizes = gitweb_check_feature('show-sizes');
7287 my $have_blame = gitweb_check_feature('blame');
7289 my @entries = ();
7291 local $/ = "\0";
7292 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7293 ($show_sizes ? '-l' : ()), @extra_options, $hash
7294 or die_error(500, "Open git-ls-tree failed");
7295 @entries = map { chomp; $_ } <$fd>;
7296 close $fd
7297 or die_error(404, "Reading tree failed");
7300 my $refs = git_get_references();
7301 my $ref = format_ref_marker($refs, $hash_base);
7302 git_header_html();
7303 my $basedir = '';
7304 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7305 my @views_nav = ();
7306 if (defined $file_name) {
7307 push @views_nav,
7308 $cgi->a({-href => href(action=>"history", -replay=>1)},
7309 "history"),
7310 $cgi->a({-href => href(action=>"tree",
7311 hash_base=>"HEAD", file_name=>$file_name)},
7312 "HEAD"),
7314 my $snapshot_links = format_snapshot_links($hash);
7315 if (defined $snapshot_links) {
7316 # FIXME: Should be available when we have no hash base as well.
7317 push @views_nav, $snapshot_links;
7319 git_print_page_nav('tree','', $hash_base, undef, undef,
7320 join(' | ', @views_nav));
7321 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7322 } else {
7323 undef $hash_base;
7324 print "<div class=\"page_nav\">\n";
7325 print "<br/><br/></div>\n";
7326 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7328 if (defined $file_name) {
7329 $basedir = $file_name;
7330 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7331 $basedir .= '/';
7333 git_print_page_path($file_name, 'tree', $hash_base);
7335 print "<div class=\"page_body\">\n";
7336 print "<table class=\"tree\">\n";
7337 my $alternate = 1;
7338 # '..' (top directory) link if possible
7339 if (defined $hash_base &&
7340 defined $file_name && $file_name =~ m![^/]+$!) {
7341 if ($alternate) {
7342 print "<tr class=\"dark\">\n";
7343 } else {
7344 print "<tr class=\"light\">\n";
7346 $alternate ^= 1;
7348 my $up = $file_name;
7349 $up =~ s!/?[^/]+$!!;
7350 undef $up unless $up;
7351 # based on git_print_tree_entry
7352 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7353 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7354 print '<td class="list">';
7355 print $cgi->a({-href => href(action=>"tree",
7356 hash_base=>$hash_base,
7357 file_name=>$up)},
7358 "..");
7359 print "</td>\n";
7360 print "<td class=\"link\"></td>\n";
7362 print "</tr>\n";
7364 foreach my $line (@entries) {
7365 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7367 if ($alternate) {
7368 print "<tr class=\"dark\">\n";
7369 } else {
7370 print "<tr class=\"light\">\n";
7372 $alternate ^= 1;
7374 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7376 print "</tr>\n";
7378 print "</table>\n" .
7379 "</div>";
7380 git_footer_html();
7383 sub sanitize_for_filename {
7384 my $name = shift;
7386 $name =~ s!/!-!g;
7387 $name =~ s/[^[:alnum:]_.-]//g;
7389 return $name;
7392 sub snapshot_name {
7393 my ($project, $hash) = @_;
7395 # path/to/project.git -> project
7396 # path/to/project/.git -> project
7397 my $name = to_utf8($project);
7398 $name =~ s,([^/])/*\.git$,$1,;
7399 $name = sanitize_for_filename(basename($name));
7401 my $ver = $hash;
7402 if ($hash =~ /^[0-9a-fA-F]+$/) {
7403 # shorten SHA-1 hash
7404 my $full_hash = git_get_full_hash($project, $hash);
7405 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7406 $ver = git_get_short_hash($project, $hash);
7408 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7409 # tags don't need shortened SHA-1 hash
7410 $ver = $1;
7411 } else {
7412 # branches and other need shortened SHA-1 hash
7413 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7414 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7415 my $ref_dir = (defined $1) ? $1 : '';
7416 $ver = $2;
7418 $ref_dir = sanitize_for_filename($ref_dir);
7419 # for refs neither in heads nor remotes we want to
7420 # add a ref dir to archive name
7421 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7422 $ver = $ref_dir . '-' . $ver;
7425 $ver .= '-' . git_get_short_hash($project, $hash);
7427 # special case of sanitization for filename - we change
7428 # slashes to dots instead of dashes
7429 # in case of hierarchical branch names
7430 $ver =~ s!/!.!g;
7431 $ver =~ s/[^[:alnum:]_.-]//g;
7433 # name = project-version_string
7434 $name = "$name-$ver";
7436 return wantarray ? ($name, $name) : $name;
7439 sub exit_if_unmodified_since {
7440 my ($latest_epoch) = @_;
7441 our $cgi;
7443 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7444 if (defined $if_modified) {
7445 my $since;
7446 if (eval { require HTTP::Date; 1; }) {
7447 $since = HTTP::Date::str2time($if_modified);
7448 } elsif (eval { require Time::ParseDate; 1; }) {
7449 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7451 if (defined $since && $latest_epoch <= $since) {
7452 my %latest_date = parse_date($latest_epoch);
7453 print $cgi->header(
7454 -last_modified => $latest_date{'rfc2822'},
7455 -status => '304 Not Modified');
7456 goto DONE_GITWEB;
7461 sub git_snapshot {
7462 my $format = $input_params{'snapshot_format'};
7463 if (!@snapshot_fmts) {
7464 die_error(403, "Snapshots not allowed");
7466 # default to first supported snapshot format
7467 $format ||= $snapshot_fmts[0];
7468 if ($format !~ m/^[a-z0-9]+$/) {
7469 die_error(400, "Invalid snapshot format parameter");
7470 } elsif (!exists($known_snapshot_formats{$format})) {
7471 die_error(400, "Unknown snapshot format");
7472 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7473 die_error(403, "Snapshot format not allowed");
7474 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7475 die_error(403, "Unsupported snapshot format");
7478 my $type = git_get_type("$hash^{}");
7479 if (!$type) {
7480 die_error(404, 'Object does not exist');
7481 } elsif ($type eq 'blob') {
7482 die_error(400, 'Object is not a tree-ish');
7485 my ($name, $prefix) = snapshot_name($project, $hash);
7486 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7488 my %co = parse_commit($hash);
7489 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7491 my $cmd = quote_command(
7492 git_cmd(), 'archive',
7493 "--format=$known_snapshot_formats{$format}{'format'}",
7494 "--prefix=$prefix/", $hash);
7495 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7496 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7499 $filename =~ s/(["\\])/\\$1/g;
7500 my %latest_date;
7501 if (%co) {
7502 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7505 print $cgi->header(
7506 -type => $known_snapshot_formats{$format}{'type'},
7507 -content_disposition => 'inline; filename="' . $filename . '"',
7508 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7509 -status => '200 OK');
7511 open my $fd, "-|", $cmd
7512 or die_error(500, "Execute git-archive failed");
7513 binmode STDOUT, ':raw';
7514 print <$fd>;
7515 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7516 close $fd;
7519 sub git_log_generic {
7520 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7522 my $head = git_get_head_hash($project);
7523 if (!defined $base) {
7524 $base = $head;
7526 if (!defined $page) {
7527 $page = 0;
7529 my $refs = git_get_references();
7531 my $commit_hash = $base;
7532 if (defined $parent) {
7533 $commit_hash = "$parent..$base";
7535 my @commitlist =
7536 parse_commits($commit_hash, 101, (100 * $page),
7537 defined $file_name ? ($file_name, "--full-history") : ());
7539 my $ftype;
7540 if (!defined $file_hash && defined $file_name) {
7541 # some commits could have deleted file in question,
7542 # and not have it in tree, but one of them has to have it
7543 for (my $i = 0; $i < @commitlist; $i++) {
7544 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7545 last if defined $file_hash;
7548 if (defined $file_hash) {
7549 $ftype = git_get_type($file_hash);
7551 if (defined $file_name && !defined $ftype) {
7552 die_error(500, "Unknown type of object");
7554 my %co;
7555 if (defined $file_name) {
7556 %co = parse_commit($base)
7557 or die_error(404, "Unknown commit object");
7561 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7562 my $next_link = '';
7563 if ($#commitlist >= 100) {
7564 $next_link =
7565 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7566 -accesskey => "n", -title => "Alt-n"}, "next");
7568 my $patch_max = gitweb_get_feature('patches');
7569 if ($patch_max && !defined $file_name) {
7570 if ($patch_max < 0 || @commitlist <= $patch_max) {
7571 $paging_nav .= " &sdot; " .
7572 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7573 "patches");
7577 git_header_html();
7578 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7579 if (defined $file_name) {
7580 git_print_header_div('commit', esc_html($co{'title'}), $base);
7581 } else {
7582 git_print_header_div('summary', $project)
7584 git_print_page_path($file_name, $ftype, $hash_base)
7585 if (defined $file_name);
7587 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7588 $file_name, $file_hash, $ftype);
7590 git_footer_html();
7593 sub git_log {
7594 git_log_generic('log', \&git_log_body,
7595 $hash, $hash_parent);
7598 sub git_commit {
7599 $hash ||= $hash_base || "HEAD";
7600 my %co = parse_commit($hash)
7601 or die_error(404, "Unknown commit object");
7603 my $parent = $co{'parent'};
7604 my $parents = $co{'parents'}; # listref
7606 # we need to prepare $formats_nav before any parameter munging
7607 my $formats_nav;
7608 if (!defined $parent) {
7609 # --root commitdiff
7610 $formats_nav .= '(initial)';
7611 } elsif (@$parents == 1) {
7612 # single parent commit
7613 $formats_nav .=
7614 '(parent: ' .
7615 $cgi->a({-href => href(action=>"commit",
7616 hash=>$parent)},
7617 esc_html(substr($parent, 0, 7))) .
7618 ')';
7619 } else {
7620 # merge commit
7621 $formats_nav .=
7622 '(merge: ' .
7623 join(' ', map {
7624 $cgi->a({-href => href(action=>"commit",
7625 hash=>$_)},
7626 esc_html(substr($_, 0, 7)));
7627 } @$parents ) .
7628 ')';
7630 if (gitweb_check_feature('patches') && @$parents <= 1) {
7631 $formats_nav .= " | " .
7632 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7633 "patch");
7636 if (!defined $parent) {
7637 $parent = "--root";
7639 my @difftree;
7640 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7641 @diff_opts,
7642 (@$parents <= 1 ? $parent : '-c'),
7643 $hash, "--"
7644 or die_error(500, "Open git-diff-tree failed");
7645 @difftree = map { chomp; $_ } <$fd>;
7646 close $fd or die_error(404, "Reading git-diff-tree failed");
7648 # non-textual hash id's can be cached
7649 my $expires;
7650 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7651 $expires = "+1d";
7653 my $refs = git_get_references();
7654 my $ref = format_ref_marker($refs, $co{'id'});
7656 git_header_html(undef, $expires);
7657 git_print_page_nav('commit', '',
7658 $hash, $co{'tree'}, $hash,
7659 $formats_nav);
7661 if (defined $co{'parent'}) {
7662 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7663 } else {
7664 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7666 print "<div class=\"title_text\">\n" .
7667 "<table class=\"object_header\">\n";
7668 git_print_authorship_rows(\%co);
7669 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7670 print "<tr>" .
7671 "<td>tree</td>" .
7672 "<td class=\"sha1\">" .
7673 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7674 class => "list"}, $co{'tree'}) .
7675 "</td>" .
7676 "<td class=\"link\">" .
7677 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7678 "tree");
7679 my $snapshot_links = format_snapshot_links($hash);
7680 if (defined $snapshot_links) {
7681 print " | " . $snapshot_links;
7683 print "</td>" .
7684 "</tr>\n";
7686 foreach my $par (@$parents) {
7687 print "<tr>" .
7688 "<td>parent</td>" .
7689 "<td class=\"sha1\">" .
7690 $cgi->a({-href => href(action=>"commit", hash=>$par),
7691 class => "list"}, $par) .
7692 "</td>" .
7693 "<td class=\"link\">" .
7694 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7695 " | " .
7696 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7697 "</td>" .
7698 "</tr>\n";
7700 print "</table>".
7701 "</div>\n";
7703 print "<div class=\"page_body\">\n";
7704 git_print_log($co{'comment'});
7705 print "</div>\n";
7707 git_difftree_body(\@difftree, $hash, @$parents);
7709 git_footer_html();
7712 sub git_object {
7713 # object is defined by:
7714 # - hash or hash_base alone
7715 # - hash_base and file_name
7716 my $type;
7718 # - hash or hash_base alone
7719 if ($hash || ($hash_base && !defined $file_name)) {
7720 my $object_id = $hash || $hash_base;
7722 open my $fd, "-|", quote_command(
7723 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7724 or die_error(404, "Object does not exist");
7725 $type = <$fd>;
7726 chomp $type;
7727 close $fd
7728 or die_error(404, "Object does not exist");
7730 # - hash_base and file_name
7731 } elsif ($hash_base && defined $file_name) {
7732 $file_name =~ s,/+$,,;
7734 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7735 or die_error(404, "Base object does not exist");
7737 # here errors should not happen
7738 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7739 or die_error(500, "Open git-ls-tree failed");
7740 my $line = <$fd>;
7741 close $fd;
7743 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7744 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7745 die_error(404, "File or directory for given base does not exist");
7747 $type = $2;
7748 $hash = $3;
7749 } else {
7750 die_error(400, "Not enough information to find object");
7753 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7754 hash=>$hash, hash_base=>$hash_base,
7755 file_name=>$file_name),
7756 -status => '302 Found');
7759 sub git_blobdiff {
7760 my $format = shift || 'html';
7761 my $diff_style = $input_params{'diff_style'} || 'inline';
7763 my $fd;
7764 my @difftree;
7765 my %diffinfo;
7766 my $expires;
7768 # preparing $fd and %diffinfo for git_patchset_body
7769 # new style URI
7770 if (defined $hash_base && defined $hash_parent_base) {
7771 if (defined $file_name) {
7772 # read raw output
7773 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7774 $hash_parent_base, $hash_base,
7775 "--", (defined $file_parent ? $file_parent : ()), $file_name
7776 or die_error(500, "Open git-diff-tree failed");
7777 @difftree = map { chomp; $_ } <$fd>;
7778 close $fd
7779 or die_error(404, "Reading git-diff-tree failed");
7780 @difftree
7781 or die_error(404, "Blob diff not found");
7783 } elsif (defined $hash &&
7784 $hash =~ /[0-9a-fA-F]{40}/) {
7785 # try to find filename from $hash
7787 # read filtered raw output
7788 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7789 $hash_parent_base, $hash_base, "--"
7790 or die_error(500, "Open git-diff-tree failed");
7791 @difftree =
7792 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7793 # $hash == to_id
7794 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7795 map { chomp; $_ } <$fd>;
7796 close $fd
7797 or die_error(404, "Reading git-diff-tree failed");
7798 @difftree
7799 or die_error(404, "Blob diff not found");
7801 } else {
7802 die_error(400, "Missing one of the blob diff parameters");
7805 if (@difftree > 1) {
7806 die_error(400, "Ambiguous blob diff specification");
7809 %diffinfo = parse_difftree_raw_line($difftree[0]);
7810 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7811 $file_name ||= $diffinfo{'to_file'};
7813 $hash_parent ||= $diffinfo{'from_id'};
7814 $hash ||= $diffinfo{'to_id'};
7816 # non-textual hash id's can be cached
7817 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7818 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7819 $expires = '+1d';
7822 # open patch output
7823 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7824 '-p', ($format eq 'html' ? "--full-index" : ()),
7825 $hash_parent_base, $hash_base,
7826 "--", (defined $file_parent ? $file_parent : ()), $file_name
7827 or die_error(500, "Open git-diff-tree failed");
7830 # old/legacy style URI -- not generated anymore since 1.4.3.
7831 if (!%diffinfo) {
7832 die_error('404 Not Found', "Missing one of the blob diff parameters")
7835 # header
7836 if ($format eq 'html') {
7837 my $formats_nav =
7838 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7839 "raw");
7840 $formats_nav .= diff_style_nav($diff_style);
7841 git_header_html(undef, $expires);
7842 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7843 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7844 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7845 } else {
7846 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7847 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7849 if (defined $file_name) {
7850 git_print_page_path($file_name, "blob", $hash_base);
7851 } else {
7852 print "<div class=\"page_path\"></div>\n";
7855 } elsif ($format eq 'plain') {
7856 print $cgi->header(
7857 -type => 'text/plain',
7858 -charset => 'utf-8',
7859 -expires => $expires,
7860 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7862 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7864 } else {
7865 die_error(400, "Unknown blobdiff format");
7868 # patch
7869 if ($format eq 'html') {
7870 print "<div class=\"page_body\">\n";
7872 git_patchset_body($fd, $diff_style,
7873 [ \%diffinfo ], $hash_base, $hash_parent_base);
7874 close $fd;
7876 print "</div>\n"; # class="page_body"
7877 git_footer_html();
7879 } else {
7880 while (my $line = <$fd>) {
7881 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7882 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7884 print $line;
7886 last if $line =~ m!^\+\+\+!;
7888 local $/ = undef;
7889 print <$fd>;
7890 close $fd;
7894 sub git_blobdiff_plain {
7895 git_blobdiff('plain');
7898 # assumes that it is added as later part of already existing navigation,
7899 # so it returns "| foo | bar" rather than just "foo | bar"
7900 sub diff_style_nav {
7901 my ($diff_style, $is_combined) = @_;
7902 $diff_style ||= 'inline';
7904 return "" if ($is_combined);
7906 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7907 my %styles = @styles;
7908 @styles =
7909 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7911 return join '',
7912 map { " | ".$_ }
7913 map {
7914 $_ eq $diff_style ? $styles{$_} :
7915 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7916 } @styles;
7919 sub git_commitdiff {
7920 my %params = @_;
7921 my $format = $params{-format} || 'html';
7922 my $diff_style = $input_params{'diff_style'} || 'inline';
7924 my ($patch_max) = gitweb_get_feature('patches');
7925 if ($format eq 'patch') {
7926 die_error(403, "Patch view not allowed") unless $patch_max;
7929 $hash ||= $hash_base || "HEAD";
7930 my %co = parse_commit($hash)
7931 or die_error(404, "Unknown commit object");
7933 # choose format for commitdiff for merge
7934 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7935 $hash_parent = '--cc';
7937 # we need to prepare $formats_nav before almost any parameter munging
7938 my $formats_nav;
7939 if ($format eq 'html') {
7940 $formats_nav =
7941 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7942 "raw");
7943 if ($patch_max && @{$co{'parents'}} <= 1) {
7944 $formats_nav .= " | " .
7945 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7946 "patch");
7948 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7950 if (defined $hash_parent &&
7951 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7952 # commitdiff with two commits given
7953 my $hash_parent_short = $hash_parent;
7954 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7955 $hash_parent_short = substr($hash_parent, 0, 7);
7957 $formats_nav .=
7958 ' (from';
7959 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7960 if ($co{'parents'}[$i] eq $hash_parent) {
7961 $formats_nav .= ' parent ' . ($i+1);
7962 last;
7965 $formats_nav .= ': ' .
7966 $cgi->a({-href => href(-replay=>1,
7967 hash=>$hash_parent, hash_base=>undef)},
7968 esc_html($hash_parent_short)) .
7969 ')';
7970 } elsif (!$co{'parent'}) {
7971 # --root commitdiff
7972 $formats_nav .= ' (initial)';
7973 } elsif (scalar @{$co{'parents'}} == 1) {
7974 # single parent commit
7975 $formats_nav .=
7976 ' (parent: ' .
7977 $cgi->a({-href => href(-replay=>1,
7978 hash=>$co{'parent'}, hash_base=>undef)},
7979 esc_html(substr($co{'parent'}, 0, 7))) .
7980 ')';
7981 } else {
7982 # merge commit
7983 if ($hash_parent eq '--cc') {
7984 $formats_nav .= ' | ' .
7985 $cgi->a({-href => href(-replay=>1,
7986 hash=>$hash, hash_parent=>'-c')},
7987 'combined');
7988 } else { # $hash_parent eq '-c'
7989 $formats_nav .= ' | ' .
7990 $cgi->a({-href => href(-replay=>1,
7991 hash=>$hash, hash_parent=>'--cc')},
7992 'compact');
7994 $formats_nav .=
7995 ' (merge: ' .
7996 join(' ', map {
7997 $cgi->a({-href => href(-replay=>1,
7998 hash=>$_, hash_base=>undef)},
7999 esc_html(substr($_, 0, 7)));
8000 } @{$co{'parents'}} ) .
8001 ')';
8005 my $hash_parent_param = $hash_parent;
8006 if (!defined $hash_parent_param) {
8007 # --cc for multiple parents, --root for parentless
8008 $hash_parent_param =
8009 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
8012 # read commitdiff
8013 my $fd;
8014 my @difftree;
8015 if ($format eq 'html') {
8016 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8017 "--no-commit-id", "--patch-with-raw", "--full-index",
8018 $hash_parent_param, $hash, "--"
8019 or die_error(500, "Open git-diff-tree failed");
8021 while (my $line = <$fd>) {
8022 chomp $line;
8023 # empty line ends raw part of diff-tree output
8024 last unless $line;
8025 push @difftree, scalar parse_difftree_raw_line($line);
8028 } elsif ($format eq 'plain') {
8029 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8030 '-p', $hash_parent_param, $hash, "--"
8031 or die_error(500, "Open git-diff-tree failed");
8032 } elsif ($format eq 'patch') {
8033 # For commit ranges, we limit the output to the number of
8034 # patches specified in the 'patches' feature.
8035 # For single commits, we limit the output to a single patch,
8036 # diverging from the git-format-patch default.
8037 my @commit_spec = ();
8038 if ($hash_parent) {
8039 if ($patch_max > 0) {
8040 push @commit_spec, "-$patch_max";
8042 push @commit_spec, '-n', "$hash_parent..$hash";
8043 } else {
8044 if ($params{-single}) {
8045 push @commit_spec, '-1';
8046 } else {
8047 if ($patch_max > 0) {
8048 push @commit_spec, "-$patch_max";
8050 push @commit_spec, "-n";
8052 push @commit_spec, '--root', $hash;
8054 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
8055 '--encoding=utf8', '--stdout', @commit_spec
8056 or die_error(500, "Open git-format-patch failed");
8057 } else {
8058 die_error(400, "Unknown commitdiff format");
8061 # non-textual hash id's can be cached
8062 my $expires;
8063 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8064 $expires = "+1d";
8067 # write commit message
8068 if ($format eq 'html') {
8069 my $refs = git_get_references();
8070 my $ref = format_ref_marker($refs, $co{'id'});
8072 git_header_html(undef, $expires);
8073 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
8074 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
8075 print "<div class=\"title_text\">\n" .
8076 "<table class=\"object_header\">\n";
8077 git_print_authorship_rows(\%co);
8078 print "</table>".
8079 "</div>\n";
8080 print "<div class=\"page_body\">\n";
8081 if (@{$co{'comment'}} > 1) {
8082 print "<div class=\"log\">\n";
8083 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
8084 print "</div>\n"; # class="log"
8087 } elsif ($format eq 'plain') {
8088 my $refs = git_get_references("tags");
8089 my $tagname = git_get_rev_name_tags($hash);
8090 my $filename = basename($project) . "-$hash.patch";
8092 print $cgi->header(
8093 -type => 'text/plain',
8094 -charset => 'utf-8',
8095 -expires => $expires,
8096 -content_disposition => 'inline; filename="' . "$filename" . '"');
8097 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8098 print "From: " . to_utf8($co{'author'}) . "\n";
8099 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8100 print "Subject: " . to_utf8($co{'title'}) . "\n";
8102 print "X-Git-Tag: $tagname\n" if $tagname;
8103 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8105 foreach my $line (@{$co{'comment'}}) {
8106 print to_utf8($line) . "\n";
8108 print "---\n\n";
8109 } elsif ($format eq 'patch') {
8110 my $filename = basename($project) . "-$hash.patch";
8112 print $cgi->header(
8113 -type => 'text/plain',
8114 -charset => 'utf-8',
8115 -expires => $expires,
8116 -content_disposition => 'inline; filename="' . "$filename" . '"');
8119 # write patch
8120 if ($format eq 'html') {
8121 my $use_parents = !defined $hash_parent ||
8122 $hash_parent eq '-c' || $hash_parent eq '--cc';
8123 git_difftree_body(\@difftree, $hash,
8124 $use_parents ? @{$co{'parents'}} : $hash_parent);
8125 print "<br/>\n";
8127 git_patchset_body($fd, $diff_style,
8128 \@difftree, $hash,
8129 $use_parents ? @{$co{'parents'}} : $hash_parent);
8130 close $fd;
8131 print "</div>\n"; # class="page_body"
8132 git_footer_html();
8134 } elsif ($format eq 'plain') {
8135 local $/ = undef;
8136 print <$fd>;
8137 close $fd
8138 or print "Reading git-diff-tree failed\n";
8139 } elsif ($format eq 'patch') {
8140 local $/ = undef;
8141 print <$fd>;
8142 close $fd
8143 or print "Reading git-format-patch failed\n";
8147 sub git_commitdiff_plain {
8148 git_commitdiff(-format => 'plain');
8151 # format-patch-style patches
8152 sub git_patch {
8153 git_commitdiff(-format => 'patch', -single => 1);
8156 sub git_patches {
8157 git_commitdiff(-format => 'patch');
8160 sub git_history {
8161 git_log_generic('history', \&git_history_body,
8162 $hash_base, $hash_parent_base,
8163 $file_name, $hash);
8166 sub git_search {
8167 $searchtype ||= 'commit';
8169 # check if appropriate features are enabled
8170 gitweb_check_feature('search')
8171 or die_error(403, "Search is disabled");
8172 if ($searchtype eq 'pickaxe') {
8173 # pickaxe may take all resources of your box and run for several minutes
8174 # with every query - so decide by yourself how public you make this feature
8175 gitweb_check_feature('pickaxe')
8176 or die_error(403, "Pickaxe search is disabled");
8178 if ($searchtype eq 'grep') {
8179 # grep search might be potentially CPU-intensive, too
8180 gitweb_check_feature('grep')
8181 or die_error(403, "Grep search is disabled");
8184 if (!defined $searchtext) {
8185 die_error(400, "Text field is empty");
8187 if (!defined $hash) {
8188 $hash = git_get_head_hash($project);
8190 my %co = parse_commit($hash);
8191 if (!%co) {
8192 die_error(404, "Unknown commit object");
8194 if (!defined $page) {
8195 $page = 0;
8198 if ($searchtype eq 'commit' ||
8199 $searchtype eq 'author' ||
8200 $searchtype eq 'committer') {
8201 git_search_message(%co);
8202 } elsif ($searchtype eq 'pickaxe') {
8203 git_search_changes(%co);
8204 } elsif ($searchtype eq 'grep') {
8205 git_search_files(%co);
8206 } else {
8207 die_error(400, "Unknown search type");
8211 sub git_search_help {
8212 git_header_html();
8213 git_print_page_nav('','', $hash,$hash,$hash);
8214 print <<EOT;
8215 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8216 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8217 the pattern entered is recognized as the POSIX extended
8218 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8219 insensitive).</p>
8220 <dl>
8221 <dt><b>commit</b></dt>
8222 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8224 my $have_grep = gitweb_check_feature('grep');
8225 if ($have_grep) {
8226 print <<EOT;
8227 <dt><b>grep</b></dt>
8228 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8229 a different one) are searched for the given pattern. On large trees, this search can take
8230 a while and put some strain on the server, so please use it with some consideration. Note that
8231 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8232 case-sensitive.</dd>
8235 print <<EOT;
8236 <dt><b>author</b></dt>
8237 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8238 <dt><b>committer</b></dt>
8239 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8241 my $have_pickaxe = gitweb_check_feature('pickaxe');
8242 if ($have_pickaxe) {
8243 print <<EOT;
8244 <dt><b>pickaxe</b></dt>
8245 <dd>All commits that caused the string to appear or disappear from any file (changes that
8246 added, removed or "modified" the string) will be listed. This search can take a while and
8247 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8248 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8251 print "</dl>\n";
8252 git_footer_html();
8255 sub git_shortlog {
8256 git_log_generic('shortlog', \&git_shortlog_body,
8257 $hash, $hash_parent);
8260 ## ......................................................................
8261 ## feeds (RSS, Atom; OPML)
8263 sub git_feed {
8264 my $format = shift || 'atom';
8265 my $have_blame = gitweb_check_feature('blame');
8267 # Atom: http://www.atomenabled.org/developers/syndication/
8268 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8269 if ($format ne 'rss' && $format ne 'atom') {
8270 die_error(400, "Unknown web feed format");
8273 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8274 my $head = $hash || 'HEAD';
8275 my @commitlist = parse_commits($head, 150, 0, $file_name);
8277 my %latest_commit;
8278 my %latest_date;
8279 my $content_type = "application/$format+xml";
8280 if (defined $cgi->http('HTTP_ACCEPT') &&
8281 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8282 # browser (feed reader) prefers text/xml
8283 $content_type = 'text/xml';
8285 if (defined($commitlist[0])) {
8286 %latest_commit = %{$commitlist[0]};
8287 my $latest_epoch = $latest_commit{'committer_epoch'};
8288 exit_if_unmodified_since($latest_epoch);
8289 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8291 print $cgi->header(
8292 -type => $content_type,
8293 -charset => 'utf-8',
8294 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8295 -status => '200 OK');
8297 # Optimization: skip generating the body if client asks only
8298 # for Last-Modified date.
8299 return if ($cgi->request_method() eq 'HEAD');
8301 # header variables
8302 my $title = "$site_name - $project/$action";
8303 my $feed_type = 'log';
8304 if (defined $hash) {
8305 $title .= " - '$hash'";
8306 $feed_type = 'branch log';
8307 if (defined $file_name) {
8308 $title .= " :: $file_name";
8309 $feed_type = 'history';
8311 } elsif (defined $file_name) {
8312 $title .= " - $file_name";
8313 $feed_type = 'history';
8315 $title .= " $feed_type";
8316 $title = esc_html($title);
8317 my $descr = git_get_project_description($project);
8318 if (defined $descr) {
8319 $descr = esc_html($descr);
8320 } else {
8321 $descr = "$project " .
8322 ($format eq 'rss' ? 'RSS' : 'Atom') .
8323 " feed";
8325 my $owner = git_get_project_owner($project);
8326 $owner = esc_html($owner);
8328 #header
8329 my $alt_url;
8330 if (defined $file_name) {
8331 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8332 } elsif (defined $hash) {
8333 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8334 } else {
8335 $alt_url = href(-full=>1, action=>"summary");
8337 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8338 if ($format eq 'rss') {
8339 print <<XML;
8340 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8341 <channel>
8343 print "<title>$title</title>\n" .
8344 "<link>$alt_url</link>\n" .
8345 "<description>$descr</description>\n" .
8346 "<language>en</language>\n" .
8347 # project owner is responsible for 'editorial' content
8348 "<managingEditor>$owner</managingEditor>\n";
8349 if (defined $logo || defined $favicon) {
8350 # prefer the logo to the favicon, since RSS
8351 # doesn't allow both
8352 my $img = esc_url($logo || $favicon);
8353 print "<image>\n" .
8354 "<url>$img</url>\n" .
8355 "<title>$title</title>\n" .
8356 "<link>$alt_url</link>\n" .
8357 "</image>\n";
8359 if (%latest_date) {
8360 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8361 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8363 print "<generator>gitweb v.$version/$git_version</generator>\n";
8364 } elsif ($format eq 'atom') {
8365 print <<XML;
8366 <feed xmlns="http://www.w3.org/2005/Atom">
8368 print "<title>$title</title>\n" .
8369 "<subtitle>$descr</subtitle>\n" .
8370 '<link rel="alternate" type="text/html" href="' .
8371 $alt_url . '" />' . "\n" .
8372 '<link rel="self" type="' . $content_type . '" href="' .
8373 $cgi->self_url() . '" />' . "\n" .
8374 "<id>" . href(-full=>1) . "</id>\n" .
8375 # use project owner for feed author
8376 "<author><name>$owner</name></author>\n";
8377 if (defined $favicon) {
8378 print "<icon>" . esc_url($favicon) . "</icon>\n";
8380 if (defined $logo) {
8381 # not twice as wide as tall: 72 x 27 pixels
8382 print "<logo>" . esc_url($logo) . "</logo>\n";
8384 if (! %latest_date) {
8385 # dummy date to keep the feed valid until commits trickle in:
8386 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8387 } else {
8388 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8390 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8393 # contents
8394 for (my $i = 0; $i <= $#commitlist; $i++) {
8395 my %co = %{$commitlist[$i]};
8396 my $commit = $co{'id'};
8397 # we read 150, we always show 30 and the ones more recent than 48 hours
8398 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8399 last;
8401 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8403 # get list of changed files
8404 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8405 $co{'parent'} || "--root",
8406 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8407 or next;
8408 my @difftree = map { chomp; $_ } <$fd>;
8409 close $fd
8410 or next;
8412 # print element (entry, item)
8413 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8414 if ($format eq 'rss') {
8415 print "<item>\n" .
8416 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8417 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8418 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8419 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8420 "<link>$co_url</link>\n" .
8421 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8422 "<content:encoded>" .
8423 "<![CDATA[\n";
8424 } elsif ($format eq 'atom') {
8425 print "<entry>\n" .
8426 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8427 "<updated>$cd{'iso-8601'}</updated>\n" .
8428 "<author>\n" .
8429 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8430 if ($co{'author_email'}) {
8431 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8433 print "</author>\n" .
8434 # use committer for contributor
8435 "<contributor>\n" .
8436 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8437 if ($co{'committer_email'}) {
8438 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8440 print "</contributor>\n" .
8441 "<published>$cd{'iso-8601'}</published>\n" .
8442 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8443 "<id>$co_url</id>\n" .
8444 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8445 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8447 my $comment = $co{'comment'};
8448 print "<pre>\n";
8449 foreach my $line (@$comment) {
8450 $line = esc_html($line);
8451 print "$line\n";
8453 print "</pre><ul>\n";
8454 foreach my $difftree_line (@difftree) {
8455 my %difftree = parse_difftree_raw_line($difftree_line);
8456 next if !$difftree{'from_id'};
8458 my $file = $difftree{'file'} || $difftree{'to_file'};
8460 print "<li>" .
8461 "[" .
8462 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8463 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8464 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8465 file_name=>$file, file_parent=>$difftree{'from_file'}),
8466 -title => "diff"}, 'D');
8467 if ($have_blame) {
8468 print $cgi->a({-href => href(-full=>1, action=>"blame",
8469 file_name=>$file, hash_base=>$commit),
8470 -title => "blame"}, 'B');
8472 # if this is not a feed of a file history
8473 if (!defined $file_name || $file_name ne $file) {
8474 print $cgi->a({-href => href(-full=>1, action=>"history",
8475 file_name=>$file, hash=>$commit),
8476 -title => "history"}, 'H');
8478 $file = esc_path($file);
8479 print "] ".
8480 "$file</li>\n";
8482 if ($format eq 'rss') {
8483 print "</ul>]]>\n" .
8484 "</content:encoded>\n" .
8485 "</item>\n";
8486 } elsif ($format eq 'atom') {
8487 print "</ul>\n</div>\n" .
8488 "</content>\n" .
8489 "</entry>\n";
8493 # end of feed
8494 if ($format eq 'rss') {
8495 print "</channel>\n</rss>\n";
8496 } elsif ($format eq 'atom') {
8497 print "</feed>\n";
8501 sub git_rss {
8502 git_feed('rss');
8505 sub git_atom {
8506 git_feed('atom');
8509 sub git_opml {
8510 my @list = git_get_projects_list($project_filter, $strict_export);
8511 if (!@list) {
8512 die_error(404, "No projects found");
8515 print $cgi->header(
8516 -type => 'text/xml',
8517 -charset => 'utf-8',
8518 -content_disposition => 'inline; filename="opml.xml"');
8520 my $title = esc_html($site_name);
8521 my $filter = " within subdirectory ";
8522 if (defined $project_filter) {
8523 $filter .= esc_html($project_filter);
8524 } else {
8525 $filter = "";
8527 print <<XML;
8528 <?xml version="1.0" encoding="utf-8"?>
8529 <opml version="1.0">
8530 <head>
8531 <title>$title OPML Export$filter</title>
8532 </head>
8533 <body>
8534 <outline text="git RSS feeds">
8537 foreach my $pr (@list) {
8538 my %proj = %$pr;
8539 my $head = git_get_head_hash($proj{'path'});
8540 if (!defined $head) {
8541 next;
8543 $git_dir = "$projectroot/$proj{'path'}";
8544 my %co = parse_commit($head);
8545 if (!%co) {
8546 next;
8549 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8550 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8551 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8552 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8554 print <<XML;
8555 </outline>
8556 </body>
8557 </opml>