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