gitweb/lib - Use locking to avoid 'cache miss stampede' problem
[git/jnareb-git.git] / gitweb / gitweb.perl
blob4758bec9b3f56730e2e362dd4a8595173ca50de9
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;
14 use File::Spec;
15 # __DIR__ is taken from Dir::Self __DIR__ fragment
16 sub __DIR__ () {
17 File::Spec->rel2abs(join '', (File::Spec->splitpath(__FILE__))[0, 1]);
19 use lib __DIR__ . '/lib';
21 use CGI qw(:standard :escapeHTML -nosticky);
22 use CGI::Util qw(unescape);
23 use CGI::Carp qw(fatalsToBrowser set_message);
24 use Encode;
25 use Fcntl ':mode';
26 use File::Find qw();
27 use File::Basename qw(basename);
28 binmode STDOUT, ':utf8';
30 our $t0;
31 if (eval { require Time::HiRes; 1; }) {
32 $t0 = [Time::HiRes::gettimeofday()];
34 our $number_of_git_cmds = 0;
36 BEGIN {
37 CGI->compile() if $ENV{'MOD_PERL'};
40 our $version = "++GIT_VERSION++";
42 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
43 sub evaluate_uri {
44 our $cgi;
46 our $my_url = $cgi->url();
47 our $my_uri = $cgi->url(-absolute => 1);
49 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
50 # needed and used only for URLs with nonempty PATH_INFO
51 our $base_url = $my_url;
53 # When the script is used as DirectoryIndex, the URL does not contain the name
54 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
55 # have to do it ourselves. We make $path_info global because it's also used
56 # later on.
58 # Another issue with the script being the DirectoryIndex is that the resulting
59 # $my_url data is not the full script URL: this is good, because we want
60 # generated links to keep implying the script name if it wasn't explicitly
61 # indicated in the URL we're handling, but it means that $my_url cannot be used
62 # as base URL.
63 # Therefore, if we needed to strip PATH_INFO, then we know that we have
64 # to build the base URL ourselves:
65 our $path_info = $ENV{"PATH_INFO"};
66 if ($path_info) {
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 # name of your site or organization to appear in page titles
94 # replace this with something more descriptive for clearer bookmarks
95 our $site_name = "++GITWEB_SITENAME++"
96 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
98 # filename of html text to include at top of each page
99 our $site_header = "++GITWEB_SITE_HEADER++";
100 # html text to include at home page
101 our $home_text = "++GITWEB_HOMETEXT++";
102 # filename of html text to include at bottom of each page
103 our $site_footer = "++GITWEB_SITE_FOOTER++";
105 # URI of stylesheets
106 our @stylesheets = ("++GITWEB_CSS++");
107 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
108 our $stylesheet = undef;
109 # URI of GIT logo (72x27 size)
110 our $logo = "++GITWEB_LOGO++";
111 # URI of GIT favicon, assumed to be image/png type
112 our $favicon = "++GITWEB_FAVICON++";
113 # URI of gitweb.js (JavaScript code for gitweb)
114 our $javascript = "++GITWEB_JS++";
116 # URI and label (title) of GIT logo link
117 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
118 #our $logo_label = "git documentation";
119 our $logo_url = "http://git-scm.com/";
120 our $logo_label = "git homepage";
122 # source of projects list
123 our $projects_list = "++GITWEB_LIST++";
125 # the width (in characters) of the projects list "Description" column
126 our $projects_list_description_width = 25;
128 # default order of projects list
129 # valid values are none, project, descr, owner, and age
130 our $default_projects_order = "project";
132 # show repository only if this file exists
133 # (only effective if this variable evaluates to true)
134 our $export_ok = "++GITWEB_EXPORT_OK++";
136 # show repository only if this subroutine returns true
137 # when given the path to the project, for example:
138 # sub { return -e "$_[0]/git-daemon-export-ok"; }
139 our $export_auth_hook = undef;
141 # only allow viewing of repositories also shown on the overview page
142 our $strict_export = "++GITWEB_STRICT_EXPORT++";
144 # list of git base URLs used for URL to where fetch project from,
145 # i.e. full URL is "$git_base_url/$project"
146 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
148 # default blob_plain mimetype and default charset for text/plain blob
149 our $default_blob_plain_mimetype = 'text/plain';
150 our $default_text_plain_charset = undef;
152 # file to use for guessing MIME types before trying /etc/mime.types
153 # (relative to the current git repository)
154 our $mimetypes_file = undef;
156 # assume this charset if line contains non-UTF-8 characters;
157 # it should be valid encoding (see Encoding::Supported(3pm) for list),
158 # for which encoding all byte sequences are valid, for example
159 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
160 # could be even 'utf-8' for the old behavior)
161 our $fallback_encoding = 'latin1';
163 # rename detection options for git-diff and git-diff-tree
164 # - default is '-M', with the cost proportional to
165 # (number of removed files) * (number of new files).
166 # - more costly is '-C' (which implies '-M'), with the cost proportional to
167 # (number of changed files + number of removed files) * (number of new files)
168 # - even more costly is '-C', '--find-copies-harder' with cost
169 # (number of files in the original tree) * (number of new files)
170 # - one might want to include '-B' option, e.g. '-B', '-M'
171 our @diff_opts = ('-M'); # taken from git_commit
173 # Disables features that would allow repository owners to inject script into
174 # the gitweb domain.
175 our $prevent_xss = 0;
177 # Path to the highlight executable to use (must be the one from
178 # http://www.andre-simon.de due to assumptions about parameters and output).
179 # Useful if highlight is not installed on your webserver's PATH.
180 # [Default: highlight]
181 our $highlight_bin = "++HIGHLIGHT_BIN++";
183 # information about snapshot formats that gitweb is capable of serving
184 our %known_snapshot_formats = (
185 # name => {
186 # 'display' => display name,
187 # 'type' => mime type,
188 # 'suffix' => filename suffix,
189 # 'format' => --format for git-archive,
190 # 'compressor' => [compressor command and arguments]
191 # (array reference, optional)
192 # 'disabled' => boolean (optional)}
194 'tgz' => {
195 'display' => 'tar.gz',
196 'type' => 'application/x-gzip',
197 'suffix' => '.tar.gz',
198 'format' => 'tar',
199 'compressor' => ['gzip']},
201 'tbz2' => {
202 'display' => 'tar.bz2',
203 'type' => 'application/x-bzip2',
204 'suffix' => '.tar.bz2',
205 'format' => 'tar',
206 'compressor' => ['bzip2']},
208 'txz' => {
209 'display' => 'tar.xz',
210 'type' => 'application/x-xz',
211 'suffix' => '.tar.xz',
212 'format' => 'tar',
213 'compressor' => ['xz'],
214 'disabled' => 1},
216 'zip' => {
217 'display' => 'zip',
218 'type' => 'application/x-zip',
219 'suffix' => '.zip',
220 'format' => 'zip'},
223 # Aliases so we understand old gitweb.snapshot values in repository
224 # configuration.
225 our %known_snapshot_format_aliases = (
226 'gzip' => 'tgz',
227 'bzip2' => 'tbz2',
228 'xz' => 'txz',
230 # backward compatibility: legacy gitweb config support
231 'x-gzip' => undef, 'gz' => undef,
232 'x-bzip2' => undef, 'bz2' => undef,
233 'x-zip' => undef, '' => undef,
236 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
237 # are changed, it may be appropriate to change these values too via
238 # $GITWEB_CONFIG.
239 our %avatar_size = (
240 'default' => 16,
241 'double' => 32
244 # Used to set the maximum load that we will still respond to gitweb queries.
245 # If server load exceed this value then return "503 server busy" error.
246 # If gitweb cannot determined server load, it is taken to be 0.
247 # Leave it undefined (or set to 'undef') to turn off load checking.
248 our $maxload = 300;
250 # configuration for 'highlight' (http://www.andre-simon.de/)
251 # match by basename
252 our %highlight_basename = (
253 #'Program' => 'py',
254 #'Library' => 'py',
255 'SConstruct' => 'py', # SCons equivalent of Makefile
256 'Makefile' => 'make',
258 # match by extension
259 our %highlight_ext = (
260 # main extensions, defining name of syntax;
261 # see files in /usr/share/highlight/langDefs/ directory
262 map { $_ => $_ }
263 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl),
264 # alternate extensions, see /etc/highlight/filetypes.conf
265 'h' => 'c',
266 map { $_ => 'cpp' } qw(cxx c++ cc),
267 map { $_ => 'php' } qw(php3 php4),
268 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
269 'mak' => 'make',
270 map { $_ => 'xml' } qw(xhtml html htm),
274 # This enables/disables the caching layer in gitweb. Currently supported
275 # is only output (response) caching, similar to the one used on git.kernel.org.
276 our $caching_enabled = 0;
277 # Set to _initialized_ instance of cache interface implementing (at least)
278 # get($key) and set($key, $data) methods (Cache::Cache and CHI interfaces),
279 # or to name of class of cache interface implementing said methods.
280 # If unset, GitwebCache::FileCacheWithLocking would be used, which is 'dumb'
281 # (but fast) file based caching layer, currently without any support for
282 # cache size limiting. It is therefore recommended that the cache directory
283 # be periodically completely deleted; this operation is safe to perform.
284 # Suggested mechanism:
285 # mv $cachedir $cachedir.flush && mkdir $cachedir && rm -rf $cachedir.flush
286 our $cache;
287 # You define site-wide cache options defaults here; override them with
288 # $GITWEB_CONFIG as necessary.
289 our %cache_options = (
290 # The location in the filesystem that will hold the root of the cache.
291 # This directory will be created as needed (if possible) on the first
292 # cache set. Note that either this directory must exists and web server
293 # has to have write permissions to it, or web server must be able to
294 # create this directory.
295 # Possible values:
296 # * 'cache' (relative to gitweb),
297 # * File::Spec->catdir(File::Spec->tmpdir(), 'gitweb-cache'),
298 # * '/var/cache/gitweb' (FHS compliant, requires being set up),
299 'cache_root' => 'cache',
301 # The number of subdirectories deep to cache object item. This should be
302 # large enough that no cache directory has more than a few hundred
303 # objects. Each non-leaf directory contains up to 256 subdirectories
304 # (00-ff). Must be larger than 0.
305 'cache_depth' => 1,
307 # The (global) minimum expiration time for objects placed in the cache,
308 # in seconds. If the dynamic adaptive cache exporation time is lower
309 # than this number, we set cache timeout to this minimum.
310 'expires_min' => 20, # 20 seconds
312 # The (global) maximum expiration time for dynamic (adaptive) caching
313 # algorithm, in seconds. If the adaptive cache lifetime exceeds this
314 # number, we set cache timeout to this maximum.
315 # (If 'expires_min' >= 'expires_max', there is no adaptive cache timeout,
316 # and 'expires_min' is used as expiration time for objects in cache.)
317 'expires_max' => 1200, # 20 minutes
319 # Cache lifetime will be increased by applying this factor to the result
320 # from 'check_load' callback (see below).
321 'expires_factor' => 60, # expire time in seconds for 1.0 (100% CPU) load
323 # User supplied callback for deciding the cache policy, usually system
324 # load. Multiplied by 'expires_factor' gives adaptive expiration time,
325 # in seconds, subject to the limits imposed by 'expires_min' and
326 # 'expires_max' bounds. Set to undef (or delete) to turn off dynamic
327 # lifetime control.
328 # (Compatibile with Cache::Adaptive.)
329 'check_load' => \&get_loadavg,
331 # Set to _initialized_ instance of GitwebCache::Capture compatibile capturing
332 # engine, i.e. one implementing ->new() constructor, and ->capture($code)
333 # method. If unset (default), the GitwebCache::Capture::Simple would be used.
334 our $capture;
336 # You define site-wide feature defaults here; override them with
337 # $GITWEB_CONFIG as necessary.
338 our %feature = (
339 # feature => {
340 # 'sub' => feature-sub (subroutine),
341 # 'override' => allow-override (boolean),
342 # 'default' => [ default options...] (array reference)}
344 # if feature is overridable (it means that allow-override has true value),
345 # then feature-sub will be called with default options as parameters;
346 # return value of feature-sub indicates if to enable specified feature
348 # if there is no 'sub' key (no feature-sub), then feature cannot be
349 # overridden
351 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
352 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
353 # is enabled
355 # Enable the 'blame' blob view, showing the last commit that modified
356 # each line in the file. This can be very CPU-intensive.
358 # To enable system wide have in $GITWEB_CONFIG
359 # $feature{'blame'}{'default'} = [1];
360 # To have project specific config enable override in $GITWEB_CONFIG
361 # $feature{'blame'}{'override'} = 1;
362 # and in project config gitweb.blame = 0|1;
363 'blame' => {
364 'sub' => sub { feature_bool('blame', @_) },
365 'override' => 0,
366 'default' => [0]},
368 # Enable the 'snapshot' link, providing a compressed archive of any
369 # tree. This can potentially generate high traffic if you have large
370 # project.
372 # Value is a list of formats defined in %known_snapshot_formats that
373 # you wish to offer.
374 # To disable system wide have in $GITWEB_CONFIG
375 # $feature{'snapshot'}{'default'} = [];
376 # To have project specific config enable override in $GITWEB_CONFIG
377 # $feature{'snapshot'}{'override'} = 1;
378 # and in project config, a comma-separated list of formats or "none"
379 # to disable. Example: gitweb.snapshot = tbz2,zip;
380 'snapshot' => {
381 'sub' => \&feature_snapshot,
382 'override' => 0,
383 'default' => ['tgz']},
385 # Enable text search, which will list the commits which match author,
386 # committer or commit text to a given string. Enabled by default.
387 # Project specific override is not supported.
388 'search' => {
389 'override' => 0,
390 'default' => [1]},
392 # Enable grep search, which will list the files in currently selected
393 # tree containing the given string. Enabled by default. This can be
394 # potentially CPU-intensive, of course.
396 # To enable system wide have in $GITWEB_CONFIG
397 # $feature{'grep'}{'default'} = [1];
398 # To have project specific config enable override in $GITWEB_CONFIG
399 # $feature{'grep'}{'override'} = 1;
400 # and in project config gitweb.grep = 0|1;
401 'grep' => {
402 'sub' => sub { feature_bool('grep', @_) },
403 'override' => 0,
404 'default' => [1]},
406 # Enable the pickaxe search, which will list the commits that modified
407 # a given string in a file. This can be practical and quite faster
408 # alternative to 'blame', but still potentially CPU-intensive.
410 # To enable system wide have in $GITWEB_CONFIG
411 # $feature{'pickaxe'}{'default'} = [1];
412 # To have project specific config enable override in $GITWEB_CONFIG
413 # $feature{'pickaxe'}{'override'} = 1;
414 # and in project config gitweb.pickaxe = 0|1;
415 'pickaxe' => {
416 'sub' => sub { feature_bool('pickaxe', @_) },
417 'override' => 0,
418 'default' => [1]},
420 # Enable showing size of blobs in a 'tree' view, in a separate
421 # column, similar to what 'ls -l' does. This cost a bit of IO.
423 # To disable system wide have in $GITWEB_CONFIG
424 # $feature{'show-sizes'}{'default'} = [0];
425 # To have project specific config enable override in $GITWEB_CONFIG
426 # $feature{'show-sizes'}{'override'} = 1;
427 # and in project config gitweb.showsizes = 0|1;
428 'show-sizes' => {
429 'sub' => sub { feature_bool('showsizes', @_) },
430 'override' => 0,
431 'default' => [1]},
433 # Make gitweb use an alternative format of the URLs which can be
434 # more readable and natural-looking: project name is embedded
435 # directly in the path and the query string contains other
436 # auxiliary information. All gitweb installations recognize
437 # URL in either format; this configures in which formats gitweb
438 # generates links.
440 # To enable system wide have in $GITWEB_CONFIG
441 # $feature{'pathinfo'}{'default'} = [1];
442 # Project specific override is not supported.
444 # Note that you will need to change the default location of CSS,
445 # favicon, logo and possibly other files to an absolute URL. Also,
446 # if gitweb.cgi serves as your indexfile, you will need to force
447 # $my_uri to contain the script name in your $GITWEB_CONFIG.
448 'pathinfo' => {
449 'override' => 0,
450 'default' => [0]},
452 # Make gitweb consider projects in project root subdirectories
453 # to be forks of existing projects. Given project $projname.git,
454 # projects matching $projname/*.git will not be shown in the main
455 # projects list, instead a '+' mark will be added to $projname
456 # there and a 'forks' view will be enabled for the project, listing
457 # all the forks. If project list is taken from a file, forks have
458 # to be listed after the main project.
460 # To enable system wide have in $GITWEB_CONFIG
461 # $feature{'forks'}{'default'} = [1];
462 # Project specific override is not supported.
463 'forks' => {
464 'override' => 0,
465 'default' => [0]},
467 # Insert custom links to the action bar of all project pages.
468 # This enables you mainly to link to third-party scripts integrating
469 # into gitweb; e.g. git-browser for graphical history representation
470 # or custom web-based repository administration interface.
472 # The 'default' value consists of a list of triplets in the form
473 # (label, link, position) where position is the label after which
474 # to insert the link and link is a format string where %n expands
475 # to the project name, %f to the project path within the filesystem,
476 # %h to the current hash (h gitweb parameter) and %b to the current
477 # hash base (hb gitweb parameter); %% expands to %.
479 # To enable system wide have in $GITWEB_CONFIG e.g.
480 # $feature{'actions'}{'default'} = [('graphiclog',
481 # '/git-browser/by-commit.html?r=%n', 'summary')];
482 # Project specific override is not supported.
483 'actions' => {
484 'override' => 0,
485 'default' => []},
487 # Allow gitweb scan project content tags described in ctags/
488 # of project repository, and display the popular Web 2.0-ish
489 # "tag cloud" near the project list. Note that this is something
490 # COMPLETELY different from the normal Git tags.
492 # gitweb by itself can show existing tags, but it does not handle
493 # tagging itself; you need an external application for that.
494 # For an example script, check Girocco's cgi/tagproj.cgi.
495 # You may want to install the HTML::TagCloud Perl module to get
496 # a pretty tag cloud instead of just a list of tags.
498 # To enable system wide have in $GITWEB_CONFIG
499 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
500 # Project specific override is not supported.
501 'ctags' => {
502 'override' => 0,
503 'default' => [0]},
505 # The maximum number of patches in a patchset generated in patch
506 # view. Set this to 0 or undef to disable patch view, or to a
507 # negative number to remove any limit.
509 # To disable system wide have in $GITWEB_CONFIG
510 # $feature{'patches'}{'default'} = [0];
511 # To have project specific config enable override in $GITWEB_CONFIG
512 # $feature{'patches'}{'override'} = 1;
513 # and in project config gitweb.patches = 0|n;
514 # where n is the maximum number of patches allowed in a patchset.
515 'patches' => {
516 'sub' => \&feature_patches,
517 'override' => 0,
518 'default' => [16]},
520 # Avatar support. When this feature is enabled, views such as
521 # shortlog or commit will display an avatar associated with
522 # the email of the committer(s) and/or author(s).
524 # Currently available providers are gravatar and picon.
525 # If an unknown provider is specified, the feature is disabled.
527 # Gravatar depends on Digest::MD5.
528 # Picon currently relies on the indiana.edu database.
530 # To enable system wide have in $GITWEB_CONFIG
531 # $feature{'avatar'}{'default'} = ['<provider>'];
532 # where <provider> is either gravatar or picon.
533 # To have project specific config enable override in $GITWEB_CONFIG
534 # $feature{'avatar'}{'override'} = 1;
535 # and in project config gitweb.avatar = <provider>;
536 'avatar' => {
537 'sub' => \&feature_avatar,
538 'override' => 0,
539 'default' => ['']},
541 # Enable displaying how much time and how many git commands
542 # it took to generate and display page. Disabled by default.
543 # Project specific override is not supported.
544 'timed' => {
545 'override' => 0,
546 'default' => [0]},
548 # Enable turning some links into links to actions which require
549 # JavaScript to run (like 'blame_incremental'). Not enabled by
550 # default. Project specific override is currently not supported.
551 'javascript-actions' => {
552 'override' => 0,
553 'default' => [0]},
555 # Syntax highlighting support. This is based on Daniel Svensson's
556 # and Sham Chukoury's work in gitweb-xmms2.git.
557 # It requires the 'highlight' program present in $PATH,
558 # and therefore is disabled by default.
560 # To enable system wide have in $GITWEB_CONFIG
561 # $feature{'highlight'}{'default'} = [1];
563 'highlight' => {
564 'sub' => sub { feature_bool('highlight', @_) },
565 'override' => 0,
566 'default' => [0]},
569 sub gitweb_get_feature {
570 my ($name) = @_;
571 return unless exists $feature{$name};
572 my ($sub, $override, @defaults) = (
573 $feature{$name}{'sub'},
574 $feature{$name}{'override'},
575 @{$feature{$name}{'default'}});
576 # project specific override is possible only if we have project
577 our $git_dir; # global variable, declared later
578 if (!$override || !defined $git_dir) {
579 return @defaults;
581 if (!defined $sub) {
582 warn "feature $name is not overridable";
583 return @defaults;
585 return $sub->(@defaults);
588 # A wrapper to check if a given feature is enabled.
589 # With this, you can say
591 # my $bool_feat = gitweb_check_feature('bool_feat');
592 # gitweb_check_feature('bool_feat') or somecode;
594 # instead of
596 # my ($bool_feat) = gitweb_get_feature('bool_feat');
597 # (gitweb_get_feature('bool_feat'))[0] or somecode;
599 sub gitweb_check_feature {
600 return (gitweb_get_feature(@_))[0];
604 sub feature_bool {
605 my $key = shift;
606 my ($val) = git_get_project_config($key, '--bool');
608 if (!defined $val) {
609 return ($_[0]);
610 } elsif ($val eq 'true') {
611 return (1);
612 } elsif ($val eq 'false') {
613 return (0);
617 sub feature_snapshot {
618 my (@fmts) = @_;
620 my ($val) = git_get_project_config('snapshot');
622 if ($val) {
623 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
626 return @fmts;
629 sub feature_patches {
630 my @val = (git_get_project_config('patches', '--int'));
632 if (@val) {
633 return @val;
636 return ($_[0]);
639 sub feature_avatar {
640 my @val = (git_get_project_config('avatar'));
642 return @val ? @val : @_;
645 # checking HEAD file with -e is fragile if the repository was
646 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
647 # and then pruned.
648 sub check_head_link {
649 my ($dir) = @_;
650 my $headfile = "$dir/HEAD";
651 return ((-e $headfile) ||
652 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
655 sub check_export_ok {
656 my ($dir) = @_;
657 return (check_head_link($dir) &&
658 (!$export_ok || -e "$dir/$export_ok") &&
659 (!$export_auth_hook || $export_auth_hook->($dir)));
662 # process alternate names for backward compatibility
663 # filter out unsupported (unknown) snapshot formats
664 sub filter_snapshot_fmts {
665 my @fmts = @_;
667 @fmts = map {
668 exists $known_snapshot_format_aliases{$_} ?
669 $known_snapshot_format_aliases{$_} : $_} @fmts;
670 @fmts = grep {
671 exists $known_snapshot_formats{$_} &&
672 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
675 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
676 sub evaluate_gitweb_config {
677 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
678 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
679 # die if there are errors parsing config file
680 if (-e $GITWEB_CONFIG) {
681 do $GITWEB_CONFIG;
682 die $@ if $@;
683 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
684 do $GITWEB_CONFIG_SYSTEM;
685 die $@ if $@;
689 # Get loadavg of system, to compare against $maxload.
690 # Currently it requires '/proc/loadavg' present to get loadavg;
691 # if it is not present it returns 0, which means no load checking.
692 sub get_loadavg {
693 if( -e '/proc/loadavg' ){
694 open my $fd, '<', '/proc/loadavg'
695 or return 0;
696 my @load = split(/\s+/, scalar <$fd>);
697 close $fd;
699 # The first three columns measure CPU and IO utilization of the last one,
700 # five, and 10 minute periods. The fourth column shows the number of
701 # currently running processes and the total number of processes in the m/n
702 # format. The last column displays the last process ID used.
703 return $load[0] || 0;
705 # additional checks for load average should go here for things that don't export
706 # /proc/loadavg
708 return 0;
711 # version of the core git binary
712 our $git_version;
713 sub evaluate_git_version {
714 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
715 $number_of_git_cmds++;
718 sub check_loadavg {
719 if (defined $maxload && get_loadavg() > $maxload) {
720 die_error(503, "The load average on the server is too high");
724 # ======================================================================
725 # input validation and dispatch
727 # input parameters can be collected from a variety of sources (presently, CGI
728 # and PATH_INFO), so we define an %input_params hash that collects them all
729 # together during validation: this allows subsequent uses (e.g. href()) to be
730 # agnostic of the parameter origin
732 our %input_params = ();
734 # input parameters are stored with the long parameter name as key. This will
735 # also be used in the href subroutine to convert parameters to their CGI
736 # equivalent, and since the href() usage is the most frequent one, we store
737 # the name -> CGI key mapping here, instead of the reverse.
739 # XXX: Warning: If you touch this, check the search form for updating,
740 # too.
742 our @cgi_param_mapping = (
743 project => "p",
744 action => "a",
745 file_name => "f",
746 file_parent => "fp",
747 hash => "h",
748 hash_parent => "hp",
749 hash_base => "hb",
750 hash_parent_base => "hpb",
751 page => "pg",
752 order => "o",
753 searchtext => "s",
754 searchtype => "st",
755 snapshot_format => "sf",
756 extra_options => "opt",
757 search_use_regexp => "sr",
758 # this must be last entry (for manipulation from JavaScript)
759 javascript => "js"
761 our %cgi_param_mapping = @cgi_param_mapping;
763 # we will also need to know the possible actions, for validation
764 our %actions = (
765 "blame" => \&git_blame,
766 "blame_incremental" => \&git_blame_incremental,
767 "blame_data" => \&git_blame_data,
768 "blobdiff" => \&git_blobdiff,
769 "blobdiff_plain" => \&git_blobdiff_plain,
770 "blob" => \&git_blob,
771 "blob_plain" => \&git_blob_plain,
772 "commitdiff" => \&git_commitdiff,
773 "commitdiff_plain" => \&git_commitdiff_plain,
774 "commit" => \&git_commit,
775 "forks" => \&git_forks,
776 "heads" => \&git_heads,
777 "history" => \&git_history,
778 "log" => \&git_log,
779 "patch" => \&git_patch,
780 "patches" => \&git_patches,
781 "rss" => \&git_rss,
782 "atom" => \&git_atom,
783 "search" => \&git_search,
784 "search_help" => \&git_search_help,
785 "shortlog" => \&git_shortlog,
786 "summary" => \&git_summary,
787 "tag" => \&git_tag,
788 "tags" => \&git_tags,
789 "tree" => \&git_tree,
790 "snapshot" => \&git_snapshot,
791 "object" => \&git_object,
792 # those below don't need $project
793 "opml" => \&git_opml,
794 "project_list" => \&git_project_list,
795 "project_index" => \&git_project_index,
798 # finally, we have the hash of allowed extra_options for the commands that
799 # allow them
800 our %allowed_options = (
801 "--no-merges" => [ qw(rss atom log shortlog history) ],
804 # fill %input_params with the CGI parameters. All values except for 'opt'
805 # should be single values, but opt can be an array. We should probably
806 # build an array of parameters that can be multi-valued, but since for the time
807 # being it's only this one, we just single it out
808 sub evaluate_query_params {
809 our $cgi;
811 while (my ($name, $symbol) = each %cgi_param_mapping) {
812 if ($symbol eq 'opt') {
813 $input_params{$name} = [ $cgi->param($symbol) ];
814 } else {
815 $input_params{$name} = $cgi->param($symbol);
820 # now read PATH_INFO and update the parameter list for missing parameters
821 sub evaluate_path_info {
822 return if defined $input_params{'project'};
823 return if !$path_info;
824 $path_info =~ s,^/+,,;
825 return if !$path_info;
827 # find which part of PATH_INFO is project
828 my $project = $path_info;
829 $project =~ s,/+$,,;
830 while ($project && !check_head_link("$projectroot/$project")) {
831 $project =~ s,/*[^/]*$,,;
833 return unless $project;
834 $input_params{'project'} = $project;
836 # do not change any parameters if an action is given using the query string
837 return if $input_params{'action'};
838 $path_info =~ s,^\Q$project\E/*,,;
840 # next, check if we have an action
841 my $action = $path_info;
842 $action =~ s,/.*$,,;
843 if (exists $actions{$action}) {
844 $path_info =~ s,^$action/*,,;
845 $input_params{'action'} = $action;
848 # list of actions that want hash_base instead of hash, but can have no
849 # pathname (f) parameter
850 my @wants_base = (
851 'tree',
852 'history',
855 # we want to catch, among others
856 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
857 my ($parentrefname, $parentpathname, $refname, $pathname) =
858 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
860 # first, analyze the 'current' part
861 if (defined $pathname) {
862 # we got "branch:filename" or "branch:dir/"
863 # we could use git_get_type(branch:pathname), but:
864 # - it needs $git_dir
865 # - it does a git() call
866 # - the convention of terminating directories with a slash
867 # makes it superfluous
868 # - embedding the action in the PATH_INFO would make it even
869 # more superfluous
870 $pathname =~ s,^/+,,;
871 if (!$pathname || substr($pathname, -1) eq "/") {
872 $input_params{'action'} ||= "tree";
873 $pathname =~ s,/$,,;
874 } else {
875 # the default action depends on whether we had parent info
876 # or not
877 if ($parentrefname) {
878 $input_params{'action'} ||= "blobdiff_plain";
879 } else {
880 $input_params{'action'} ||= "blob_plain";
883 $input_params{'hash_base'} ||= $refname;
884 $input_params{'file_name'} ||= $pathname;
885 } elsif (defined $refname) {
886 # we got "branch". In this case we have to choose if we have to
887 # set hash or hash_base.
889 # Most of the actions without a pathname only want hash to be
890 # set, except for the ones specified in @wants_base that want
891 # hash_base instead. It should also be noted that hand-crafted
892 # links having 'history' as an action and no pathname or hash
893 # set will fail, but that happens regardless of PATH_INFO.
894 if (defined $parentrefname) {
895 # if there is parent let the default be 'shortlog' action
896 # (for http://git.example.com/repo.git/A..B links); if there
897 # is no parent, dispatch will detect type of object and set
898 # action appropriately if required (if action is not set)
899 $input_params{'action'} ||= "shortlog";
901 if ($input_params{'action'} &&
902 grep { $_ eq $input_params{'action'} } @wants_base) {
903 $input_params{'hash_base'} ||= $refname;
904 } else {
905 $input_params{'hash'} ||= $refname;
909 # next, handle the 'parent' part, if present
910 if (defined $parentrefname) {
911 # a missing pathspec defaults to the 'current' filename, allowing e.g.
912 # someproject/blobdiff/oldrev..newrev:/filename
913 if ($parentpathname) {
914 $parentpathname =~ s,^/+,,;
915 $parentpathname =~ s,/$,,;
916 $input_params{'file_parent'} ||= $parentpathname;
917 } else {
918 $input_params{'file_parent'} ||= $input_params{'file_name'};
920 # we assume that hash_parent_base is wanted if a path was specified,
921 # or if the action wants hash_base instead of hash
922 if (defined $input_params{'file_parent'} ||
923 grep { $_ eq $input_params{'action'} } @wants_base) {
924 $input_params{'hash_parent_base'} ||= $parentrefname;
925 } else {
926 $input_params{'hash_parent'} ||= $parentrefname;
930 # for the snapshot action, we allow URLs in the form
931 # $project/snapshot/$hash.ext
932 # where .ext determines the snapshot and gets removed from the
933 # passed $refname to provide the $hash.
935 # To be able to tell that $refname includes the format extension, we
936 # require the following two conditions to be satisfied:
937 # - the hash input parameter MUST have been set from the $refname part
938 # of the URL (i.e. they must be equal)
939 # - the snapshot format MUST NOT have been defined already (e.g. from
940 # CGI parameter sf)
941 # It's also useless to try any matching unless $refname has a dot,
942 # so we check for that too
943 if (defined $input_params{'action'} &&
944 $input_params{'action'} eq 'snapshot' &&
945 defined $refname && index($refname, '.') != -1 &&
946 $refname eq $input_params{'hash'} &&
947 !defined $input_params{'snapshot_format'}) {
948 # We loop over the known snapshot formats, checking for
949 # extensions. Allowed extensions are both the defined suffix
950 # (which includes the initial dot already) and the snapshot
951 # format key itself, with a prepended dot
952 while (my ($fmt, $opt) = each %known_snapshot_formats) {
953 my $hash = $refname;
954 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
955 next;
957 my $sfx = $1;
958 # a valid suffix was found, so set the snapshot format
959 # and reset the hash parameter
960 $input_params{'snapshot_format'} = $fmt;
961 $input_params{'hash'} = $hash;
962 # we also set the format suffix to the one requested
963 # in the URL: this way a request for e.g. .tgz returns
964 # a .tgz instead of a .tar.gz
965 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
966 last;
971 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
972 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
973 $searchtext, $search_regexp);
974 sub evaluate_and_validate_params {
975 our $action = $input_params{'action'};
976 if (defined $action) {
977 if (!validate_action($action)) {
978 die_error(400, "Invalid action parameter");
982 # parameters which are pathnames
983 our $project = $input_params{'project'};
984 if (defined $project) {
985 if (!validate_project($project)) {
986 undef $project;
987 die_error(404, "No such project");
991 our $file_name = $input_params{'file_name'};
992 if (defined $file_name) {
993 if (!validate_pathname($file_name)) {
994 die_error(400, "Invalid file parameter");
998 our $file_parent = $input_params{'file_parent'};
999 if (defined $file_parent) {
1000 if (!validate_pathname($file_parent)) {
1001 die_error(400, "Invalid file parent parameter");
1005 # parameters which are refnames
1006 our $hash = $input_params{'hash'};
1007 if (defined $hash) {
1008 if (!validate_refname($hash)) {
1009 die_error(400, "Invalid hash parameter");
1013 our $hash_parent = $input_params{'hash_parent'};
1014 if (defined $hash_parent) {
1015 if (!validate_refname($hash_parent)) {
1016 die_error(400, "Invalid hash parent parameter");
1020 our $hash_base = $input_params{'hash_base'};
1021 if (defined $hash_base) {
1022 if (!validate_refname($hash_base)) {
1023 die_error(400, "Invalid hash base parameter");
1027 our @extra_options = @{$input_params{'extra_options'}};
1028 # @extra_options is always defined, since it can only be (currently) set from
1029 # CGI, and $cgi->param() returns the empty array in array context if the param
1030 # is not set
1031 foreach my $opt (@extra_options) {
1032 if (not exists $allowed_options{$opt}) {
1033 die_error(400, "Invalid option parameter");
1035 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1036 die_error(400, "Invalid option parameter for this action");
1040 our $hash_parent_base = $input_params{'hash_parent_base'};
1041 if (defined $hash_parent_base) {
1042 if (!validate_refname($hash_parent_base)) {
1043 die_error(400, "Invalid hash parent base parameter");
1047 # other parameters
1048 our $page = $input_params{'page'};
1049 if (defined $page) {
1050 if ($page =~ m/[^0-9]/) {
1051 die_error(400, "Invalid page parameter");
1055 our $searchtype = $input_params{'searchtype'};
1056 if (defined $searchtype) {
1057 if ($searchtype =~ m/[^a-z]/) {
1058 die_error(400, "Invalid searchtype parameter");
1062 our $search_use_regexp = $input_params{'search_use_regexp'};
1064 our $searchtext = $input_params{'searchtext'};
1065 our $search_regexp;
1066 if (defined $searchtext) {
1067 if (length($searchtext) < 2) {
1068 die_error(403, "At least two characters are required for search parameter");
1070 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1074 # path to the current git repository
1075 our $git_dir;
1076 sub evaluate_git_dir {
1077 our $git_dir = "$projectroot/$project" if $project;
1080 our (@snapshot_fmts, $git_avatar);
1081 sub configure_gitweb_features {
1082 # list of supported snapshot formats
1083 our @snapshot_fmts = gitweb_get_feature('snapshot');
1084 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1086 # check that the avatar feature is set to a known provider name,
1087 # and for each provider check if the dependencies are satisfied.
1088 # if the provider name is invalid or the dependencies are not met,
1089 # reset $git_avatar to the empty string.
1090 our ($git_avatar) = gitweb_get_feature('avatar');
1091 if ($git_avatar eq 'gravatar') {
1092 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1093 } elsif ($git_avatar eq 'picon') {
1094 # no dependencies
1095 } else {
1096 $git_avatar = '';
1100 # custom error handler: 'die <message>' is Internal Server Error
1101 sub handle_errors_html {
1102 my $msg = shift; # it is already HTML escaped
1104 # to avoid infinite loop where error occurs in die_error,
1105 # change handler to default handler, disabling handle_errors_html
1106 set_message("Error occured when inside die_error:\n$msg");
1108 # you cannot jump out of die_error when called as error handler;
1109 # the subroutine set via CGI::Carp::set_message is called _after_
1110 # HTTP headers are already written, so it cannot write them itself
1111 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1113 set_message(\&handle_errors_html);
1115 # dispatch
1116 sub dispatch {
1117 if (!defined $action) {
1118 if (defined $hash) {
1119 $action = git_get_type($hash);
1120 } elsif (defined $hash_base && defined $file_name) {
1121 $action = git_get_type("$hash_base:$file_name");
1122 } elsif (defined $project) {
1123 $action = 'summary';
1124 } else {
1125 $action = 'project_list';
1128 if (!defined($actions{$action})) {
1129 die_error(400, "Unknown action");
1131 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1132 !$project) {
1133 die_error(400, "Project needed");
1136 if ($caching_enabled) {
1137 # human readable key identifying gitweb output
1138 my $output_key = href(-replay => 1, -full => 1, -path_info => 0);
1140 cache_output($cache, $capture, $output_key, $actions{$action});
1141 } else {
1142 $actions{$action}->();
1146 sub reset_timer {
1147 our $t0 = [Time::HiRes::gettimeofday()]
1148 if defined $t0;
1149 our $number_of_git_cmds = 0;
1152 sub run_request {
1153 reset_timer();
1155 evaluate_uri();
1156 evaluate_gitweb_config();
1157 evaluate_git_version();
1158 check_loadavg();
1159 configure_caching()
1160 if ($caching_enabled);
1162 # $projectroot and $projects_list might be set in gitweb config file
1163 $projects_list ||= $projectroot;
1165 evaluate_query_params();
1166 evaluate_path_info();
1167 evaluate_and_validate_params();
1168 evaluate_git_dir();
1170 configure_gitweb_features();
1172 dispatch();
1175 our $is_last_request = sub { 1 };
1176 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1177 our $CGI = 'CGI';
1178 our $cgi;
1179 sub configure_as_fcgi {
1180 require CGI::Fast;
1181 our $CGI = 'CGI::Fast';
1183 my $request_number = 0;
1184 # let each child service 100 requests
1185 our $is_last_request = sub { ++$request_number > 100 };
1187 sub evaluate_argv {
1188 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1189 configure_as_fcgi()
1190 if $script_name =~ /\.fcgi$/;
1192 return unless (@ARGV);
1194 require Getopt::Long;
1195 Getopt::Long::GetOptions(
1196 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1197 'nproc|n=i' => sub {
1198 my ($arg, $val) = @_;
1199 return unless eval { require FCGI::ProcManager; 1; };
1200 my $proc_manager = FCGI::ProcManager->new({
1201 n_processes => $val,
1203 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1204 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1205 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1210 sub run {
1211 evaluate_argv();
1213 $pre_listen_hook->()
1214 if $pre_listen_hook;
1216 REQUEST:
1217 while ($cgi = $CGI->new()) {
1218 $pre_dispatch_hook->()
1219 if $pre_dispatch_hook;
1221 run_request();
1223 $post_dispatch_hook->()
1224 if $post_dispatch_hook;
1226 last REQUEST if ($is_last_request->());
1229 DONE_GITWEB:
1233 sub configure_caching {
1234 if (!eval { require GitwebCache::CacheOutput; 1; }) {
1235 # cache is configured _before_ handling request, so $cgi is not defined,
1236 # so we can't just "die" with sending error message to web browser
1237 #die_error(500, "Caching enabled and GitwebCache::CacheOutput not found");
1239 # turn off caching and warn instead
1240 $caching_enabled = 0;
1241 warn "Caching enabled and GitwebCache::CacheOutput not found";
1243 GitwebCache::CacheOutput->import();
1245 # $cache might be initialized (instantiated) cache, i.e. cache object,
1246 # or it might be name of class, or it might be undefined
1247 unless (defined $cache && ref($cache)) {
1248 $cache ||= 'GitwebCache::FileCacheWithLocking';
1249 eval "require $cache";
1250 die $@ if $@;
1251 $cache = $cache->new({
1252 %cache_options,
1253 #'cache_root' => '/tmp/cache',
1254 #'cache_depth' => 2,
1255 #'expires_in' => 20, # in seconds (CHI compatibile)
1256 # (Cache::Cache compatibile initialization)
1257 'default_expires_in' => $cache_options{'expires_in'},
1258 # (CHI compatibile initialization)
1259 'root_dir' => $cache_options{'cache_root'},
1260 'depth' => $cache_options{'cache_depth'},
1263 unless (defined $capture && ref($capture)) {
1264 require GitwebCache::Capture::Simple;
1265 $capture = GitwebCache::Capture::Simple->new();
1269 run();
1271 if (defined caller) {
1272 # wrapped in a subroutine processing requests,
1273 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1274 return;
1275 } else {
1276 # pure CGI script, serving single request
1277 exit;
1280 ## ======================================================================
1281 ## action links
1283 # possible values of extra options
1284 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1285 # -replay => 1 - start from a current view (replay with modifications)
1286 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1287 sub href {
1288 my %params = @_;
1289 # default is to use -absolute url() i.e. $my_uri
1290 my $href = $params{-full} ? $my_url : $my_uri;
1292 $params{'project'} = $project unless exists $params{'project'};
1294 if ($params{-replay}) {
1295 while (my ($name, $symbol) = each %cgi_param_mapping) {
1296 if (!exists $params{$name}) {
1297 $params{$name} = $input_params{$name};
1302 my $use_pathinfo = gitweb_check_feature('pathinfo');
1303 if (defined $params{'project'} &&
1304 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1305 # try to put as many parameters as possible in PATH_INFO:
1306 # - project name
1307 # - action
1308 # - hash_parent or hash_parent_base:/file_parent
1309 # - hash or hash_base:/filename
1310 # - the snapshot_format as an appropriate suffix
1312 # When the script is the root DirectoryIndex for the domain,
1313 # $href here would be something like http://gitweb.example.com/
1314 # Thus, we strip any trailing / from $href, to spare us double
1315 # slashes in the final URL
1316 $href =~ s,/$,,;
1318 # Then add the project name, if present
1319 $href .= "/".esc_url($params{'project'});
1320 delete $params{'project'};
1322 # since we destructively absorb parameters, we keep this
1323 # boolean that remembers if we're handling a snapshot
1324 my $is_snapshot = $params{'action'} eq 'snapshot';
1326 # Summary just uses the project path URL, any other action is
1327 # added to the URL
1328 if (defined $params{'action'}) {
1329 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1330 delete $params{'action'};
1333 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1334 # stripping nonexistent or useless pieces
1335 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1336 || $params{'hash_parent'} || $params{'hash'});
1337 if (defined $params{'hash_base'}) {
1338 if (defined $params{'hash_parent_base'}) {
1339 $href .= esc_url($params{'hash_parent_base'});
1340 # skip the file_parent if it's the same as the file_name
1341 if (defined $params{'file_parent'}) {
1342 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1343 delete $params{'file_parent'};
1344 } elsif ($params{'file_parent'} !~ /\.\./) {
1345 $href .= ":/".esc_url($params{'file_parent'});
1346 delete $params{'file_parent'};
1349 $href .= "..";
1350 delete $params{'hash_parent'};
1351 delete $params{'hash_parent_base'};
1352 } elsif (defined $params{'hash_parent'}) {
1353 $href .= esc_url($params{'hash_parent'}). "..";
1354 delete $params{'hash_parent'};
1357 $href .= esc_url($params{'hash_base'});
1358 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1359 $href .= ":/".esc_url($params{'file_name'});
1360 delete $params{'file_name'};
1362 delete $params{'hash'};
1363 delete $params{'hash_base'};
1364 } elsif (defined $params{'hash'}) {
1365 $href .= esc_url($params{'hash'});
1366 delete $params{'hash'};
1369 # If the action was a snapshot, we can absorb the
1370 # snapshot_format parameter too
1371 if ($is_snapshot) {
1372 my $fmt = $params{'snapshot_format'};
1373 # snapshot_format should always be defined when href()
1374 # is called, but just in case some code forgets, we
1375 # fall back to the default
1376 $fmt ||= $snapshot_fmts[0];
1377 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1378 delete $params{'snapshot_format'};
1382 # now encode the parameters explicitly
1383 my @result = ();
1384 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1385 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1386 if (defined $params{$name}) {
1387 if (ref($params{$name}) eq "ARRAY") {
1388 foreach my $par (@{$params{$name}}) {
1389 push @result, $symbol . "=" . esc_param($par);
1391 } else {
1392 push @result, $symbol . "=" . esc_param($params{$name});
1396 $href .= "?" . join(';', @result) if scalar @result;
1398 return $href;
1402 ## ======================================================================
1403 ## validation, quoting/unquoting and escaping
1405 sub validate_action {
1406 my $input = shift || return undef;
1407 return undef unless exists $actions{$input};
1408 return $input;
1411 sub validate_project {
1412 my $input = shift || return undef;
1413 if (!validate_pathname($input) ||
1414 !(-d "$projectroot/$input") ||
1415 !check_export_ok("$projectroot/$input") ||
1416 ($strict_export && !project_in_list($input))) {
1417 return undef;
1418 } else {
1419 return $input;
1423 sub validate_pathname {
1424 my $input = shift || return undef;
1426 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1427 # at the beginning, at the end, and between slashes.
1428 # also this catches doubled slashes
1429 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1430 return undef;
1432 # no null characters
1433 if ($input =~ m!\0!) {
1434 return undef;
1436 return $input;
1439 sub validate_refname {
1440 my $input = shift || return undef;
1442 # textual hashes are O.K.
1443 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1444 return $input;
1446 # it must be correct pathname
1447 $input = validate_pathname($input)
1448 or return undef;
1449 # restrictions on ref name according to git-check-ref-format
1450 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1451 return undef;
1453 return $input;
1456 # decode sequences of octets in utf8 into Perl's internal form,
1457 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1458 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1459 sub to_utf8 {
1460 my $str = shift;
1461 return undef unless defined $str;
1462 if (utf8::valid($str)) {
1463 utf8::decode($str);
1464 return $str;
1465 } else {
1466 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1470 # quote unsafe chars, but keep the slash, even when it's not
1471 # correct, but quoted slashes look too horrible in bookmarks
1472 sub esc_param {
1473 my $str = shift;
1474 return undef unless defined $str;
1475 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1476 $str =~ s/ /\+/g;
1477 return $str;
1480 # quote unsafe chars in whole URL, so some characters cannot be quoted
1481 sub esc_url {
1482 my $str = shift;
1483 return undef unless defined $str;
1484 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1485 $str =~ s/ /\+/g;
1486 return $str;
1489 # replace invalid utf8 character with SUBSTITUTION sequence
1490 sub esc_html {
1491 my $str = shift;
1492 my %opts = @_;
1494 return undef unless defined $str;
1496 $str = to_utf8($str);
1497 $str = $cgi->escapeHTML($str);
1498 if ($opts{'-nbsp'}) {
1499 $str =~ s/ /&nbsp;/g;
1501 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1502 return $str;
1505 # quote control characters and escape filename to HTML
1506 sub esc_path {
1507 my $str = shift;
1508 my %opts = @_;
1510 return undef unless defined $str;
1512 $str = to_utf8($str);
1513 $str = $cgi->escapeHTML($str);
1514 if ($opts{'-nbsp'}) {
1515 $str =~ s/ /&nbsp;/g;
1517 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1518 return $str;
1521 # Make control characters "printable", using character escape codes (CEC)
1522 sub quot_cec {
1523 my $cntrl = shift;
1524 my %opts = @_;
1525 my %es = ( # character escape codes, aka escape sequences
1526 "\t" => '\t', # tab (HT)
1527 "\n" => '\n', # line feed (LF)
1528 "\r" => '\r', # carrige return (CR)
1529 "\f" => '\f', # form feed (FF)
1530 "\b" => '\b', # backspace (BS)
1531 "\a" => '\a', # alarm (bell) (BEL)
1532 "\e" => '\e', # escape (ESC)
1533 "\013" => '\v', # vertical tab (VT)
1534 "\000" => '\0', # nul character (NUL)
1536 my $chr = ( (exists $es{$cntrl})
1537 ? $es{$cntrl}
1538 : sprintf('\%2x', ord($cntrl)) );
1539 if ($opts{-nohtml}) {
1540 return $chr;
1541 } else {
1542 return "<span class=\"cntrl\">$chr</span>";
1546 # Alternatively use unicode control pictures codepoints,
1547 # Unicode "printable representation" (PR)
1548 sub quot_upr {
1549 my $cntrl = shift;
1550 my %opts = @_;
1552 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1553 if ($opts{-nohtml}) {
1554 return $chr;
1555 } else {
1556 return "<span class=\"cntrl\">$chr</span>";
1560 # git may return quoted and escaped filenames
1561 sub unquote {
1562 my $str = shift;
1564 sub unq {
1565 my $seq = shift;
1566 my %es = ( # character escape codes, aka escape sequences
1567 't' => "\t", # tab (HT, TAB)
1568 'n' => "\n", # newline (NL)
1569 'r' => "\r", # return (CR)
1570 'f' => "\f", # form feed (FF)
1571 'b' => "\b", # backspace (BS)
1572 'a' => "\a", # alarm (bell) (BEL)
1573 'e' => "\e", # escape (ESC)
1574 'v' => "\013", # vertical tab (VT)
1577 if ($seq =~ m/^[0-7]{1,3}$/) {
1578 # octal char sequence
1579 return chr(oct($seq));
1580 } elsif (exists $es{$seq}) {
1581 # C escape sequence, aka character escape code
1582 return $es{$seq};
1584 # quoted ordinary character
1585 return $seq;
1588 if ($str =~ m/^"(.*)"$/) {
1589 # needs unquoting
1590 $str = $1;
1591 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1593 return $str;
1596 # escape tabs (convert tabs to spaces)
1597 sub untabify {
1598 my $line = shift;
1600 while ((my $pos = index($line, "\t")) != -1) {
1601 if (my $count = (8 - ($pos % 8))) {
1602 my $spaces = ' ' x $count;
1603 $line =~ s/\t/$spaces/;
1607 return $line;
1610 sub project_in_list {
1611 my $project = shift;
1612 my @list = git_get_projects_list();
1613 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1616 ## ----------------------------------------------------------------------
1617 ## HTML aware string manipulation
1619 # Try to chop given string on a word boundary between position
1620 # $len and $len+$add_len. If there is no word boundary there,
1621 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1622 # (marking chopped part) would be longer than given string.
1623 sub chop_str {
1624 my $str = shift;
1625 my $len = shift;
1626 my $add_len = shift || 10;
1627 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1629 # Make sure perl knows it is utf8 encoded so we don't
1630 # cut in the middle of a utf8 multibyte char.
1631 $str = to_utf8($str);
1633 # allow only $len chars, but don't cut a word if it would fit in $add_len
1634 # if it doesn't fit, cut it if it's still longer than the dots we would add
1635 # remove chopped character entities entirely
1637 # when chopping in the middle, distribute $len into left and right part
1638 # return early if chopping wouldn't make string shorter
1639 if ($where eq 'center') {
1640 return $str if ($len + 5 >= length($str)); # filler is length 5
1641 $len = int($len/2);
1642 } else {
1643 return $str if ($len + 4 >= length($str)); # filler is length 4
1646 # regexps: ending and beginning with word part up to $add_len
1647 my $endre = qr/.{$len}\w{0,$add_len}/;
1648 my $begre = qr/\w{0,$add_len}.{$len}/;
1650 if ($where eq 'left') {
1651 $str =~ m/^(.*?)($begre)$/;
1652 my ($lead, $body) = ($1, $2);
1653 if (length($lead) > 4) {
1654 $lead = " ...";
1656 return "$lead$body";
1658 } elsif ($where eq 'center') {
1659 $str =~ m/^($endre)(.*)$/;
1660 my ($left, $str) = ($1, $2);
1661 $str =~ m/^(.*?)($begre)$/;
1662 my ($mid, $right) = ($1, $2);
1663 if (length($mid) > 5) {
1664 $mid = " ... ";
1666 return "$left$mid$right";
1668 } else {
1669 $str =~ m/^($endre)(.*)$/;
1670 my $body = $1;
1671 my $tail = $2;
1672 if (length($tail) > 4) {
1673 $tail = "... ";
1675 return "$body$tail";
1679 # takes the same arguments as chop_str, but also wraps a <span> around the
1680 # result with a title attribute if it does get chopped. Additionally, the
1681 # string is HTML-escaped.
1682 sub chop_and_escape_str {
1683 my ($str) = @_;
1685 my $chopped = chop_str(@_);
1686 if ($chopped eq $str) {
1687 return esc_html($chopped);
1688 } else {
1689 $str =~ s/[[:cntrl:]]/?/g;
1690 return $cgi->span({-title=>$str}, esc_html($chopped));
1694 ## ----------------------------------------------------------------------
1695 ## functions returning short strings
1697 # CSS class for given age value (in seconds)
1698 sub age_class {
1699 my $age = shift;
1701 if (!defined $age) {
1702 return "noage";
1703 } elsif ($age < 60*60*2) {
1704 return "age0";
1705 } elsif ($age < 60*60*24*2) {
1706 return "age1";
1707 } else {
1708 return "age2";
1712 # convert age in seconds to "nn units ago" string
1713 sub age_string {
1714 my $age = shift;
1715 my $age_str;
1717 if ($age > 60*60*24*365*2) {
1718 $age_str = (int $age/60/60/24/365);
1719 $age_str .= " years ago";
1720 } elsif ($age > 60*60*24*(365/12)*2) {
1721 $age_str = int $age/60/60/24/(365/12);
1722 $age_str .= " months ago";
1723 } elsif ($age > 60*60*24*7*2) {
1724 $age_str = int $age/60/60/24/7;
1725 $age_str .= " weeks ago";
1726 } elsif ($age > 60*60*24*2) {
1727 $age_str = int $age/60/60/24;
1728 $age_str .= " days ago";
1729 } elsif ($age > 60*60*2) {
1730 $age_str = int $age/60/60;
1731 $age_str .= " hours ago";
1732 } elsif ($age > 60*2) {
1733 $age_str = int $age/60;
1734 $age_str .= " min ago";
1735 } elsif ($age > 2) {
1736 $age_str = int $age;
1737 $age_str .= " sec ago";
1738 } else {
1739 $age_str .= " right now";
1741 return $age_str;
1744 use constant {
1745 S_IFINVALID => 0030000,
1746 S_IFGITLINK => 0160000,
1749 # submodule/subproject, a commit object reference
1750 sub S_ISGITLINK {
1751 my $mode = shift;
1753 return (($mode & S_IFMT) == S_IFGITLINK)
1756 # convert file mode in octal to symbolic file mode string
1757 sub mode_str {
1758 my $mode = oct shift;
1760 if (S_ISGITLINK($mode)) {
1761 return 'm---------';
1762 } elsif (S_ISDIR($mode & S_IFMT)) {
1763 return 'drwxr-xr-x';
1764 } elsif (S_ISLNK($mode)) {
1765 return 'lrwxrwxrwx';
1766 } elsif (S_ISREG($mode)) {
1767 # git cares only about the executable bit
1768 if ($mode & S_IXUSR) {
1769 return '-rwxr-xr-x';
1770 } else {
1771 return '-rw-r--r--';
1773 } else {
1774 return '----------';
1778 # convert file mode in octal to file type string
1779 sub file_type {
1780 my $mode = shift;
1782 if ($mode !~ m/^[0-7]+$/) {
1783 return $mode;
1784 } else {
1785 $mode = oct $mode;
1788 if (S_ISGITLINK($mode)) {
1789 return "submodule";
1790 } elsif (S_ISDIR($mode & S_IFMT)) {
1791 return "directory";
1792 } elsif (S_ISLNK($mode)) {
1793 return "symlink";
1794 } elsif (S_ISREG($mode)) {
1795 return "file";
1796 } else {
1797 return "unknown";
1801 # convert file mode in octal to file type description string
1802 sub file_type_long {
1803 my $mode = shift;
1805 if ($mode !~ m/^[0-7]+$/) {
1806 return $mode;
1807 } else {
1808 $mode = oct $mode;
1811 if (S_ISGITLINK($mode)) {
1812 return "submodule";
1813 } elsif (S_ISDIR($mode & S_IFMT)) {
1814 return "directory";
1815 } elsif (S_ISLNK($mode)) {
1816 return "symlink";
1817 } elsif (S_ISREG($mode)) {
1818 if ($mode & S_IXUSR) {
1819 return "executable";
1820 } else {
1821 return "file";
1823 } else {
1824 return "unknown";
1829 ## ----------------------------------------------------------------------
1830 ## functions returning short HTML fragments, or transforming HTML fragments
1831 ## which don't belong to other sections
1833 # format line of commit message.
1834 sub format_log_line_html {
1835 my $line = shift;
1837 $line = esc_html($line, -nbsp=>1);
1838 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1839 $cgi->a({-href => href(action=>"object", hash=>$1),
1840 -class => "text"}, $1);
1841 }eg;
1843 return $line;
1846 # format marker of refs pointing to given object
1848 # the destination action is chosen based on object type and current context:
1849 # - for annotated tags, we choose the tag view unless it's the current view
1850 # already, in which case we go to shortlog view
1851 # - for other refs, we keep the current view if we're in history, shortlog or
1852 # log view, and select shortlog otherwise
1853 sub format_ref_marker {
1854 my ($refs, $id) = @_;
1855 my $markers = '';
1857 if (defined $refs->{$id}) {
1858 foreach my $ref (@{$refs->{$id}}) {
1859 # this code exploits the fact that non-lightweight tags are the
1860 # only indirect objects, and that they are the only objects for which
1861 # we want to use tag instead of shortlog as action
1862 my ($type, $name) = qw();
1863 my $indirect = ($ref =~ s/\^\{\}$//);
1864 # e.g. tags/v2.6.11 or heads/next
1865 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1866 $type = $1;
1867 $name = $2;
1868 } else {
1869 $type = "ref";
1870 $name = $ref;
1873 my $class = $type;
1874 $class .= " indirect" if $indirect;
1876 my $dest_action = "shortlog";
1878 if ($indirect) {
1879 $dest_action = "tag" unless $action eq "tag";
1880 } elsif ($action =~ /^(history|(short)?log)$/) {
1881 $dest_action = $action;
1884 my $dest = "";
1885 $dest .= "refs/" unless $ref =~ m!^refs/!;
1886 $dest .= $ref;
1888 my $link = $cgi->a({
1889 -href => href(
1890 action=>$dest_action,
1891 hash=>$dest
1892 )}, $name);
1894 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1895 $link . "</span>";
1899 if ($markers) {
1900 return ' <span class="refs">'. $markers . '</span>';
1901 } else {
1902 return "";
1906 # format, perhaps shortened and with markers, title line
1907 sub format_subject_html {
1908 my ($long, $short, $href, $extra) = @_;
1909 $extra = '' unless defined($extra);
1911 if (length($short) < length($long)) {
1912 $long =~ s/[[:cntrl:]]/?/g;
1913 return $cgi->a({-href => $href, -class => "list subject",
1914 -title => to_utf8($long)},
1915 esc_html($short)) . $extra;
1916 } else {
1917 return $cgi->a({-href => $href, -class => "list subject"},
1918 esc_html($long)) . $extra;
1922 # Rather than recomputing the url for an email multiple times, we cache it
1923 # after the first hit. This gives a visible benefit in views where the avatar
1924 # for the same email is used repeatedly (e.g. shortlog).
1925 # The cache is shared by all avatar engines (currently gravatar only), which
1926 # are free to use it as preferred. Since only one avatar engine is used for any
1927 # given page, there's no risk for cache conflicts.
1928 our %avatar_cache = ();
1930 # Compute the picon url for a given email, by using the picon search service over at
1931 # http://www.cs.indiana.edu/picons/search.html
1932 sub picon_url {
1933 my $email = lc shift;
1934 if (!$avatar_cache{$email}) {
1935 my ($user, $domain) = split('@', $email);
1936 $avatar_cache{$email} =
1937 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1938 "$domain/$user/" .
1939 "users+domains+unknown/up/single";
1941 return $avatar_cache{$email};
1944 # Compute the gravatar url for a given email, if it's not in the cache already.
1945 # Gravatar stores only the part of the URL before the size, since that's the
1946 # one computationally more expensive. This also allows reuse of the cache for
1947 # different sizes (for this particular engine).
1948 sub gravatar_url {
1949 my $email = lc shift;
1950 my $size = shift;
1951 $avatar_cache{$email} ||=
1952 "http://www.gravatar.com/avatar/" .
1953 Digest::MD5::md5_hex($email) . "?s=";
1954 return $avatar_cache{$email} . $size;
1957 # Insert an avatar for the given $email at the given $size if the feature
1958 # is enabled.
1959 sub git_get_avatar {
1960 my ($email, %opts) = @_;
1961 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1962 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1963 $opts{-size} ||= 'default';
1964 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1965 my $url = "";
1966 if ($git_avatar eq 'gravatar') {
1967 $url = gravatar_url($email, $size);
1968 } elsif ($git_avatar eq 'picon') {
1969 $url = picon_url($email);
1971 # Other providers can be added by extending the if chain, defining $url
1972 # as needed. If no variant puts something in $url, we assume avatars
1973 # are completely disabled/unavailable.
1974 if ($url) {
1975 return $pre_white .
1976 "<img width=\"$size\" " .
1977 "class=\"avatar\" " .
1978 "src=\"$url\" " .
1979 "alt=\"\" " .
1980 "/>" . $post_white;
1981 } else {
1982 return "";
1986 sub format_search_author {
1987 my ($author, $searchtype, $displaytext) = @_;
1988 my $have_search = gitweb_check_feature('search');
1990 if ($have_search) {
1991 my $performed = "";
1992 if ($searchtype eq 'author') {
1993 $performed = "authored";
1994 } elsif ($searchtype eq 'committer') {
1995 $performed = "committed";
1998 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1999 searchtext=>$author,
2000 searchtype=>$searchtype), class=>"list",
2001 title=>"Search for commits $performed by $author"},
2002 $displaytext);
2004 } else {
2005 return $displaytext;
2009 # format the author name of the given commit with the given tag
2010 # the author name is chopped and escaped according to the other
2011 # optional parameters (see chop_str).
2012 sub format_author_html {
2013 my $tag = shift;
2014 my $co = shift;
2015 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2016 return "<$tag class=\"author\">" .
2017 format_search_author($co->{'author_name'}, "author",
2018 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2019 $author) .
2020 "</$tag>";
2023 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2024 sub format_git_diff_header_line {
2025 my $line = shift;
2026 my $diffinfo = shift;
2027 my ($from, $to) = @_;
2029 if ($diffinfo->{'nparents'}) {
2030 # combined diff
2031 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2032 if ($to->{'href'}) {
2033 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2034 esc_path($to->{'file'}));
2035 } else { # file was deleted (no href)
2036 $line .= esc_path($to->{'file'});
2038 } else {
2039 # "ordinary" diff
2040 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2041 if ($from->{'href'}) {
2042 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2043 'a/' . esc_path($from->{'file'}));
2044 } else { # file was added (no href)
2045 $line .= 'a/' . esc_path($from->{'file'});
2047 $line .= ' ';
2048 if ($to->{'href'}) {
2049 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2050 'b/' . esc_path($to->{'file'}));
2051 } else { # file was deleted
2052 $line .= 'b/' . esc_path($to->{'file'});
2056 return "<div class=\"diff header\">$line</div>\n";
2059 # format extended diff header line, before patch itself
2060 sub format_extended_diff_header_line {
2061 my $line = shift;
2062 my $diffinfo = shift;
2063 my ($from, $to) = @_;
2065 # match <path>
2066 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2067 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2068 esc_path($from->{'file'}));
2070 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2071 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2072 esc_path($to->{'file'}));
2074 # match single <mode>
2075 if ($line =~ m/\s(\d{6})$/) {
2076 $line .= '<span class="info"> (' .
2077 file_type_long($1) .
2078 ')</span>';
2080 # match <hash>
2081 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2082 # can match only for combined diff
2083 $line = 'index ';
2084 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2085 if ($from->{'href'}[$i]) {
2086 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2087 -class=>"hash"},
2088 substr($diffinfo->{'from_id'}[$i],0,7));
2089 } else {
2090 $line .= '0' x 7;
2092 # separator
2093 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2095 $line .= '..';
2096 if ($to->{'href'}) {
2097 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2098 substr($diffinfo->{'to_id'},0,7));
2099 } else {
2100 $line .= '0' x 7;
2103 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2104 # can match only for ordinary diff
2105 my ($from_link, $to_link);
2106 if ($from->{'href'}) {
2107 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2108 substr($diffinfo->{'from_id'},0,7));
2109 } else {
2110 $from_link = '0' x 7;
2112 if ($to->{'href'}) {
2113 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2114 substr($diffinfo->{'to_id'},0,7));
2115 } else {
2116 $to_link = '0' x 7;
2118 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2119 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2122 return $line . "<br/>\n";
2125 # format from-file/to-file diff header
2126 sub format_diff_from_to_header {
2127 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2128 my $line;
2129 my $result = '';
2131 $line = $from_line;
2132 #assert($line =~ m/^---/) if DEBUG;
2133 # no extra formatting for "^--- /dev/null"
2134 if (! $diffinfo->{'nparents'}) {
2135 # ordinary (single parent) diff
2136 if ($line =~ m!^--- "?a/!) {
2137 if ($from->{'href'}) {
2138 $line = '--- a/' .
2139 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2140 esc_path($from->{'file'}));
2141 } else {
2142 $line = '--- a/' .
2143 esc_path($from->{'file'});
2146 $result .= qq!<div class="diff from_file">$line</div>\n!;
2148 } else {
2149 # combined diff (merge commit)
2150 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2151 if ($from->{'href'}[$i]) {
2152 $line = '--- ' .
2153 $cgi->a({-href=>href(action=>"blobdiff",
2154 hash_parent=>$diffinfo->{'from_id'}[$i],
2155 hash_parent_base=>$parents[$i],
2156 file_parent=>$from->{'file'}[$i],
2157 hash=>$diffinfo->{'to_id'},
2158 hash_base=>$hash,
2159 file_name=>$to->{'file'}),
2160 -class=>"path",
2161 -title=>"diff" . ($i+1)},
2162 $i+1) .
2163 '/' .
2164 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2165 esc_path($from->{'file'}[$i]));
2166 } else {
2167 $line = '--- /dev/null';
2169 $result .= qq!<div class="diff from_file">$line</div>\n!;
2173 $line = $to_line;
2174 #assert($line =~ m/^\+\+\+/) if DEBUG;
2175 # no extra formatting for "^+++ /dev/null"
2176 if ($line =~ m!^\+\+\+ "?b/!) {
2177 if ($to->{'href'}) {
2178 $line = '+++ b/' .
2179 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2180 esc_path($to->{'file'}));
2181 } else {
2182 $line = '+++ b/' .
2183 esc_path($to->{'file'});
2186 $result .= qq!<div class="diff to_file">$line</div>\n!;
2188 return $result;
2191 # create note for patch simplified by combined diff
2192 sub format_diff_cc_simplified {
2193 my ($diffinfo, @parents) = @_;
2194 my $result = '';
2196 $result .= "<div class=\"diff header\">" .
2197 "diff --cc ";
2198 if (!is_deleted($diffinfo)) {
2199 $result .= $cgi->a({-href => href(action=>"blob",
2200 hash_base=>$hash,
2201 hash=>$diffinfo->{'to_id'},
2202 file_name=>$diffinfo->{'to_file'}),
2203 -class => "path"},
2204 esc_path($diffinfo->{'to_file'}));
2205 } else {
2206 $result .= esc_path($diffinfo->{'to_file'});
2208 $result .= "</div>\n" . # class="diff header"
2209 "<div class=\"diff nodifferences\">" .
2210 "Simple merge" .
2211 "</div>\n"; # class="diff nodifferences"
2213 return $result;
2216 # format patch (diff) line (not to be used for diff headers)
2217 sub format_diff_line {
2218 my $line = shift;
2219 my ($from, $to) = @_;
2220 my $diff_class = "";
2222 chomp $line;
2224 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2225 # combined diff
2226 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2227 if ($line =~ m/^\@{3}/) {
2228 $diff_class = " chunk_header";
2229 } elsif ($line =~ m/^\\/) {
2230 $diff_class = " incomplete";
2231 } elsif ($prefix =~ tr/+/+/) {
2232 $diff_class = " add";
2233 } elsif ($prefix =~ tr/-/-/) {
2234 $diff_class = " rem";
2236 } else {
2237 # assume ordinary diff
2238 my $char = substr($line, 0, 1);
2239 if ($char eq '+') {
2240 $diff_class = " add";
2241 } elsif ($char eq '-') {
2242 $diff_class = " rem";
2243 } elsif ($char eq '@') {
2244 $diff_class = " chunk_header";
2245 } elsif ($char eq "\\") {
2246 $diff_class = " incomplete";
2249 $line = untabify($line);
2250 if ($from && $to && $line =~ m/^\@{2} /) {
2251 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2252 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2254 $from_lines = 0 unless defined $from_lines;
2255 $to_lines = 0 unless defined $to_lines;
2257 if ($from->{'href'}) {
2258 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2259 -class=>"list"}, $from_text);
2261 if ($to->{'href'}) {
2262 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2263 -class=>"list"}, $to_text);
2265 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2266 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2267 return "<div class=\"diff$diff_class\">$line</div>\n";
2268 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2269 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2270 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2272 @from_text = split(' ', $ranges);
2273 for (my $i = 0; $i < @from_text; ++$i) {
2274 ($from_start[$i], $from_nlines[$i]) =
2275 (split(',', substr($from_text[$i], 1)), 0);
2278 $to_text = pop @from_text;
2279 $to_start = pop @from_start;
2280 $to_nlines = pop @from_nlines;
2282 $line = "<span class=\"chunk_info\">$prefix ";
2283 for (my $i = 0; $i < @from_text; ++$i) {
2284 if ($from->{'href'}[$i]) {
2285 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2286 -class=>"list"}, $from_text[$i]);
2287 } else {
2288 $line .= $from_text[$i];
2290 $line .= " ";
2292 if ($to->{'href'}) {
2293 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2294 -class=>"list"}, $to_text);
2295 } else {
2296 $line .= $to_text;
2298 $line .= " $prefix</span>" .
2299 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2300 return "<div class=\"diff$diff_class\">$line</div>\n";
2302 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2305 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2306 # linked. Pass the hash of the tree/commit to snapshot.
2307 sub format_snapshot_links {
2308 my ($hash) = @_;
2309 my $num_fmts = @snapshot_fmts;
2310 if ($num_fmts > 1) {
2311 # A parenthesized list of links bearing format names.
2312 # e.g. "snapshot (_tar.gz_ _zip_)"
2313 return "snapshot (" . join(' ', map
2314 $cgi->a({
2315 -href => href(
2316 action=>"snapshot",
2317 hash=>$hash,
2318 snapshot_format=>$_
2320 }, $known_snapshot_formats{$_}{'display'})
2321 , @snapshot_fmts) . ")";
2322 } elsif ($num_fmts == 1) {
2323 # A single "snapshot" link whose tooltip bears the format name.
2324 # i.e. "_snapshot_"
2325 my ($fmt) = @snapshot_fmts;
2326 return
2327 $cgi->a({
2328 -href => href(
2329 action=>"snapshot",
2330 hash=>$hash,
2331 snapshot_format=>$fmt
2333 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2334 }, "snapshot");
2335 } else { # $num_fmts == 0
2336 return undef;
2340 ## ......................................................................
2341 ## functions returning values to be passed, perhaps after some
2342 ## transformation, to other functions; e.g. returning arguments to href()
2344 # returns hash to be passed to href to generate gitweb URL
2345 # in -title key it returns description of link
2346 sub get_feed_info {
2347 my $format = shift || 'Atom';
2348 my %res = (action => lc($format));
2350 # feed links are possible only for project views
2351 return unless (defined $project);
2352 # some views should link to OPML, or to generic project feed,
2353 # or don't have specific feed yet (so they should use generic)
2354 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2356 my $branch;
2357 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2358 # from tag links; this also makes possible to detect branch links
2359 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2360 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2361 $branch = $1;
2363 # find log type for feed description (title)
2364 my $type = 'log';
2365 if (defined $file_name) {
2366 $type = "history of $file_name";
2367 $type .= "/" if ($action eq 'tree');
2368 $type .= " on '$branch'" if (defined $branch);
2369 } else {
2370 $type = "log of $branch" if (defined $branch);
2373 $res{-title} = $type;
2374 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2375 $res{'file_name'} = $file_name;
2377 return %res;
2380 ## ----------------------------------------------------------------------
2381 ## git utility subroutines, invoking git commands
2383 # returns path to the core git executable and the --git-dir parameter as list
2384 sub git_cmd {
2385 $number_of_git_cmds++;
2386 return $GIT, '--git-dir='.$git_dir;
2389 # quote the given arguments for passing them to the shell
2390 # quote_command("command", "arg 1", "arg with ' and ! characters")
2391 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2392 # Try to avoid using this function wherever possible.
2393 sub quote_command {
2394 return join(' ',
2395 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2398 # get HEAD ref of given project as hash
2399 sub git_get_head_hash {
2400 return git_get_full_hash(shift, 'HEAD');
2403 sub git_get_full_hash {
2404 return git_get_hash(@_);
2407 sub git_get_short_hash {
2408 return git_get_hash(@_, '--short=7');
2411 sub git_get_hash {
2412 my ($project, $hash, @options) = @_;
2413 my $o_git_dir = $git_dir;
2414 my $retval = undef;
2415 $git_dir = "$projectroot/$project";
2416 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2417 '--verify', '-q', @options, $hash) {
2418 $retval = <$fd>;
2419 chomp $retval if defined $retval;
2420 close $fd;
2422 if (defined $o_git_dir) {
2423 $git_dir = $o_git_dir;
2425 return $retval;
2428 # get type of given object
2429 sub git_get_type {
2430 my $hash = shift;
2432 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2433 my $type = <$fd>;
2434 close $fd or return;
2435 chomp $type;
2436 return $type;
2439 # repository configuration
2440 our $config_file = '';
2441 our %config;
2443 # store multiple values for single key as anonymous array reference
2444 # single values stored directly in the hash, not as [ <value> ]
2445 sub hash_set_multi {
2446 my ($hash, $key, $value) = @_;
2448 if (!exists $hash->{$key}) {
2449 $hash->{$key} = $value;
2450 } elsif (!ref $hash->{$key}) {
2451 $hash->{$key} = [ $hash->{$key}, $value ];
2452 } else {
2453 push @{$hash->{$key}}, $value;
2457 # return hash of git project configuration
2458 # optionally limited to some section, e.g. 'gitweb'
2459 sub git_parse_project_config {
2460 my $section_regexp = shift;
2461 my %config;
2463 local $/ = "\0";
2465 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2466 or return;
2468 while (my $keyval = <$fh>) {
2469 chomp $keyval;
2470 my ($key, $value) = split(/\n/, $keyval, 2);
2472 hash_set_multi(\%config, $key, $value)
2473 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2475 close $fh;
2477 return %config;
2480 # convert config value to boolean: 'true' or 'false'
2481 # no value, number > 0, 'true' and 'yes' values are true
2482 # rest of values are treated as false (never as error)
2483 sub config_to_bool {
2484 my $val = shift;
2486 return 1 if !defined $val; # section.key
2488 # strip leading and trailing whitespace
2489 $val =~ s/^\s+//;
2490 $val =~ s/\s+$//;
2492 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2493 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2496 # convert config value to simple decimal number
2497 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2498 # to be multiplied by 1024, 1048576, or 1073741824
2499 sub config_to_int {
2500 my $val = shift;
2502 # strip leading and trailing whitespace
2503 $val =~ s/^\s+//;
2504 $val =~ s/\s+$//;
2506 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2507 $unit = lc($unit);
2508 # unknown unit is treated as 1
2509 return $num * ($unit eq 'g' ? 1073741824 :
2510 $unit eq 'm' ? 1048576 :
2511 $unit eq 'k' ? 1024 : 1);
2513 return $val;
2516 # convert config value to array reference, if needed
2517 sub config_to_multi {
2518 my $val = shift;
2520 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2523 sub git_get_project_config {
2524 my ($key, $type) = @_;
2526 return unless defined $git_dir;
2528 # key sanity check
2529 return unless ($key);
2530 $key =~ s/^gitweb\.//;
2531 return if ($key =~ m/\W/);
2533 # type sanity check
2534 if (defined $type) {
2535 $type =~ s/^--//;
2536 $type = undef
2537 unless ($type eq 'bool' || $type eq 'int');
2540 # get config
2541 if (!defined $config_file ||
2542 $config_file ne "$git_dir/config") {
2543 %config = git_parse_project_config('gitweb');
2544 $config_file = "$git_dir/config";
2547 # check if config variable (key) exists
2548 return unless exists $config{"gitweb.$key"};
2550 # ensure given type
2551 if (!defined $type) {
2552 return $config{"gitweb.$key"};
2553 } elsif ($type eq 'bool') {
2554 # backward compatibility: 'git config --bool' returns true/false
2555 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2556 } elsif ($type eq 'int') {
2557 return config_to_int($config{"gitweb.$key"});
2559 return $config{"gitweb.$key"};
2562 # get hash of given path at given ref
2563 sub git_get_hash_by_path {
2564 my $base = shift;
2565 my $path = shift || return undef;
2566 my $type = shift;
2568 $path =~ s,/+$,,;
2570 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2571 or die_error(500, "Open git-ls-tree failed");
2572 my $line = <$fd>;
2573 close $fd or return undef;
2575 if (!defined $line) {
2576 # there is no tree or hash given by $path at $base
2577 return undef;
2580 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2581 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2582 if (defined $type && $type ne $2) {
2583 # type doesn't match
2584 return undef;
2586 return $3;
2589 # get path of entry with given hash at given tree-ish (ref)
2590 # used to get 'from' filename for combined diff (merge commit) for renames
2591 sub git_get_path_by_hash {
2592 my $base = shift || return;
2593 my $hash = shift || return;
2595 local $/ = "\0";
2597 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2598 or return undef;
2599 while (my $line = <$fd>) {
2600 chomp $line;
2602 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2603 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2604 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2605 close $fd;
2606 return $1;
2609 close $fd;
2610 return undef;
2613 ## ......................................................................
2614 ## git utility functions, directly accessing git repository
2616 sub git_get_project_description {
2617 my $path = shift;
2619 $git_dir = "$projectroot/$path";
2620 open my $fd, '<', "$git_dir/description"
2621 or return git_get_project_config('description');
2622 my $descr = <$fd>;
2623 close $fd;
2624 if (defined $descr) {
2625 chomp $descr;
2627 return $descr;
2630 sub git_get_project_ctags {
2631 my $path = shift;
2632 my $ctags = {};
2634 $git_dir = "$projectroot/$path";
2635 opendir my $dh, "$git_dir/ctags"
2636 or return $ctags;
2637 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2638 open my $ct, '<', $_ or next;
2639 my $val = <$ct>;
2640 chomp $val;
2641 close $ct;
2642 my $ctag = $_; $ctag =~ s#.*/##;
2643 $ctags->{$ctag} = $val;
2645 closedir $dh;
2646 $ctags;
2649 sub git_populate_project_tagcloud {
2650 my $ctags = shift;
2652 # First, merge different-cased tags; tags vote on casing
2653 my %ctags_lc;
2654 foreach (keys %$ctags) {
2655 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2656 if (not $ctags_lc{lc $_}->{topcount}
2657 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2658 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2659 $ctags_lc{lc $_}->{topname} = $_;
2663 my $cloud;
2664 if (eval { require HTML::TagCloud; 1; }) {
2665 $cloud = HTML::TagCloud->new;
2666 foreach (sort keys %ctags_lc) {
2667 # Pad the title with spaces so that the cloud looks
2668 # less crammed.
2669 my $title = $ctags_lc{$_}->{topname};
2670 $title =~ s/ /&nbsp;/g;
2671 $title =~ s/^/&nbsp;/g;
2672 $title =~ s/$/&nbsp;/g;
2673 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2675 } else {
2676 $cloud = \%ctags_lc;
2678 $cloud;
2681 sub git_show_project_tagcloud {
2682 my ($cloud, $count) = @_;
2683 print STDERR ref($cloud)."..\n";
2684 if (ref $cloud eq 'HTML::TagCloud') {
2685 return $cloud->html_and_css($count);
2686 } else {
2687 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2688 return '<p align="center">' . join (', ', map {
2689 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2690 } splice(@tags, 0, $count)) . '</p>';
2694 sub git_get_project_url_list {
2695 my $path = shift;
2697 $git_dir = "$projectroot/$path";
2698 open my $fd, '<', "$git_dir/cloneurl"
2699 or return wantarray ?
2700 @{ config_to_multi(git_get_project_config('url')) } :
2701 config_to_multi(git_get_project_config('url'));
2702 my @git_project_url_list = map { chomp; $_ } <$fd>;
2703 close $fd;
2705 return wantarray ? @git_project_url_list : \@git_project_url_list;
2708 sub git_get_projects_list {
2709 my ($filter) = @_;
2710 my @list;
2712 $filter ||= '';
2713 $filter =~ s/\.git$//;
2715 my $check_forks = gitweb_check_feature('forks');
2717 if (-d $projects_list) {
2718 # search in directory
2719 my $dir = $projects_list . ($filter ? "/$filter" : '');
2720 # remove the trailing "/"
2721 $dir =~ s!/+$!!;
2722 my $pfxlen = length("$dir");
2723 my $pfxdepth = ($dir =~ tr!/!!);
2725 File::Find::find({
2726 follow_fast => 1, # follow symbolic links
2727 follow_skip => 2, # ignore duplicates
2728 dangling_symlinks => 0, # ignore dangling symlinks, silently
2729 wanted => sub {
2730 # global variables
2731 our $project_maxdepth;
2732 our $projectroot;
2733 # skip project-list toplevel, if we get it.
2734 return if (m!^[/.]$!);
2735 # only directories can be git repositories
2736 return unless (-d $_);
2737 # don't traverse too deep (Find is super slow on os x)
2738 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2739 $File::Find::prune = 1;
2740 return;
2743 my $subdir = substr($File::Find::name, $pfxlen + 1);
2744 # we check related file in $projectroot
2745 my $path = ($filter ? "$filter/" : '') . $subdir;
2746 if (check_export_ok("$projectroot/$path")) {
2747 push @list, { path => $path };
2748 $File::Find::prune = 1;
2751 }, "$dir");
2753 } elsif (-f $projects_list) {
2754 # read from file(url-encoded):
2755 # 'git%2Fgit.git Linus+Torvalds'
2756 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2757 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2758 my %paths;
2759 open my $fd, '<', $projects_list or return;
2760 PROJECT:
2761 while (my $line = <$fd>) {
2762 chomp $line;
2763 my ($path, $owner) = split ' ', $line;
2764 $path = unescape($path);
2765 $owner = unescape($owner);
2766 if (!defined $path) {
2767 next;
2769 if ($filter ne '') {
2770 # looking for forks;
2771 my $pfx = substr($path, 0, length($filter));
2772 if ($pfx ne $filter) {
2773 next PROJECT;
2775 my $sfx = substr($path, length($filter));
2776 if ($sfx !~ /^\/.*\.git$/) {
2777 next PROJECT;
2779 } elsif ($check_forks) {
2780 PATH:
2781 foreach my $filter (keys %paths) {
2782 # looking for forks;
2783 my $pfx = substr($path, 0, length($filter));
2784 if ($pfx ne $filter) {
2785 next PATH;
2787 my $sfx = substr($path, length($filter));
2788 if ($sfx !~ /^\/.*\.git$/) {
2789 next PATH;
2791 # is a fork, don't include it in
2792 # the list
2793 next PROJECT;
2796 if (check_export_ok("$projectroot/$path")) {
2797 my $pr = {
2798 path => $path,
2799 owner => to_utf8($owner),
2801 push @list, $pr;
2802 (my $forks_path = $path) =~ s/\.git$//;
2803 $paths{$forks_path}++;
2806 close $fd;
2808 return @list;
2811 our $gitweb_project_owner = undef;
2812 sub git_get_project_list_from_file {
2814 return if (defined $gitweb_project_owner);
2816 $gitweb_project_owner = {};
2817 # read from file (url-encoded):
2818 # 'git%2Fgit.git Linus+Torvalds'
2819 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2820 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2821 if (-f $projects_list) {
2822 open(my $fd, '<', $projects_list);
2823 while (my $line = <$fd>) {
2824 chomp $line;
2825 my ($pr, $ow) = split ' ', $line;
2826 $pr = unescape($pr);
2827 $ow = unescape($ow);
2828 $gitweb_project_owner->{$pr} = to_utf8($ow);
2830 close $fd;
2834 sub git_get_project_owner {
2835 my $project = shift;
2836 my $owner;
2838 return undef unless $project;
2839 $git_dir = "$projectroot/$project";
2841 if (!defined $gitweb_project_owner) {
2842 git_get_project_list_from_file();
2845 if (exists $gitweb_project_owner->{$project}) {
2846 $owner = $gitweb_project_owner->{$project};
2848 if (!defined $owner){
2849 $owner = git_get_project_config('owner');
2851 if (!defined $owner) {
2852 $owner = get_file_owner("$git_dir");
2855 return $owner;
2858 sub git_get_last_activity {
2859 my ($path) = @_;
2860 my $fd;
2862 $git_dir = "$projectroot/$path";
2863 open($fd, "-|", git_cmd(), 'for-each-ref',
2864 '--format=%(committer)',
2865 '--sort=-committerdate',
2866 '--count=1',
2867 'refs/heads') or return;
2868 my $most_recent = <$fd>;
2869 close $fd or return;
2870 if (defined $most_recent &&
2871 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2872 my $timestamp = $1;
2873 my $age = time - $timestamp;
2874 return ($age, age_string($age));
2876 return (undef, undef);
2879 sub git_get_references {
2880 my $type = shift || "";
2881 my %refs;
2882 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2883 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2884 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2885 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2886 or return;
2888 while (my $line = <$fd>) {
2889 chomp $line;
2890 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2891 if (defined $refs{$1}) {
2892 push @{$refs{$1}}, $2;
2893 } else {
2894 $refs{$1} = [ $2 ];
2898 close $fd or return;
2899 return \%refs;
2902 sub git_get_rev_name_tags {
2903 my $hash = shift || return undef;
2905 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2906 or return;
2907 my $name_rev = <$fd>;
2908 close $fd;
2910 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2911 return $1;
2912 } else {
2913 # catches also '$hash undefined' output
2914 return undef;
2918 ## ----------------------------------------------------------------------
2919 ## parse to hash functions
2921 sub parse_date {
2922 my $epoch = shift;
2923 my $tz = shift || "-0000";
2925 my %date;
2926 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2927 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2928 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2929 $date{'hour'} = $hour;
2930 $date{'minute'} = $min;
2931 $date{'mday'} = $mday;
2932 $date{'day'} = $days[$wday];
2933 $date{'month'} = $months[$mon];
2934 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2935 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2936 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2937 $mday, $months[$mon], $hour ,$min;
2938 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2939 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2941 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2942 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2943 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2944 $date{'hour_local'} = $hour;
2945 $date{'minute_local'} = $min;
2946 $date{'tz_local'} = $tz;
2947 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2948 1900+$year, $mon+1, $mday,
2949 $hour, $min, $sec, $tz);
2950 return %date;
2953 sub parse_tag {
2954 my $tag_id = shift;
2955 my %tag;
2956 my @comment;
2958 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2959 $tag{'id'} = $tag_id;
2960 while (my $line = <$fd>) {
2961 chomp $line;
2962 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2963 $tag{'object'} = $1;
2964 } elsif ($line =~ m/^type (.+)$/) {
2965 $tag{'type'} = $1;
2966 } elsif ($line =~ m/^tag (.+)$/) {
2967 $tag{'name'} = $1;
2968 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2969 $tag{'author'} = $1;
2970 $tag{'author_epoch'} = $2;
2971 $tag{'author_tz'} = $3;
2972 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2973 $tag{'author_name'} = $1;
2974 $tag{'author_email'} = $2;
2975 } else {
2976 $tag{'author_name'} = $tag{'author'};
2978 } elsif ($line =~ m/--BEGIN/) {
2979 push @comment, $line;
2980 last;
2981 } elsif ($line eq "") {
2982 last;
2985 push @comment, <$fd>;
2986 $tag{'comment'} = \@comment;
2987 close $fd or return;
2988 if (!defined $tag{'name'}) {
2989 return
2991 return %tag
2994 sub parse_commit_text {
2995 my ($commit_text, $withparents) = @_;
2996 my @commit_lines = split '\n', $commit_text;
2997 my %co;
2999 pop @commit_lines; # Remove '\0'
3001 if (! @commit_lines) {
3002 return;
3005 my $header = shift @commit_lines;
3006 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3007 return;
3009 ($co{'id'}, my @parents) = split ' ', $header;
3010 while (my $line = shift @commit_lines) {
3011 last if $line eq "\n";
3012 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3013 $co{'tree'} = $1;
3014 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3015 push @parents, $1;
3016 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3017 $co{'author'} = to_utf8($1);
3018 $co{'author_epoch'} = $2;
3019 $co{'author_tz'} = $3;
3020 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3021 $co{'author_name'} = $1;
3022 $co{'author_email'} = $2;
3023 } else {
3024 $co{'author_name'} = $co{'author'};
3026 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3027 $co{'committer'} = to_utf8($1);
3028 $co{'committer_epoch'} = $2;
3029 $co{'committer_tz'} = $3;
3030 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3031 $co{'committer_name'} = $1;
3032 $co{'committer_email'} = $2;
3033 } else {
3034 $co{'committer_name'} = $co{'committer'};
3038 if (!defined $co{'tree'}) {
3039 return;
3041 $co{'parents'} = \@parents;
3042 $co{'parent'} = $parents[0];
3044 foreach my $title (@commit_lines) {
3045 $title =~ s/^ //;
3046 if ($title ne "") {
3047 $co{'title'} = chop_str($title, 80, 5);
3048 # remove leading stuff of merges to make the interesting part visible
3049 if (length($title) > 50) {
3050 $title =~ s/^Automatic //;
3051 $title =~ s/^merge (of|with) /Merge ... /i;
3052 if (length($title) > 50) {
3053 $title =~ s/(http|rsync):\/\///;
3055 if (length($title) > 50) {
3056 $title =~ s/(master|www|rsync)\.//;
3058 if (length($title) > 50) {
3059 $title =~ s/kernel.org:?//;
3061 if (length($title) > 50) {
3062 $title =~ s/\/pub\/scm//;
3065 $co{'title_short'} = chop_str($title, 50, 5);
3066 last;
3069 if (! defined $co{'title'} || $co{'title'} eq "") {
3070 $co{'title'} = $co{'title_short'} = '(no commit message)';
3072 # remove added spaces
3073 foreach my $line (@commit_lines) {
3074 $line =~ s/^ //;
3076 $co{'comment'} = \@commit_lines;
3078 my $age = time - $co{'committer_epoch'};
3079 $co{'age'} = $age;
3080 $co{'age_string'} = age_string($age);
3081 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3082 if ($age > 60*60*24*7*2) {
3083 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3084 $co{'age_string_age'} = $co{'age_string'};
3085 } else {
3086 $co{'age_string_date'} = $co{'age_string'};
3087 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3089 return %co;
3092 sub parse_commit {
3093 my ($commit_id) = @_;
3094 my %co;
3096 local $/ = "\0";
3098 open my $fd, "-|", git_cmd(), "rev-list",
3099 "--parents",
3100 "--header",
3101 "--max-count=1",
3102 $commit_id,
3103 "--",
3104 or die_error(500, "Open git-rev-list failed");
3105 %co = parse_commit_text(<$fd>, 1);
3106 close $fd;
3108 return %co;
3111 sub parse_commits {
3112 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3113 my @cos;
3115 $maxcount ||= 1;
3116 $skip ||= 0;
3118 local $/ = "\0";
3120 open my $fd, "-|", git_cmd(), "rev-list",
3121 "--header",
3122 @args,
3123 ("--max-count=" . $maxcount),
3124 ("--skip=" . $skip),
3125 @extra_options,
3126 $commit_id,
3127 "--",
3128 ($filename ? ($filename) : ())
3129 or die_error(500, "Open git-rev-list failed");
3130 while (my $line = <$fd>) {
3131 my %co = parse_commit_text($line);
3132 push @cos, \%co;
3134 close $fd;
3136 return wantarray ? @cos : \@cos;
3139 # parse line of git-diff-tree "raw" output
3140 sub parse_difftree_raw_line {
3141 my $line = shift;
3142 my %res;
3144 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3145 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3146 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3147 $res{'from_mode'} = $1;
3148 $res{'to_mode'} = $2;
3149 $res{'from_id'} = $3;
3150 $res{'to_id'} = $4;
3151 $res{'status'} = $5;
3152 $res{'similarity'} = $6;
3153 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3154 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3155 } else {
3156 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3159 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3160 # combined diff (for merge commit)
3161 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3162 $res{'nparents'} = length($1);
3163 $res{'from_mode'} = [ split(' ', $2) ];
3164 $res{'to_mode'} = pop @{$res{'from_mode'}};
3165 $res{'from_id'} = [ split(' ', $3) ];
3166 $res{'to_id'} = pop @{$res{'from_id'}};
3167 $res{'status'} = [ split('', $4) ];
3168 $res{'to_file'} = unquote($5);
3170 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3171 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3172 $res{'commit'} = $1;
3175 return wantarray ? %res : \%res;
3178 # wrapper: return parsed line of git-diff-tree "raw" output
3179 # (the argument might be raw line, or parsed info)
3180 sub parsed_difftree_line {
3181 my $line_or_ref = shift;
3183 if (ref($line_or_ref) eq "HASH") {
3184 # pre-parsed (or generated by hand)
3185 return $line_or_ref;
3186 } else {
3187 return parse_difftree_raw_line($line_or_ref);
3191 # parse line of git-ls-tree output
3192 sub parse_ls_tree_line {
3193 my $line = shift;
3194 my %opts = @_;
3195 my %res;
3197 if ($opts{'-l'}) {
3198 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3199 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3201 $res{'mode'} = $1;
3202 $res{'type'} = $2;
3203 $res{'hash'} = $3;
3204 $res{'size'} = $4;
3205 if ($opts{'-z'}) {
3206 $res{'name'} = $5;
3207 } else {
3208 $res{'name'} = unquote($5);
3210 } else {
3211 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3212 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3214 $res{'mode'} = $1;
3215 $res{'type'} = $2;
3216 $res{'hash'} = $3;
3217 if ($opts{'-z'}) {
3218 $res{'name'} = $4;
3219 } else {
3220 $res{'name'} = unquote($4);
3224 return wantarray ? %res : \%res;
3227 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3228 sub parse_from_to_diffinfo {
3229 my ($diffinfo, $from, $to, @parents) = @_;
3231 if ($diffinfo->{'nparents'}) {
3232 # combined diff
3233 $from->{'file'} = [];
3234 $from->{'href'} = [];
3235 fill_from_file_info($diffinfo, @parents)
3236 unless exists $diffinfo->{'from_file'};
3237 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3238 $from->{'file'}[$i] =
3239 defined $diffinfo->{'from_file'}[$i] ?
3240 $diffinfo->{'from_file'}[$i] :
3241 $diffinfo->{'to_file'};
3242 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3243 $from->{'href'}[$i] = href(action=>"blob",
3244 hash_base=>$parents[$i],
3245 hash=>$diffinfo->{'from_id'}[$i],
3246 file_name=>$from->{'file'}[$i]);
3247 } else {
3248 $from->{'href'}[$i] = undef;
3251 } else {
3252 # ordinary (not combined) diff
3253 $from->{'file'} = $diffinfo->{'from_file'};
3254 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3255 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3256 hash=>$diffinfo->{'from_id'},
3257 file_name=>$from->{'file'});
3258 } else {
3259 delete $from->{'href'};
3263 $to->{'file'} = $diffinfo->{'to_file'};
3264 if (!is_deleted($diffinfo)) { # file exists in result
3265 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3266 hash=>$diffinfo->{'to_id'},
3267 file_name=>$to->{'file'});
3268 } else {
3269 delete $to->{'href'};
3273 ## ......................................................................
3274 ## parse to array of hashes functions
3276 sub git_get_heads_list {
3277 my $limit = shift;
3278 my @headslist;
3280 open my $fd, '-|', git_cmd(), 'for-each-ref',
3281 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3282 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3283 'refs/heads'
3284 or return;
3285 while (my $line = <$fd>) {
3286 my %ref_item;
3288 chomp $line;
3289 my ($refinfo, $committerinfo) = split(/\0/, $line);
3290 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3291 my ($committer, $epoch, $tz) =
3292 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3293 $ref_item{'fullname'} = $name;
3294 $name =~ s!^refs/heads/!!;
3296 $ref_item{'name'} = $name;
3297 $ref_item{'id'} = $hash;
3298 $ref_item{'title'} = $title || '(no commit message)';
3299 $ref_item{'epoch'} = $epoch;
3300 if ($epoch) {
3301 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3302 } else {
3303 $ref_item{'age'} = "unknown";
3306 push @headslist, \%ref_item;
3308 close $fd;
3310 return wantarray ? @headslist : \@headslist;
3313 sub git_get_tags_list {
3314 my $limit = shift;
3315 my @tagslist;
3317 open my $fd, '-|', git_cmd(), 'for-each-ref',
3318 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3319 '--format=%(objectname) %(objecttype) %(refname) '.
3320 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3321 'refs/tags'
3322 or return;
3323 while (my $line = <$fd>) {
3324 my %ref_item;
3326 chomp $line;
3327 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3328 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3329 my ($creator, $epoch, $tz) =
3330 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3331 $ref_item{'fullname'} = $name;
3332 $name =~ s!^refs/tags/!!;
3334 $ref_item{'type'} = $type;
3335 $ref_item{'id'} = $id;
3336 $ref_item{'name'} = $name;
3337 if ($type eq "tag") {
3338 $ref_item{'subject'} = $title;
3339 $ref_item{'reftype'} = $reftype;
3340 $ref_item{'refid'} = $refid;
3341 } else {
3342 $ref_item{'reftype'} = $type;
3343 $ref_item{'refid'} = $id;
3346 if ($type eq "tag" || $type eq "commit") {
3347 $ref_item{'epoch'} = $epoch;
3348 if ($epoch) {
3349 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3350 } else {
3351 $ref_item{'age'} = "unknown";
3355 push @tagslist, \%ref_item;
3357 close $fd;
3359 return wantarray ? @tagslist : \@tagslist;
3362 ## ----------------------------------------------------------------------
3363 ## filesystem-related functions
3365 sub get_file_owner {
3366 my $path = shift;
3368 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3369 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3370 if (!defined $gcos) {
3371 return undef;
3373 my $owner = $gcos;
3374 $owner =~ s/[,;].*$//;
3375 return to_utf8($owner);
3378 # assume that file exists
3379 sub insert_file {
3380 my $filename = shift;
3382 open my $fd, '<', $filename;
3383 print map { to_utf8($_) } <$fd>;
3384 close $fd;
3387 ## ......................................................................
3388 ## mimetype related functions
3390 sub mimetype_guess_file {
3391 my $filename = shift;
3392 my $mimemap = shift;
3393 -r $mimemap or return undef;
3395 my %mimemap;
3396 open(my $mh, '<', $mimemap) or return undef;
3397 while (<$mh>) {
3398 next if m/^#/; # skip comments
3399 my ($mimetype, $exts) = split(/\t+/);
3400 if (defined $exts) {
3401 my @exts = split(/\s+/, $exts);
3402 foreach my $ext (@exts) {
3403 $mimemap{$ext} = $mimetype;
3407 close($mh);
3409 $filename =~ /\.([^.]*)$/;
3410 return $mimemap{$1};
3413 sub mimetype_guess {
3414 my $filename = shift;
3415 my $mime;
3416 $filename =~ /\./ or return undef;
3418 if ($mimetypes_file) {
3419 my $file = $mimetypes_file;
3420 if ($file !~ m!^/!) { # if it is relative path
3421 # it is relative to project
3422 $file = "$projectroot/$project/$file";
3424 $mime = mimetype_guess_file($filename, $file);
3426 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3427 return $mime;
3430 sub blob_mimetype {
3431 my $fd = shift;
3432 my $filename = shift;
3434 if ($filename) {
3435 my $mime = mimetype_guess($filename);
3436 $mime and return $mime;
3439 # just in case
3440 return $default_blob_plain_mimetype unless $fd;
3442 if (-T $fd) {
3443 return 'text/plain';
3444 } elsif (! $filename) {
3445 return 'application/octet-stream';
3446 } elsif ($filename =~ m/\.png$/i) {
3447 return 'image/png';
3448 } elsif ($filename =~ m/\.gif$/i) {
3449 return 'image/gif';
3450 } elsif ($filename =~ m/\.jpe?g$/i) {
3451 return 'image/jpeg';
3452 } else {
3453 return 'application/octet-stream';
3457 sub blob_contenttype {
3458 my ($fd, $file_name, $type) = @_;
3460 $type ||= blob_mimetype($fd, $file_name);
3461 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3462 $type .= "; charset=$default_text_plain_charset";
3465 return $type;
3468 # guess file syntax for syntax highlighting; return undef if no highlighting
3469 # the name of syntax can (in the future) depend on syntax highlighter used
3470 sub guess_file_syntax {
3471 my ($highlight, $mimetype, $file_name) = @_;
3472 return undef unless ($highlight && defined $file_name);
3473 my $basename = basename($file_name, '.in');
3474 return $highlight_basename{$basename}
3475 if exists $highlight_basename{$basename};
3477 $basename =~ /\.([^.]*)$/;
3478 my $ext = $1 or return undef;
3479 return $highlight_ext{$ext}
3480 if exists $highlight_ext{$ext};
3482 return undef;
3485 # run highlighter and return FD of its output,
3486 # or return original FD if no highlighting
3487 sub run_highlighter {
3488 my ($fd, $highlight, $syntax) = @_;
3489 return $fd unless ($highlight && defined $syntax);
3491 close $fd
3492 or die_error(404, "Reading blob failed");
3493 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3494 quote_command($highlight_bin).
3495 " --xhtml --fragment --syntax $syntax |"
3496 or die_error(500, "Couldn't open file or run syntax highlighter");
3497 return $fd;
3500 ## ======================================================================
3501 ## functions printing HTML: header, footer, error page
3503 sub get_page_title {
3504 my $title = to_utf8($site_name);
3506 return $title unless (defined $project);
3507 $title .= " - " . to_utf8($project);
3509 return $title unless (defined $action);
3510 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3512 return $title unless (defined $file_name);
3513 $title .= " - " . esc_path($file_name);
3514 if ($action eq "tree" && $file_name !~ m|/$|) {
3515 $title .= "/";
3518 return $title;
3521 sub git_header_html {
3522 my $status = shift || "200 OK";
3523 my $expires = shift;
3524 my %opts = @_;
3526 my $title = get_page_title();
3527 my $content_type;
3528 # require explicit support from the UA if we are to send the page as
3529 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3530 # we have to do this because MSIE sometimes globs '*/*', pretending to
3531 # support xhtml+xml but choking when it gets what it asked for.
3532 # Disable content-type negotiation when caching (use mimetype good for all).
3533 if (!$caching_enabled &&
3534 defined $cgi->http('HTTP_ACCEPT') &&
3535 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3536 $cgi->Accept('application/xhtml+xml') != 0) {
3537 $content_type = 'application/xhtml+xml';
3538 } else {
3539 $content_type = 'text/html';
3541 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3542 -status=> $status, -expires => $expires)
3543 unless ($opts{'-no_http_header'});
3544 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3545 print <<EOF;
3546 <?xml version="1.0" encoding="utf-8"?>
3547 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3548 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3549 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3550 <!-- git core binaries version $git_version -->
3551 <head>
3552 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3553 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3554 <meta name="robots" content="index, nofollow"/>
3555 <title>$title</title>
3557 # the stylesheet, favicon etc urls won't work correctly with path_info
3558 # unless we set the appropriate base URL
3559 # if caching is enabled we can get it from cache for path_info when it
3560 # is generated without path_info
3561 if ($ENV{'PATH_INFO'} || $caching_enabled) {
3562 print "<base href=\"".esc_url($base_url)."\" />\n";
3564 # print out each stylesheet that exist, providing backwards capability
3565 # for those people who defined $stylesheet in a config file
3566 if (defined $stylesheet) {
3567 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3568 } else {
3569 foreach my $stylesheet (@stylesheets) {
3570 next unless $stylesheet;
3571 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3574 if (defined $project) {
3575 my %href_params = get_feed_info();
3576 if (!exists $href_params{'-title'}) {
3577 $href_params{'-title'} = 'log';
3580 foreach my $format qw(RSS Atom) {
3581 my $type = lc($format);
3582 my %link_attr = (
3583 '-rel' => 'alternate',
3584 '-title' => "$project - $href_params{'-title'} - $format feed",
3585 '-type' => "application/$type+xml"
3588 $href_params{'action'} = $type;
3589 $link_attr{'-href'} = href(%href_params);
3590 print "<link ".
3591 "rel=\"$link_attr{'-rel'}\" ".
3592 "title=\"$link_attr{'-title'}\" ".
3593 "href=\"$link_attr{'-href'}\" ".
3594 "type=\"$link_attr{'-type'}\" ".
3595 "/>\n";
3597 $href_params{'extra_options'} = '--no-merges';
3598 $link_attr{'-href'} = href(%href_params);
3599 $link_attr{'-title'} .= ' (no merges)';
3600 print "<link ".
3601 "rel=\"$link_attr{'-rel'}\" ".
3602 "title=\"$link_attr{'-title'}\" ".
3603 "href=\"$link_attr{'-href'}\" ".
3604 "type=\"$link_attr{'-type'}\" ".
3605 "/>\n";
3608 } else {
3609 printf('<link rel="alternate" title="%s projects list" '.
3610 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3611 $site_name, href(project=>undef, action=>"project_index"));
3612 printf('<link rel="alternate" title="%s projects feeds" '.
3613 'href="%s" type="text/x-opml" />'."\n",
3614 $site_name, href(project=>undef, action=>"opml"));
3616 if (defined $favicon) {
3617 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3620 print "</head>\n" .
3621 "<body>\n";
3623 if (defined $site_header && -f $site_header) {
3624 insert_file($site_header);
3627 print "<div class=\"page_header\">\n" .
3628 $cgi->a({-href => esc_url($logo_url),
3629 -title => $logo_label},
3630 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3631 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3632 if (defined $project) {
3633 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3634 if (defined $action) {
3635 print " / $action";
3637 print "\n";
3639 print "</div>\n";
3641 my $have_search = gitweb_check_feature('search');
3642 if (defined $project && $have_search) {
3643 if (!defined $searchtext) {
3644 $searchtext = "";
3646 my $search_hash;
3647 if (defined $hash_base) {
3648 $search_hash = $hash_base;
3649 } elsif (defined $hash) {
3650 $search_hash = $hash;
3651 } else {
3652 $search_hash = "HEAD";
3654 my $action = $my_uri;
3655 my $use_pathinfo = gitweb_check_feature('pathinfo');
3656 if ($use_pathinfo) {
3657 $action .= "/".esc_url($project);
3659 print $cgi->startform(-method => "get", -action => $action) .
3660 "<div class=\"search\">\n" .
3661 (!$use_pathinfo &&
3662 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3663 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3664 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3665 $cgi->popup_menu(-name => 'st', -default => 'commit',
3666 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3667 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3668 " search:\n",
3669 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3670 "<span title=\"Extended regular expression\">" .
3671 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3672 -checked => $search_use_regexp) .
3673 "</span>" .
3674 "</div>" .
3675 $cgi->end_form() . "\n";
3679 sub git_footer_html {
3680 my $feed_class = 'rss_logo';
3682 print "<div class=\"page_footer\">\n";
3683 if (defined $project) {
3684 my $descr = git_get_project_description($project);
3685 if (defined $descr) {
3686 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3689 my %href_params = get_feed_info();
3690 if (!%href_params) {
3691 $feed_class .= ' generic';
3693 $href_params{'-title'} ||= 'log';
3695 foreach my $format qw(RSS Atom) {
3696 $href_params{'action'} = lc($format);
3697 print $cgi->a({-href => href(%href_params),
3698 -title => "$href_params{'-title'} $format feed",
3699 -class => $feed_class}, $format)."\n";
3702 } else {
3703 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3704 -class => $feed_class}, "OPML") . " ";
3705 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3706 -class => $feed_class}, "TXT") . "\n";
3708 print "</div>\n"; # class="page_footer"
3710 # timing info doesn't make much sense with output (response) caching,
3711 # so when caching is enabled gitweb prints the time of page generation
3712 if ((defined $t0 || $caching_enabled) &&
3713 gitweb_check_feature('timed')) {
3714 print "<div id=\"generating_info\">\n";
3715 if ($caching_enabled) {
3716 print 'This page was generated at '.
3717 gmtime( time() )." GMT\n";
3718 } else {
3719 print 'This page took '.
3720 '<span id="generating_time" class="time_span">'.
3721 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3722 ' seconds </span>'.
3723 ' and '.
3724 '<span id="generating_cmd">'.
3725 $number_of_git_cmds.
3726 '</span> git commands '.
3727 " to generate.\n";
3729 print "</div>\n"; # class="page_footer"
3732 if (defined $site_footer && -f $site_footer) {
3733 insert_file($site_footer);
3736 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3737 if (!$caching_enabled &&
3738 defined $action && $action eq 'blame_incremental') {
3739 print qq!<script type="text/javascript">\n!.
3740 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3741 qq! "!. href() .qq!");\n!.
3742 qq!</script>\n!;
3743 } elsif (gitweb_check_feature('javascript-actions')) {
3744 print qq!<script type="text/javascript">\n!.
3745 qq!window.onload = fixLinks;\n!.
3746 qq!</script>\n!;
3749 print "</body>\n" .
3750 "</html>";
3753 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3754 # Example: die_error(404, 'Hash not found')
3755 # By convention, use the following status codes (as defined in RFC 2616):
3756 # 400: Invalid or missing CGI parameters, or
3757 # requested object exists but has wrong type.
3758 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3759 # this server or project.
3760 # 404: Requested object/revision/project doesn't exist.
3761 # 500: The server isn't configured properly, or
3762 # an internal error occurred (e.g. failed assertions caused by bugs), or
3763 # an unknown error occurred (e.g. the git binary died unexpectedly).
3764 # 503: The server is currently unavailable (because it is overloaded,
3765 # or down for maintenance). Generally, this is a temporary state.
3766 sub die_error {
3767 my $status = shift || 500;
3768 my $error = esc_html(shift) || "Internal Server Error";
3769 my $extra = shift;
3770 my %opts = @_;
3772 my %http_responses = (
3773 400 => '400 Bad Request',
3774 403 => '403 Forbidden',
3775 404 => '404 Not Found',
3776 500 => '500 Internal Server Error',
3777 503 => '503 Service Unavailable',
3780 # Do not cache error pages
3781 capture_stop($cache, $capture) if ($capture && $caching_enabled);
3783 git_header_html($http_responses{$status}, undef, %opts);
3784 print <<EOF;
3785 <div class="page_body">
3786 <br /><br />
3787 $status - $error
3788 <br />
3790 if (defined $extra) {
3791 print "<hr />\n" .
3792 "$extra\n";
3794 print "</div>\n";
3796 git_footer_html();
3797 goto DONE_GITWEB
3798 unless ($opts{'-error_handler'});
3801 ## ----------------------------------------------------------------------
3802 ## functions printing or outputting HTML: navigation
3804 sub git_print_page_nav {
3805 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3806 $extra = '' if !defined $extra; # pager or formats
3808 my @navs = qw(summary shortlog log commit commitdiff tree);
3809 if ($suppress) {
3810 @navs = grep { $_ ne $suppress } @navs;
3813 my %arg = map { $_ => {action=>$_} } @navs;
3814 if (defined $head) {
3815 for (qw(commit commitdiff)) {
3816 $arg{$_}{'hash'} = $head;
3818 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3819 for (qw(shortlog log)) {
3820 $arg{$_}{'hash'} = $head;
3825 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3826 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3828 my @actions = gitweb_get_feature('actions');
3829 my %repl = (
3830 '%' => '%',
3831 'n' => $project, # project name
3832 'f' => $git_dir, # project path within filesystem
3833 'h' => $treehead || '', # current hash ('h' parameter)
3834 'b' => $treebase || '', # hash base ('hb' parameter)
3836 while (@actions) {
3837 my ($label, $link, $pos) = splice(@actions,0,3);
3838 # insert
3839 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3840 # munch munch
3841 $link =~ s/%([%nfhb])/$repl{$1}/g;
3842 $arg{$label}{'_href'} = $link;
3845 print "<div class=\"page_nav\">\n" .
3846 (join " | ",
3847 map { $_ eq $current ?
3848 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3849 } @navs);
3850 print "<br/>\n$extra<br/>\n" .
3851 "</div>\n";
3854 sub format_paging_nav {
3855 my ($action, $page, $has_next_link) = @_;
3856 my $paging_nav;
3859 if ($page > 0) {
3860 $paging_nav .=
3861 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3862 " &sdot; " .
3863 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3864 -accesskey => "p", -title => "Alt-p"}, "prev");
3865 } else {
3866 $paging_nav .= "first &sdot; prev";
3869 if ($has_next_link) {
3870 $paging_nav .= " &sdot; " .
3871 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3872 -accesskey => "n", -title => "Alt-n"}, "next");
3873 } else {
3874 $paging_nav .= " &sdot; next";
3877 return $paging_nav;
3880 ## ......................................................................
3881 ## functions printing or outputting HTML: div
3883 sub git_print_header_div {
3884 my ($action, $title, $hash, $hash_base) = @_;
3885 my %args = ();
3887 $args{'action'} = $action;
3888 $args{'hash'} = $hash if $hash;
3889 $args{'hash_base'} = $hash_base if $hash_base;
3891 print "<div class=\"header\">\n" .
3892 $cgi->a({-href => href(%args), -class => "title"},
3893 $title ? $title : $action) .
3894 "\n</div>\n";
3897 sub print_local_time {
3898 print format_local_time(@_);
3901 sub format_local_time {
3902 my $localtime = '';
3903 my %date = @_;
3904 if ($date{'hour_local'} < 6) {
3905 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3906 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3907 } else {
3908 $localtime .= sprintf(" (%02d:%02d %s)",
3909 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3912 return $localtime;
3915 # Outputs the author name and date in long form
3916 sub git_print_authorship {
3917 my $co = shift;
3918 my %opts = @_;
3919 my $tag = $opts{-tag} || 'div';
3920 my $author = $co->{'author_name'};
3922 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3923 print "<$tag class=\"author_date\">" .
3924 format_search_author($author, "author", esc_html($author)) .
3925 " [$ad{'rfc2822'}";
3926 print_local_time(%ad) if ($opts{-localtime});
3927 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3928 . "</$tag>\n";
3931 # Outputs table rows containing the full author or committer information,
3932 # in the format expected for 'commit' view (& similar).
3933 # Parameters are a commit hash reference, followed by the list of people
3934 # to output information for. If the list is empty it defaults to both
3935 # author and committer.
3936 sub git_print_authorship_rows {
3937 my $co = shift;
3938 # too bad we can't use @people = @_ || ('author', 'committer')
3939 my @people = @_;
3940 @people = ('author', 'committer') unless @people;
3941 foreach my $who (@people) {
3942 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3943 print "<tr><td>$who</td><td>" .
3944 format_search_author($co->{"${who}_name"}, $who,
3945 esc_html($co->{"${who}_name"})) . " " .
3946 format_search_author($co->{"${who}_email"}, $who,
3947 esc_html("<" . $co->{"${who}_email"} . ">")) .
3948 "</td><td rowspan=\"2\">" .
3949 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3950 "</td></tr>\n" .
3951 "<tr>" .
3952 "<td></td><td> $wd{'rfc2822'}";
3953 print_local_time(%wd);
3954 print "</td>" .
3955 "</tr>\n";
3959 sub git_print_page_path {
3960 my $name = shift;
3961 my $type = shift;
3962 my $hb = shift;
3965 print "<div class=\"page_path\">";
3966 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3967 -title => 'tree root'}, to_utf8("[$project]"));
3968 print " / ";
3969 if (defined $name) {
3970 my @dirname = split '/', $name;
3971 my $basename = pop @dirname;
3972 my $fullname = '';
3974 foreach my $dir (@dirname) {
3975 $fullname .= ($fullname ? '/' : '') . $dir;
3976 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3977 hash_base=>$hb),
3978 -title => $fullname}, esc_path($dir));
3979 print " / ";
3981 if (defined $type && $type eq 'blob') {
3982 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3983 hash_base=>$hb),
3984 -title => $name}, esc_path($basename));
3985 } elsif (defined $type && $type eq 'tree') {
3986 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3987 hash_base=>$hb),
3988 -title => $name}, esc_path($basename));
3989 print " / ";
3990 } else {
3991 print esc_path($basename);
3994 print "<br/></div>\n";
3997 sub git_print_log {
3998 my $log = shift;
3999 my %opts = @_;
4001 if ($opts{'-remove_title'}) {
4002 # remove title, i.e. first line of log
4003 shift @$log;
4005 # remove leading empty lines
4006 while (defined $log->[0] && $log->[0] eq "") {
4007 shift @$log;
4010 # print log
4011 my $signoff = 0;
4012 my $empty = 0;
4013 foreach my $line (@$log) {
4014 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4015 $signoff = 1;
4016 $empty = 0;
4017 if (! $opts{'-remove_signoff'}) {
4018 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4019 next;
4020 } else {
4021 # remove signoff lines
4022 next;
4024 } else {
4025 $signoff = 0;
4028 # print only one empty line
4029 # do not print empty line after signoff
4030 if ($line eq "") {
4031 next if ($empty || $signoff);
4032 $empty = 1;
4033 } else {
4034 $empty = 0;
4037 print format_log_line_html($line) . "<br/>\n";
4040 if ($opts{'-final_empty_line'}) {
4041 # end with single empty line
4042 print "<br/>\n" unless $empty;
4046 # return link target (what link points to)
4047 sub git_get_link_target {
4048 my $hash = shift;
4049 my $link_target;
4051 # read link
4052 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4053 or return;
4055 local $/ = undef;
4056 $link_target = <$fd>;
4058 close $fd
4059 or return;
4061 return $link_target;
4064 # given link target, and the directory (basedir) the link is in,
4065 # return target of link relative to top directory (top tree);
4066 # return undef if it is not possible (including absolute links).
4067 sub normalize_link_target {
4068 my ($link_target, $basedir) = @_;
4070 # absolute symlinks (beginning with '/') cannot be normalized
4071 return if (substr($link_target, 0, 1) eq '/');
4073 # normalize link target to path from top (root) tree (dir)
4074 my $path;
4075 if ($basedir) {
4076 $path = $basedir . '/' . $link_target;
4077 } else {
4078 # we are in top (root) tree (dir)
4079 $path = $link_target;
4082 # remove //, /./, and /../
4083 my @path_parts;
4084 foreach my $part (split('/', $path)) {
4085 # discard '.' and ''
4086 next if (!$part || $part eq '.');
4087 # handle '..'
4088 if ($part eq '..') {
4089 if (@path_parts) {
4090 pop @path_parts;
4091 } else {
4092 # link leads outside repository (outside top dir)
4093 return;
4095 } else {
4096 push @path_parts, $part;
4099 $path = join('/', @path_parts);
4101 return $path;
4104 # print tree entry (row of git_tree), but without encompassing <tr> element
4105 sub git_print_tree_entry {
4106 my ($t, $basedir, $hash_base, $have_blame) = @_;
4108 my %base_key = ();
4109 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4111 # The format of a table row is: mode list link. Where mode is
4112 # the mode of the entry, list is the name of the entry, an href,
4113 # and link is the action links of the entry.
4115 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4116 if (exists $t->{'size'}) {
4117 print "<td class=\"size\">$t->{'size'}</td>\n";
4119 if ($t->{'type'} eq "blob") {
4120 print "<td class=\"list\">" .
4121 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4122 file_name=>"$basedir$t->{'name'}", %base_key),
4123 -class => "list"}, esc_path($t->{'name'}));
4124 if (S_ISLNK(oct $t->{'mode'})) {
4125 my $link_target = git_get_link_target($t->{'hash'});
4126 if ($link_target) {
4127 my $norm_target = normalize_link_target($link_target, $basedir);
4128 if (defined $norm_target) {
4129 print " -> " .
4130 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4131 file_name=>$norm_target),
4132 -title => $norm_target}, esc_path($link_target));
4133 } else {
4134 print " -> " . esc_path($link_target);
4138 print "</td>\n";
4139 print "<td class=\"link\">";
4140 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4141 file_name=>"$basedir$t->{'name'}", %base_key)},
4142 "blob");
4143 if ($have_blame) {
4144 print " | " .
4145 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4146 file_name=>"$basedir$t->{'name'}", %base_key)},
4147 "blame");
4149 if (defined $hash_base) {
4150 print " | " .
4151 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4152 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4153 "history");
4155 print " | " .
4156 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4157 file_name=>"$basedir$t->{'name'}")},
4158 "raw");
4159 print "</td>\n";
4161 } elsif ($t->{'type'} eq "tree") {
4162 print "<td class=\"list\">";
4163 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4164 file_name=>"$basedir$t->{'name'}",
4165 %base_key)},
4166 esc_path($t->{'name'}));
4167 print "</td>\n";
4168 print "<td class=\"link\">";
4169 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4170 file_name=>"$basedir$t->{'name'}",
4171 %base_key)},
4172 "tree");
4173 if (defined $hash_base) {
4174 print " | " .
4175 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4176 file_name=>"$basedir$t->{'name'}")},
4177 "history");
4179 print "</td>\n";
4180 } else {
4181 # unknown object: we can only present history for it
4182 # (this includes 'commit' object, i.e. submodule support)
4183 print "<td class=\"list\">" .
4184 esc_path($t->{'name'}) .
4185 "</td>\n";
4186 print "<td class=\"link\">";
4187 if (defined $hash_base) {
4188 print $cgi->a({-href => href(action=>"history",
4189 hash_base=>$hash_base,
4190 file_name=>"$basedir$t->{'name'}")},
4191 "history");
4193 print "</td>\n";
4197 ## ......................................................................
4198 ## functions printing large fragments of HTML
4200 # get pre-image filenames for merge (combined) diff
4201 sub fill_from_file_info {
4202 my ($diff, @parents) = @_;
4204 $diff->{'from_file'} = [ ];
4205 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4206 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4207 if ($diff->{'status'}[$i] eq 'R' ||
4208 $diff->{'status'}[$i] eq 'C') {
4209 $diff->{'from_file'}[$i] =
4210 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4214 return $diff;
4217 # is current raw difftree line of file deletion
4218 sub is_deleted {
4219 my $diffinfo = shift;
4221 return $diffinfo->{'to_id'} eq ('0' x 40);
4224 # does patch correspond to [previous] difftree raw line
4225 # $diffinfo - hashref of parsed raw diff format
4226 # $patchinfo - hashref of parsed patch diff format
4227 # (the same keys as in $diffinfo)
4228 sub is_patch_split {
4229 my ($diffinfo, $patchinfo) = @_;
4231 return defined $diffinfo && defined $patchinfo
4232 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4236 sub git_difftree_body {
4237 my ($difftree, $hash, @parents) = @_;
4238 my ($parent) = $parents[0];
4239 my $have_blame = gitweb_check_feature('blame');
4240 print "<div class=\"list_head\">\n";
4241 if ($#{$difftree} > 10) {
4242 print(($#{$difftree} + 1) . " files changed:\n");
4244 print "</div>\n";
4246 print "<table class=\"" .
4247 (@parents > 1 ? "combined " : "") .
4248 "diff_tree\">\n";
4250 # header only for combined diff in 'commitdiff' view
4251 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4252 if ($has_header) {
4253 # table header
4254 print "<thead><tr>\n" .
4255 "<th></th><th></th>\n"; # filename, patchN link
4256 for (my $i = 0; $i < @parents; $i++) {
4257 my $par = $parents[$i];
4258 print "<th>" .
4259 $cgi->a({-href => href(action=>"commitdiff",
4260 hash=>$hash, hash_parent=>$par),
4261 -title => 'commitdiff to parent number ' .
4262 ($i+1) . ': ' . substr($par,0,7)},
4263 $i+1) .
4264 "&nbsp;</th>\n";
4266 print "</tr></thead>\n<tbody>\n";
4269 my $alternate = 1;
4270 my $patchno = 0;
4271 foreach my $line (@{$difftree}) {
4272 my $diff = parsed_difftree_line($line);
4274 if ($alternate) {
4275 print "<tr class=\"dark\">\n";
4276 } else {
4277 print "<tr class=\"light\">\n";
4279 $alternate ^= 1;
4281 if (exists $diff->{'nparents'}) { # combined diff
4283 fill_from_file_info($diff, @parents)
4284 unless exists $diff->{'from_file'};
4286 if (!is_deleted($diff)) {
4287 # file exists in the result (child) commit
4288 print "<td>" .
4289 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4290 file_name=>$diff->{'to_file'},
4291 hash_base=>$hash),
4292 -class => "list"}, esc_path($diff->{'to_file'})) .
4293 "</td>\n";
4294 } else {
4295 print "<td>" .
4296 esc_path($diff->{'to_file'}) .
4297 "</td>\n";
4300 if ($action eq 'commitdiff') {
4301 # link to patch
4302 $patchno++;
4303 print "<td class=\"link\">" .
4304 $cgi->a({-href => "#patch$patchno"}, "patch") .
4305 " | " .
4306 "</td>\n";
4309 my $has_history = 0;
4310 my $not_deleted = 0;
4311 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4312 my $hash_parent = $parents[$i];
4313 my $from_hash = $diff->{'from_id'}[$i];
4314 my $from_path = $diff->{'from_file'}[$i];
4315 my $status = $diff->{'status'}[$i];
4317 $has_history ||= ($status ne 'A');
4318 $not_deleted ||= ($status ne 'D');
4320 if ($status eq 'A') {
4321 print "<td class=\"link\" align=\"right\"> | </td>\n";
4322 } elsif ($status eq 'D') {
4323 print "<td class=\"link\">" .
4324 $cgi->a({-href => href(action=>"blob",
4325 hash_base=>$hash,
4326 hash=>$from_hash,
4327 file_name=>$from_path)},
4328 "blob" . ($i+1)) .
4329 " | </td>\n";
4330 } else {
4331 if ($diff->{'to_id'} eq $from_hash) {
4332 print "<td class=\"link nochange\">";
4333 } else {
4334 print "<td class=\"link\">";
4336 print $cgi->a({-href => href(action=>"blobdiff",
4337 hash=>$diff->{'to_id'},
4338 hash_parent=>$from_hash,
4339 hash_base=>$hash,
4340 hash_parent_base=>$hash_parent,
4341 file_name=>$diff->{'to_file'},
4342 file_parent=>$from_path)},
4343 "diff" . ($i+1)) .
4344 " | </td>\n";
4348 print "<td class=\"link\">";
4349 if ($not_deleted) {
4350 print $cgi->a({-href => href(action=>"blob",
4351 hash=>$diff->{'to_id'},
4352 file_name=>$diff->{'to_file'},
4353 hash_base=>$hash)},
4354 "blob");
4355 print " | " if ($has_history);
4357 if ($has_history) {
4358 print $cgi->a({-href => href(action=>"history",
4359 file_name=>$diff->{'to_file'},
4360 hash_base=>$hash)},
4361 "history");
4363 print "</td>\n";
4365 print "</tr>\n";
4366 next; # instead of 'else' clause, to avoid extra indent
4368 # else ordinary diff
4370 my ($to_mode_oct, $to_mode_str, $to_file_type);
4371 my ($from_mode_oct, $from_mode_str, $from_file_type);
4372 if ($diff->{'to_mode'} ne ('0' x 6)) {
4373 $to_mode_oct = oct $diff->{'to_mode'};
4374 if (S_ISREG($to_mode_oct)) { # only for regular file
4375 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4377 $to_file_type = file_type($diff->{'to_mode'});
4379 if ($diff->{'from_mode'} ne ('0' x 6)) {
4380 $from_mode_oct = oct $diff->{'from_mode'};
4381 if (S_ISREG($to_mode_oct)) { # only for regular file
4382 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4384 $from_file_type = file_type($diff->{'from_mode'});
4387 if ($diff->{'status'} eq "A") { # created
4388 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4389 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4390 $mode_chng .= "]</span>";
4391 print "<td>";
4392 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4393 hash_base=>$hash, file_name=>$diff->{'file'}),
4394 -class => "list"}, esc_path($diff->{'file'}));
4395 print "</td>\n";
4396 print "<td>$mode_chng</td>\n";
4397 print "<td class=\"link\">";
4398 if ($action eq 'commitdiff') {
4399 # link to patch
4400 $patchno++;
4401 print $cgi->a({-href => "#patch$patchno"}, "patch");
4402 print " | ";
4404 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4405 hash_base=>$hash, file_name=>$diff->{'file'})},
4406 "blob");
4407 print "</td>\n";
4409 } elsif ($diff->{'status'} eq "D") { # deleted
4410 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4411 print "<td>";
4412 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4413 hash_base=>$parent, file_name=>$diff->{'file'}),
4414 -class => "list"}, esc_path($diff->{'file'}));
4415 print "</td>\n";
4416 print "<td>$mode_chng</td>\n";
4417 print "<td class=\"link\">";
4418 if ($action eq 'commitdiff') {
4419 # link to patch
4420 $patchno++;
4421 print $cgi->a({-href => "#patch$patchno"}, "patch");
4422 print " | ";
4424 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4425 hash_base=>$parent, file_name=>$diff->{'file'})},
4426 "blob") . " | ";
4427 if ($have_blame) {
4428 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4429 file_name=>$diff->{'file'})},
4430 "blame") . " | ";
4432 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4433 file_name=>$diff->{'file'})},
4434 "history");
4435 print "</td>\n";
4437 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4438 my $mode_chnge = "";
4439 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4440 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4441 if ($from_file_type ne $to_file_type) {
4442 $mode_chnge .= " from $from_file_type to $to_file_type";
4444 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4445 if ($from_mode_str && $to_mode_str) {
4446 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4447 } elsif ($to_mode_str) {
4448 $mode_chnge .= " mode: $to_mode_str";
4451 $mode_chnge .= "]</span>\n";
4453 print "<td>";
4454 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4455 hash_base=>$hash, file_name=>$diff->{'file'}),
4456 -class => "list"}, esc_path($diff->{'file'}));
4457 print "</td>\n";
4458 print "<td>$mode_chnge</td>\n";
4459 print "<td class=\"link\">";
4460 if ($action eq 'commitdiff') {
4461 # link to patch
4462 $patchno++;
4463 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4464 " | ";
4465 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4466 # "commit" view and modified file (not onlu mode changed)
4467 print $cgi->a({-href => href(action=>"blobdiff",
4468 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4469 hash_base=>$hash, hash_parent_base=>$parent,
4470 file_name=>$diff->{'file'})},
4471 "diff") .
4472 " | ";
4474 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4475 hash_base=>$hash, file_name=>$diff->{'file'})},
4476 "blob") . " | ";
4477 if ($have_blame) {
4478 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4479 file_name=>$diff->{'file'})},
4480 "blame") . " | ";
4482 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4483 file_name=>$diff->{'file'})},
4484 "history");
4485 print "</td>\n";
4487 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4488 my %status_name = ('R' => 'moved', 'C' => 'copied');
4489 my $nstatus = $status_name{$diff->{'status'}};
4490 my $mode_chng = "";
4491 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4492 # mode also for directories, so we cannot use $to_mode_str
4493 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4495 print "<td>" .
4496 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4497 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4498 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4499 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4500 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4501 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4502 -class => "list"}, esc_path($diff->{'from_file'})) .
4503 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4504 "<td class=\"link\">";
4505 if ($action eq 'commitdiff') {
4506 # link to patch
4507 $patchno++;
4508 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4509 " | ";
4510 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4511 # "commit" view and modified file (not only pure rename or copy)
4512 print $cgi->a({-href => href(action=>"blobdiff",
4513 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4514 hash_base=>$hash, hash_parent_base=>$parent,
4515 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4516 "diff") .
4517 " | ";
4519 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4520 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4521 "blob") . " | ";
4522 if ($have_blame) {
4523 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4524 file_name=>$diff->{'to_file'})},
4525 "blame") . " | ";
4527 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4528 file_name=>$diff->{'to_file'})},
4529 "history");
4530 print "</td>\n";
4532 } # we should not encounter Unmerged (U) or Unknown (X) status
4533 print "</tr>\n";
4535 print "</tbody>" if $has_header;
4536 print "</table>\n";
4539 sub git_patchset_body {
4540 my ($fd, $difftree, $hash, @hash_parents) = @_;
4541 my ($hash_parent) = $hash_parents[0];
4543 my $is_combined = (@hash_parents > 1);
4544 my $patch_idx = 0;
4545 my $patch_number = 0;
4546 my $patch_line;
4547 my $diffinfo;
4548 my $to_name;
4549 my (%from, %to);
4551 print "<div class=\"patchset\">\n";
4553 # skip to first patch
4554 while ($patch_line = <$fd>) {
4555 chomp $patch_line;
4557 last if ($patch_line =~ m/^diff /);
4560 PATCH:
4561 while ($patch_line) {
4563 # parse "git diff" header line
4564 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4565 # $1 is from_name, which we do not use
4566 $to_name = unquote($2);
4567 $to_name =~ s!^b/!!;
4568 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4569 # $1 is 'cc' or 'combined', which we do not use
4570 $to_name = unquote($2);
4571 } else {
4572 $to_name = undef;
4575 # check if current patch belong to current raw line
4576 # and parse raw git-diff line if needed
4577 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4578 # this is continuation of a split patch
4579 print "<div class=\"patch cont\">\n";
4580 } else {
4581 # advance raw git-diff output if needed
4582 $patch_idx++ if defined $diffinfo;
4584 # read and prepare patch information
4585 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4587 # compact combined diff output can have some patches skipped
4588 # find which patch (using pathname of result) we are at now;
4589 if ($is_combined) {
4590 while ($to_name ne $diffinfo->{'to_file'}) {
4591 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4592 format_diff_cc_simplified($diffinfo, @hash_parents) .
4593 "</div>\n"; # class="patch"
4595 $patch_idx++;
4596 $patch_number++;
4598 last if $patch_idx > $#$difftree;
4599 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4603 # modifies %from, %to hashes
4604 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4606 # this is first patch for raw difftree line with $patch_idx index
4607 # we index @$difftree array from 0, but number patches from 1
4608 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4611 # git diff header
4612 #assert($patch_line =~ m/^diff /) if DEBUG;
4613 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4614 $patch_number++;
4615 # print "git diff" header
4616 print format_git_diff_header_line($patch_line, $diffinfo,
4617 \%from, \%to);
4619 # print extended diff header
4620 print "<div class=\"diff extended_header\">\n";
4621 EXTENDED_HEADER:
4622 while ($patch_line = <$fd>) {
4623 chomp $patch_line;
4625 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4627 print format_extended_diff_header_line($patch_line, $diffinfo,
4628 \%from, \%to);
4630 print "</div>\n"; # class="diff extended_header"
4632 # from-file/to-file diff header
4633 if (! $patch_line) {
4634 print "</div>\n"; # class="patch"
4635 last PATCH;
4637 next PATCH if ($patch_line =~ m/^diff /);
4638 #assert($patch_line =~ m/^---/) if DEBUG;
4640 my $last_patch_line = $patch_line;
4641 $patch_line = <$fd>;
4642 chomp $patch_line;
4643 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4645 print format_diff_from_to_header($last_patch_line, $patch_line,
4646 $diffinfo, \%from, \%to,
4647 @hash_parents);
4649 # the patch itself
4650 LINE:
4651 while ($patch_line = <$fd>) {
4652 chomp $patch_line;
4654 next PATCH if ($patch_line =~ m/^diff /);
4656 print format_diff_line($patch_line, \%from, \%to);
4659 } continue {
4660 print "</div>\n"; # class="patch"
4663 # for compact combined (--cc) format, with chunk and patch simplification
4664 # the patchset might be empty, but there might be unprocessed raw lines
4665 for (++$patch_idx if $patch_number > 0;
4666 $patch_idx < @$difftree;
4667 ++$patch_idx) {
4668 # read and prepare patch information
4669 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4671 # generate anchor for "patch" links in difftree / whatchanged part
4672 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4673 format_diff_cc_simplified($diffinfo, @hash_parents) .
4674 "</div>\n"; # class="patch"
4676 $patch_number++;
4679 if ($patch_number == 0) {
4680 if (@hash_parents > 1) {
4681 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4682 } else {
4683 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4687 print "</div>\n"; # class="patchset"
4690 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4692 # fills project list info (age, description, owner, forks) for each
4693 # project in the list, removing invalid projects from returned list
4694 # NOTE: modifies $projlist, but does not remove entries from it
4695 sub fill_project_list_info {
4696 my ($projlist, $check_forks) = @_;
4697 my @projects;
4699 my $show_ctags = gitweb_check_feature('ctags');
4700 PROJECT:
4701 foreach my $pr (@$projlist) {
4702 my (@activity) = git_get_last_activity($pr->{'path'});
4703 unless (@activity) {
4704 next PROJECT;
4706 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4707 if (!defined $pr->{'descr'}) {
4708 my $descr = git_get_project_description($pr->{'path'}) || "";
4709 $descr = to_utf8($descr);
4710 $pr->{'descr_long'} = $descr;
4711 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4713 if (!defined $pr->{'owner'}) {
4714 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4716 if ($check_forks) {
4717 my $pname = $pr->{'path'};
4718 if (($pname =~ s/\.git$//) &&
4719 ($pname !~ /\/$/) &&
4720 (-d "$projectroot/$pname")) {
4721 $pr->{'forks'} = "-d $projectroot/$pname";
4722 } else {
4723 $pr->{'forks'} = 0;
4726 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4727 push @projects, $pr;
4730 return @projects;
4733 # print 'sort by' <th> element, generating 'sort by $name' replay link
4734 # if that order is not selected
4735 sub print_sort_th {
4736 print format_sort_th(@_);
4739 sub format_sort_th {
4740 my ($name, $order, $header) = @_;
4741 my $sort_th = "";
4742 $header ||= ucfirst($name);
4744 if ($order eq $name) {
4745 $sort_th .= "<th>$header</th>\n";
4746 } else {
4747 $sort_th .= "<th>" .
4748 $cgi->a({-href => href(-replay=>1, order=>$name),
4749 -class => "header"}, $header) .
4750 "</th>\n";
4753 return $sort_th;
4756 sub git_project_list_body {
4757 # actually uses global variable $project
4758 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4760 my $check_forks = gitweb_check_feature('forks');
4761 my @projects = fill_project_list_info($projlist, $check_forks);
4763 $order ||= $default_projects_order;
4764 $from = 0 unless defined $from;
4765 $to = $#projects if (!defined $to || $#projects < $to);
4767 my %order_info = (
4768 project => { key => 'path', type => 'str' },
4769 descr => { key => 'descr_long', type => 'str' },
4770 owner => { key => 'owner', type => 'str' },
4771 age => { key => 'age', type => 'num' }
4773 my $oi = $order_info{$order};
4774 if ($oi->{'type'} eq 'str') {
4775 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4776 } else {
4777 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4780 my $show_ctags = gitweb_check_feature('ctags');
4781 if ($show_ctags) {
4782 my %ctags;
4783 foreach my $p (@projects) {
4784 foreach my $ct (keys %{$p->{'ctags'}}) {
4785 $ctags{$ct} += $p->{'ctags'}->{$ct};
4788 my $cloud = git_populate_project_tagcloud(\%ctags);
4789 print git_show_project_tagcloud($cloud, 64);
4792 print "<table class=\"project_list\">\n";
4793 unless ($no_header) {
4794 print "<tr>\n";
4795 if ($check_forks) {
4796 print "<th></th>\n";
4798 print_sort_th('project', $order, 'Project');
4799 print_sort_th('descr', $order, 'Description');
4800 print_sort_th('owner', $order, 'Owner');
4801 print_sort_th('age', $order, 'Last Change');
4802 print "<th></th>\n" . # for links
4803 "</tr>\n";
4805 my $alternate = 1;
4806 my $tagfilter = $cgi->param('by_tag');
4807 for (my $i = $from; $i <= $to; $i++) {
4808 my $pr = $projects[$i];
4810 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4811 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4812 and not $pr->{'descr_long'} =~ /$searchtext/;
4813 # Weed out forks or non-matching entries of search
4814 if ($check_forks) {
4815 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4816 $forkbase="^$forkbase" if $forkbase;
4817 next if not $searchtext and not $tagfilter and $show_ctags
4818 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4821 if ($alternate) {
4822 print "<tr class=\"dark\">\n";
4823 } else {
4824 print "<tr class=\"light\">\n";
4826 $alternate ^= 1;
4827 if ($check_forks) {
4828 print "<td>";
4829 if ($pr->{'forks'}) {
4830 print "<!-- $pr->{'forks'} -->\n";
4831 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4833 print "</td>\n";
4835 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4836 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4837 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4838 -class => "list", -title => $pr->{'descr_long'}},
4839 esc_html($pr->{'descr'})) . "</td>\n" .
4840 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4841 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4842 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4843 "<td class=\"link\">" .
4844 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4845 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4846 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4847 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4848 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4849 "</td>\n" .
4850 "</tr>\n";
4852 if (defined $extra) {
4853 print "<tr>\n";
4854 if ($check_forks) {
4855 print "<td></td>\n";
4857 print "<td colspan=\"5\">$extra</td>\n" .
4858 "</tr>\n";
4860 print "</table>\n";
4863 sub git_log_body {
4864 # uses global variable $project
4865 my ($commitlist, $from, $to, $refs, $extra) = @_;
4867 $from = 0 unless defined $from;
4868 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4870 for (my $i = 0; $i <= $to; $i++) {
4871 my %co = %{$commitlist->[$i]};
4872 next if !%co;
4873 my $commit = $co{'id'};
4874 my $ref = format_ref_marker($refs, $commit);
4875 my %ad = parse_date($co{'author_epoch'});
4876 git_print_header_div('commit',
4877 "<span class=\"age\">$co{'age_string'}</span>" .
4878 esc_html($co{'title'}) . $ref,
4879 $commit);
4880 print "<div class=\"title_text\">\n" .
4881 "<div class=\"log_link\">\n" .
4882 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4883 " | " .
4884 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4885 " | " .
4886 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4887 "<br/>\n" .
4888 "</div>\n";
4889 git_print_authorship(\%co, -tag => 'span');
4890 print "<br/>\n</div>\n";
4892 print "<div class=\"log_body\">\n";
4893 git_print_log($co{'comment'}, -final_empty_line=> 1);
4894 print "</div>\n";
4896 if ($extra) {
4897 print "<div class=\"page_nav\">\n";
4898 print "$extra\n";
4899 print "</div>\n";
4903 sub git_shortlog_body {
4904 # uses global variable $project
4905 my ($commitlist, $from, $to, $refs, $extra) = @_;
4907 $from = 0 unless defined $from;
4908 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4910 print "<table class=\"shortlog\">\n";
4911 my $alternate = 1;
4912 for (my $i = $from; $i <= $to; $i++) {
4913 my %co = %{$commitlist->[$i]};
4914 my $commit = $co{'id'};
4915 my $ref = format_ref_marker($refs, $commit);
4916 if ($alternate) {
4917 print "<tr class=\"dark\">\n";
4918 } else {
4919 print "<tr class=\"light\">\n";
4921 $alternate ^= 1;
4922 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4923 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4924 format_author_html('td', \%co, 10) . "<td>";
4925 print format_subject_html($co{'title'}, $co{'title_short'},
4926 href(action=>"commit", hash=>$commit), $ref);
4927 print "</td>\n" .
4928 "<td class=\"link\">" .
4929 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4930 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4931 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4932 my $snapshot_links = format_snapshot_links($commit);
4933 if (defined $snapshot_links) {
4934 print " | " . $snapshot_links;
4936 print "</td>\n" .
4937 "</tr>\n";
4939 if (defined $extra) {
4940 print "<tr>\n" .
4941 "<td colspan=\"4\">$extra</td>\n" .
4942 "</tr>\n";
4944 print "</table>\n";
4947 sub git_history_body {
4948 # Warning: assumes constant type (blob or tree) during history
4949 my ($commitlist, $from, $to, $refs, $extra,
4950 $file_name, $file_hash, $ftype) = @_;
4952 $from = 0 unless defined $from;
4953 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4955 print "<table class=\"history\">\n";
4956 my $alternate = 1;
4957 for (my $i = $from; $i <= $to; $i++) {
4958 my %co = %{$commitlist->[$i]};
4959 if (!%co) {
4960 next;
4962 my $commit = $co{'id'};
4964 my $ref = format_ref_marker($refs, $commit);
4966 if ($alternate) {
4967 print "<tr class=\"dark\">\n";
4968 } else {
4969 print "<tr class=\"light\">\n";
4971 $alternate ^= 1;
4972 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4973 # shortlog: format_author_html('td', \%co, 10)
4974 format_author_html('td', \%co, 15, 3) . "<td>";
4975 # originally git_history used chop_str($co{'title'}, 50)
4976 print format_subject_html($co{'title'}, $co{'title_short'},
4977 href(action=>"commit", hash=>$commit), $ref);
4978 print "</td>\n" .
4979 "<td class=\"link\">" .
4980 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4981 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4983 if ($ftype eq 'blob') {
4984 my $blob_current = $file_hash;
4985 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4986 if (defined $blob_current && defined $blob_parent &&
4987 $blob_current ne $blob_parent) {
4988 print " | " .
4989 $cgi->a({-href => href(action=>"blobdiff",
4990 hash=>$blob_current, hash_parent=>$blob_parent,
4991 hash_base=>$hash_base, hash_parent_base=>$commit,
4992 file_name=>$file_name)},
4993 "diff to current");
4996 print "</td>\n" .
4997 "</tr>\n";
4999 if (defined $extra) {
5000 print "<tr>\n" .
5001 "<td colspan=\"4\">$extra</td>\n" .
5002 "</tr>\n";
5004 print "</table>\n";
5007 sub git_tags_body {
5008 # uses global variable $project
5009 my ($taglist, $from, $to, $extra) = @_;
5010 $from = 0 unless defined $from;
5011 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5013 print "<table class=\"tags\">\n";
5014 my $alternate = 1;
5015 for (my $i = $from; $i <= $to; $i++) {
5016 my $entry = $taglist->[$i];
5017 my %tag = %$entry;
5018 my $comment = $tag{'subject'};
5019 my $comment_short;
5020 if (defined $comment) {
5021 $comment_short = chop_str($comment, 30, 5);
5023 if ($alternate) {
5024 print "<tr class=\"dark\">\n";
5025 } else {
5026 print "<tr class=\"light\">\n";
5028 $alternate ^= 1;
5029 if (defined $tag{'age'}) {
5030 print "<td><i>$tag{'age'}</i></td>\n";
5031 } else {
5032 print "<td></td>\n";
5034 print "<td>" .
5035 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5036 -class => "list name"}, esc_html($tag{'name'})) .
5037 "</td>\n" .
5038 "<td>";
5039 if (defined $comment) {
5040 print format_subject_html($comment, $comment_short,
5041 href(action=>"tag", hash=>$tag{'id'}));
5043 print "</td>\n" .
5044 "<td class=\"selflink\">";
5045 if ($tag{'type'} eq "tag") {
5046 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5047 } else {
5048 print "&nbsp;";
5050 print "</td>\n" .
5051 "<td class=\"link\">" . " | " .
5052 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5053 if ($tag{'reftype'} eq "commit") {
5054 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5055 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5056 } elsif ($tag{'reftype'} eq "blob") {
5057 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5059 print "</td>\n" .
5060 "</tr>";
5062 if (defined $extra) {
5063 print "<tr>\n" .
5064 "<td colspan=\"5\">$extra</td>\n" .
5065 "</tr>\n";
5067 print "</table>\n";
5070 sub git_heads_body {
5071 # uses global variable $project
5072 my ($headlist, $head, $from, $to, $extra) = @_;
5073 $from = 0 unless defined $from;
5074 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5076 print "<table class=\"heads\">\n";
5077 my $alternate = 1;
5078 for (my $i = $from; $i <= $to; $i++) {
5079 my $entry = $headlist->[$i];
5080 my %ref = %$entry;
5081 my $curr = $ref{'id'} eq $head;
5082 if ($alternate) {
5083 print "<tr class=\"dark\">\n";
5084 } else {
5085 print "<tr class=\"light\">\n";
5087 $alternate ^= 1;
5088 print "<td><i>$ref{'age'}</i></td>\n" .
5089 ($curr ? "<td class=\"current_head\">" : "<td>") .
5090 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5091 -class => "list name"},esc_html($ref{'name'})) .
5092 "</td>\n" .
5093 "<td class=\"link\">" .
5094 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5095 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5096 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
5097 "</td>\n" .
5098 "</tr>";
5100 if (defined $extra) {
5101 print "<tr>\n" .
5102 "<td colspan=\"3\">$extra</td>\n" .
5103 "</tr>\n";
5105 print "</table>\n";
5108 sub git_search_grep_body {
5109 my ($commitlist, $from, $to, $extra) = @_;
5110 $from = 0 unless defined $from;
5111 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5113 print "<table class=\"commit_search\">\n";
5114 my $alternate = 1;
5115 for (my $i = $from; $i <= $to; $i++) {
5116 my %co = %{$commitlist->[$i]};
5117 if (!%co) {
5118 next;
5120 my $commit = $co{'id'};
5121 if ($alternate) {
5122 print "<tr class=\"dark\">\n";
5123 } else {
5124 print "<tr class=\"light\">\n";
5126 $alternate ^= 1;
5127 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5128 format_author_html('td', \%co, 15, 5) .
5129 "<td>" .
5130 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5131 -class => "list subject"},
5132 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5133 my $comment = $co{'comment'};
5134 foreach my $line (@$comment) {
5135 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5136 my ($lead, $match, $trail) = ($1, $2, $3);
5137 $match = chop_str($match, 70, 5, 'center');
5138 my $contextlen = int((80 - length($match))/2);
5139 $contextlen = 30 if ($contextlen > 30);
5140 $lead = chop_str($lead, $contextlen, 10, 'left');
5141 $trail = chop_str($trail, $contextlen, 10, 'right');
5143 $lead = esc_html($lead);
5144 $match = esc_html($match);
5145 $trail = esc_html($trail);
5147 print "$lead<span class=\"match\">$match</span>$trail<br />";
5150 print "</td>\n" .
5151 "<td class=\"link\">" .
5152 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5153 " | " .
5154 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5155 " | " .
5156 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5157 print "</td>\n" .
5158 "</tr>\n";
5160 if (defined $extra) {
5161 print "<tr>\n" .
5162 "<td colspan=\"3\">$extra</td>\n" .
5163 "</tr>\n";
5165 print "</table>\n";
5168 ## ======================================================================
5169 ## ======================================================================
5170 ## actions
5172 sub git_project_list {
5173 my $order = $input_params{'order'};
5174 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5175 die_error(400, "Unknown order parameter");
5178 my @list = git_get_projects_list();
5179 if (!@list) {
5180 die_error(404, "No projects found");
5183 git_header_html();
5184 if (defined $home_text && -f $home_text) {
5185 print "<div class=\"index_include\">\n";
5186 insert_file($home_text);
5187 print "</div>\n";
5189 print $cgi->startform(-method => "get") .
5190 "<p class=\"projsearch\">Search:\n" .
5191 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5192 "</p>" .
5193 $cgi->end_form() . "\n";
5194 git_project_list_body(\@list, $order);
5195 git_footer_html();
5198 sub git_forks {
5199 my $order = $input_params{'order'};
5200 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5201 die_error(400, "Unknown order parameter");
5204 my @list = git_get_projects_list($project);
5205 if (!@list) {
5206 die_error(404, "No forks found");
5209 git_header_html();
5210 git_print_page_nav('','');
5211 git_print_header_div('summary', "$project forks");
5212 git_project_list_body(\@list, $order);
5213 git_footer_html();
5216 sub git_project_index {
5217 my @projects = git_get_projects_list($project);
5219 print $cgi->header(
5220 -type => 'text/plain',
5221 -charset => 'utf-8',
5222 -content_disposition => 'inline; filename="index.aux"');
5224 foreach my $pr (@projects) {
5225 if (!exists $pr->{'owner'}) {
5226 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5229 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5230 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5231 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5232 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5233 $path =~ s/ /\+/g;
5234 $owner =~ s/ /\+/g;
5236 print "$path $owner\n";
5240 sub git_summary {
5241 my $descr = git_get_project_description($project) || "none";
5242 my %co = parse_commit("HEAD");
5243 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5244 my $head = $co{'id'};
5246 my $owner = git_get_project_owner($project);
5248 my $refs = git_get_references();
5249 # These get_*_list functions return one more to allow us to see if
5250 # there are more ...
5251 my @taglist = git_get_tags_list(16);
5252 my @headlist = git_get_heads_list(16);
5253 my @forklist;
5254 my $check_forks = gitweb_check_feature('forks');
5256 if ($check_forks) {
5257 @forklist = git_get_projects_list($project);
5260 git_header_html();
5261 git_print_page_nav('summary','', $head);
5263 print "<div class=\"title\">&nbsp;</div>\n";
5264 print "<table class=\"projects_list\">\n" .
5265 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5266 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5267 if (defined $cd{'rfc2822'}) {
5268 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5271 # use per project git URL list in $projectroot/$project/cloneurl
5272 # or make project git URL from git base URL and project name
5273 my $url_tag = "URL";
5274 my @url_list = git_get_project_url_list($project);
5275 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5276 foreach my $git_url (@url_list) {
5277 next unless $git_url;
5278 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5279 $url_tag = "";
5282 # Tag cloud
5283 my $show_ctags = gitweb_check_feature('ctags');
5284 if ($show_ctags) {
5285 my $ctags = git_get_project_ctags($project);
5286 my $cloud = git_populate_project_tagcloud($ctags);
5287 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5288 print "</td>\n<td>" unless %$ctags;
5289 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5290 print "</td>\n<td>" if %$ctags;
5291 print git_show_project_tagcloud($cloud, 48);
5292 print "</td></tr>";
5295 print "</table>\n";
5297 # If XSS prevention is on, we don't include README.html.
5298 # TODO: Allow a readme in some safe format.
5299 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5300 print "<div class=\"title\">readme</div>\n" .
5301 "<div class=\"readme\">\n";
5302 insert_file("$projectroot/$project/README.html");
5303 print "\n</div>\n"; # class="readme"
5306 # we need to request one more than 16 (0..15) to check if
5307 # those 16 are all
5308 my @commitlist = $head ? parse_commits($head, 17) : ();
5309 if (@commitlist) {
5310 git_print_header_div('shortlog');
5311 git_shortlog_body(\@commitlist, 0, 15, $refs,
5312 $#commitlist <= 15 ? undef :
5313 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5316 if (@taglist) {
5317 git_print_header_div('tags');
5318 git_tags_body(\@taglist, 0, 15,
5319 $#taglist <= 15 ? undef :
5320 $cgi->a({-href => href(action=>"tags")}, "..."));
5323 if (@headlist) {
5324 git_print_header_div('heads');
5325 git_heads_body(\@headlist, $head, 0, 15,
5326 $#headlist <= 15 ? undef :
5327 $cgi->a({-href => href(action=>"heads")}, "..."));
5330 if (@forklist) {
5331 git_print_header_div('forks');
5332 git_project_list_body(\@forklist, 'age', 0, 15,
5333 $#forklist <= 15 ? undef :
5334 $cgi->a({-href => href(action=>"forks")}, "..."),
5335 'no_header');
5338 git_footer_html();
5341 sub git_tag {
5342 my %tag = parse_tag($hash);
5344 if (! %tag) {
5345 die_error(404, "Unknown tag object");
5348 my $head = git_get_head_hash($project);
5349 git_header_html();
5350 git_print_page_nav('','', $head,undef,$head);
5351 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5352 print "<div class=\"title_text\">\n" .
5353 "<table class=\"object_header\">\n" .
5354 "<tr>\n" .
5355 "<td>object</td>\n" .
5356 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5357 $tag{'object'}) . "</td>\n" .
5358 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5359 $tag{'type'}) . "</td>\n" .
5360 "</tr>\n";
5361 if (defined($tag{'author'})) {
5362 git_print_authorship_rows(\%tag, 'author');
5364 print "</table>\n\n" .
5365 "</div>\n";
5366 print "<div class=\"page_body\">";
5367 my $comment = $tag{'comment'};
5368 foreach my $line (@$comment) {
5369 chomp $line;
5370 print esc_html($line, -nbsp=>1) . "<br/>\n";
5372 print "</div>\n";
5373 git_footer_html();
5376 sub git_blame_common {
5377 my $format = shift || 'porcelain';
5378 if ($format eq 'porcelain' && $cgi->param('js') &&
5379 !$caching_enabled) {
5380 $format = 'incremental';
5381 $action = 'blame_incremental'; # for page title etc
5384 # permissions
5385 gitweb_check_feature('blame')
5386 or die_error(403, "Blame view not allowed");
5388 # error checking
5389 die_error(400, "No file name given") unless $file_name;
5390 $hash_base ||= git_get_head_hash($project);
5391 die_error(404, "Couldn't find base commit") unless $hash_base;
5392 my %co = parse_commit($hash_base)
5393 or die_error(404, "Commit not found");
5394 my $ftype = "blob";
5395 if (!defined $hash) {
5396 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5397 or die_error(404, "Error looking up file");
5398 } else {
5399 $ftype = git_get_type($hash);
5400 if ($ftype !~ "blob") {
5401 die_error(400, "Object is not a blob");
5405 my $fd;
5406 if ($format eq 'incremental') {
5407 # get file contents (as base)
5408 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5409 or die_error(500, "Open git-cat-file failed");
5410 } elsif ($format eq 'data') {
5411 # run git-blame --incremental
5412 open $fd, "-|", git_cmd(), "blame", "--incremental",
5413 $hash_base, "--", $file_name
5414 or die_error(500, "Open git-blame --incremental failed");
5415 } else {
5416 # run git-blame --porcelain
5417 open $fd, "-|", git_cmd(), "blame", '-p',
5418 $hash_base, '--', $file_name
5419 or die_error(500, "Open git-blame --porcelain failed");
5422 # incremental blame data returns early
5423 if ($format eq 'data') {
5424 print $cgi->header(
5425 -type=>"text/plain", -charset => "utf-8",
5426 -status=> "200 OK");
5427 local $| = 1; # output autoflush
5428 print while <$fd>;
5429 close $fd
5430 or print "ERROR $!\n";
5432 print 'END';
5433 if (!$caching_enabled &&
5434 defined $t0 && gitweb_check_feature('timed')) {
5435 print ' '.
5436 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5437 ' '.$number_of_git_cmds;
5439 print "\n";
5441 return;
5444 # page header
5445 git_header_html();
5446 my $formats_nav =
5447 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5448 "blob") .
5449 " | ";
5450 if ($format eq 'incremental') {
5451 $formats_nav .=
5452 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5453 "blame") . " (non-incremental)";
5454 } elsif (!$caching_enabled) {
5455 $formats_nav .=
5456 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5457 "blame") . " (incremental)";
5459 $formats_nav .=
5460 " | " .
5461 $cgi->a({-href => href(action=>"history", -replay=>1)},
5462 "history") .
5463 " | " .
5464 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5465 "HEAD");
5466 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5467 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5468 git_print_page_path($file_name, $ftype, $hash_base);
5470 # page body
5471 if ($format eq 'incremental') {
5472 print "<noscript>\n<div class=\"error\"><center><b>\n".
5473 "This page requires JavaScript to run.\n Use ".
5474 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5475 'this page').
5476 " instead.\n".
5477 "</b></center></div>\n</noscript>\n";
5479 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5482 print qq!<div class="page_body">\n!;
5483 print qq!<div id="progress_info">... / ...</div>\n!
5484 if ($format eq 'incremental');
5485 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5486 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5487 qq!<thead>\n!.
5488 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5489 qq!</thead>\n!.
5490 qq!<tbody>\n!;
5492 my @rev_color = qw(light dark);
5493 my $num_colors = scalar(@rev_color);
5494 my $current_color = 0;
5496 if ($format eq 'incremental') {
5497 my $color_class = $rev_color[$current_color];
5499 #contents of a file
5500 my $linenr = 0;
5501 LINE:
5502 while (my $line = <$fd>) {
5503 chomp $line;
5504 $linenr++;
5506 print qq!<tr id="l$linenr" class="$color_class">!.
5507 qq!<td class="sha1"><a href=""> </a></td>!.
5508 qq!<td class="linenr">!.
5509 qq!<a class="linenr" href="">$linenr</a></td>!;
5510 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5511 print qq!</tr>\n!;
5514 } else { # porcelain, i.e. ordinary blame
5515 my %metainfo = (); # saves information about commits
5517 # blame data
5518 LINE:
5519 while (my $line = <$fd>) {
5520 chomp $line;
5521 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5522 # no <lines in group> for subsequent lines in group of lines
5523 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5524 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5525 if (!exists $metainfo{$full_rev}) {
5526 $metainfo{$full_rev} = { 'nprevious' => 0 };
5528 my $meta = $metainfo{$full_rev};
5529 my $data;
5530 while ($data = <$fd>) {
5531 chomp $data;
5532 last if ($data =~ s/^\t//); # contents of line
5533 if ($data =~ /^(\S+)(?: (.*))?$/) {
5534 $meta->{$1} = $2 unless exists $meta->{$1};
5536 if ($data =~ /^previous /) {
5537 $meta->{'nprevious'}++;
5540 my $short_rev = substr($full_rev, 0, 8);
5541 my $author = $meta->{'author'};
5542 my %date =
5543 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5544 my $date = $date{'iso-tz'};
5545 if ($group_size) {
5546 $current_color = ($current_color + 1) % $num_colors;
5548 my $tr_class = $rev_color[$current_color];
5549 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5550 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5551 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5552 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5553 if ($group_size) {
5554 print "<td class=\"sha1\"";
5555 print " title=\"". esc_html($author) . ", $date\"";
5556 print " rowspan=\"$group_size\"" if ($group_size > 1);
5557 print ">";
5558 print $cgi->a({-href => href(action=>"commit",
5559 hash=>$full_rev,
5560 file_name=>$file_name)},
5561 esc_html($short_rev));
5562 if ($group_size >= 2) {
5563 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5564 if (@author_initials) {
5565 print "<br />" .
5566 esc_html(join('', @author_initials));
5567 # or join('.', ...)
5570 print "</td>\n";
5572 # 'previous' <sha1 of parent commit> <filename at commit>
5573 if (exists $meta->{'previous'} &&
5574 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5575 $meta->{'parent'} = $1;
5576 $meta->{'file_parent'} = unquote($2);
5578 my $linenr_commit =
5579 exists($meta->{'parent'}) ?
5580 $meta->{'parent'} : $full_rev;
5581 my $linenr_filename =
5582 exists($meta->{'file_parent'}) ?
5583 $meta->{'file_parent'} : unquote($meta->{'filename'});
5584 my $blamed = href(action => 'blame',
5585 file_name => $linenr_filename,
5586 hash_base => $linenr_commit);
5587 print "<td class=\"linenr\">";
5588 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5589 -class => "linenr" },
5590 esc_html($lineno));
5591 print "</td>";
5592 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5593 print "</tr>\n";
5594 } # end while
5598 # footer
5599 print "</tbody>\n".
5600 "</table>\n"; # class="blame"
5601 print "</div>\n"; # class="blame_body"
5602 close $fd
5603 or print "Reading blob failed\n";
5605 git_footer_html();
5608 sub git_blame {
5609 git_blame_common();
5612 sub git_blame_incremental {
5613 git_blame_common(!$caching_enabled ? 'incremental' : undef);
5616 sub git_blame_data {
5617 git_blame_common('data');
5620 sub git_tags {
5621 my $head = git_get_head_hash($project);
5622 git_header_html();
5623 git_print_page_nav('','', $head,undef,$head);
5624 git_print_header_div('summary', $project);
5626 my @tagslist = git_get_tags_list();
5627 if (@tagslist) {
5628 git_tags_body(\@tagslist);
5630 git_footer_html();
5633 sub git_heads {
5634 my $head = git_get_head_hash($project);
5635 git_header_html();
5636 git_print_page_nav('','', $head,undef,$head);
5637 git_print_header_div('summary', $project);
5639 my @headslist = git_get_heads_list();
5640 if (@headslist) {
5641 git_heads_body(\@headslist, $head);
5643 git_footer_html();
5646 sub git_blob_plain {
5647 my $type = shift;
5648 my $expires;
5650 if (!defined $hash) {
5651 if (defined $file_name) {
5652 my $base = $hash_base || git_get_head_hash($project);
5653 $hash = git_get_hash_by_path($base, $file_name, "blob")
5654 or die_error(404, "Cannot find file");
5655 } else {
5656 die_error(400, "No file name defined");
5658 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5659 # blobs defined by non-textual hash id's can be cached
5660 $expires = "+1d";
5663 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5664 or die_error(500, "Open git-cat-file blob '$hash' failed");
5666 # content-type (can include charset)
5667 $type = blob_contenttype($fd, $file_name, $type);
5669 # "save as" filename, even when no $file_name is given
5670 my $save_as = "$hash";
5671 if (defined $file_name) {
5672 $save_as = $file_name;
5673 } elsif ($type =~ m/^text\//) {
5674 $save_as .= '.txt';
5677 # With XSS prevention on, blobs of all types except a few known safe
5678 # ones are served with "Content-Disposition: attachment" to make sure
5679 # they don't run in our security domain. For certain image types,
5680 # blob view writes an <img> tag referring to blob_plain view, and we
5681 # want to be sure not to break that by serving the image as an
5682 # attachment (though Firefox 3 doesn't seem to care).
5683 my $sandbox = $prevent_xss &&
5684 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5686 print $cgi->header(
5687 -type => $type,
5688 -expires => $expires,
5689 -content_disposition =>
5690 ($sandbox ? 'attachment' : 'inline')
5691 . '; filename="' . $save_as . '"');
5692 local $/ = undef;
5693 binmode STDOUT, ':raw';
5694 print <$fd>;
5695 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5696 close $fd;
5699 sub git_blob {
5700 my $expires;
5702 if (!defined $hash) {
5703 if (defined $file_name) {
5704 my $base = $hash_base || git_get_head_hash($project);
5705 $hash = git_get_hash_by_path($base, $file_name, "blob")
5706 or die_error(404, "Cannot find file");
5707 } else {
5708 die_error(400, "No file name defined");
5710 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5711 # blobs defined by non-textual hash id's can be cached
5712 $expires = "+1d";
5715 my $have_blame = gitweb_check_feature('blame');
5716 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5717 or die_error(500, "Couldn't cat $file_name, $hash");
5718 my $mimetype = blob_mimetype($fd, $file_name);
5719 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5720 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5721 close $fd;
5722 return git_blob_plain($mimetype);
5724 # we can have blame only for text/* mimetype
5725 $have_blame &&= ($mimetype =~ m!^text/!);
5727 my $highlight = gitweb_check_feature('highlight');
5728 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5729 $fd = run_highlighter($fd, $highlight, $syntax)
5730 if $syntax;
5732 git_header_html(undef, $expires);
5733 my $formats_nav = '';
5734 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5735 if (defined $file_name) {
5736 if ($have_blame) {
5737 $formats_nav .=
5738 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5739 "blame") .
5740 " | ";
5742 $formats_nav .=
5743 $cgi->a({-href => href(action=>"history", -replay=>1)},
5744 "history") .
5745 " | " .
5746 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5747 "raw") .
5748 " | " .
5749 $cgi->a({-href => href(action=>"blob",
5750 hash_base=>"HEAD", file_name=>$file_name)},
5751 "HEAD");
5752 } else {
5753 $formats_nav .=
5754 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5755 "raw");
5757 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5758 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5759 } else {
5760 print "<div class=\"page_nav\">\n" .
5761 "<br/><br/></div>\n" .
5762 "<div class=\"title\">$hash</div>\n";
5764 git_print_page_path($file_name, "blob", $hash_base);
5765 print "<div class=\"page_body\">\n";
5766 if ($mimetype =~ m!^image/!) {
5767 print qq!<img type="$mimetype"!;
5768 if ($file_name) {
5769 print qq! alt="$file_name" title="$file_name"!;
5771 print qq! src="! .
5772 href(action=>"blob_plain", hash=>$hash,
5773 hash_base=>$hash_base, file_name=>$file_name) .
5774 qq!" />\n!;
5775 } else {
5776 my $nr;
5777 while (my $line = <$fd>) {
5778 chomp $line;
5779 $nr++;
5780 $line = untabify($line);
5781 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5782 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5785 close $fd
5786 or print "Reading blob failed.\n";
5787 print "</div>";
5788 git_footer_html();
5791 sub git_tree {
5792 if (!defined $hash_base) {
5793 $hash_base = "HEAD";
5795 if (!defined $hash) {
5796 if (defined $file_name) {
5797 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5798 } else {
5799 $hash = $hash_base;
5802 die_error(404, "No such tree") unless defined($hash);
5804 my $show_sizes = gitweb_check_feature('show-sizes');
5805 my $have_blame = gitweb_check_feature('blame');
5807 my @entries = ();
5809 local $/ = "\0";
5810 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5811 ($show_sizes ? '-l' : ()), @extra_options, $hash
5812 or die_error(500, "Open git-ls-tree failed");
5813 @entries = map { chomp; $_ } <$fd>;
5814 close $fd
5815 or die_error(404, "Reading tree failed");
5818 my $refs = git_get_references();
5819 my $ref = format_ref_marker($refs, $hash_base);
5820 git_header_html();
5821 my $basedir = '';
5822 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5823 my @views_nav = ();
5824 if (defined $file_name) {
5825 push @views_nav,
5826 $cgi->a({-href => href(action=>"history", -replay=>1)},
5827 "history"),
5828 $cgi->a({-href => href(action=>"tree",
5829 hash_base=>"HEAD", file_name=>$file_name)},
5830 "HEAD"),
5832 my $snapshot_links = format_snapshot_links($hash);
5833 if (defined $snapshot_links) {
5834 # FIXME: Should be available when we have no hash base as well.
5835 push @views_nav, $snapshot_links;
5837 git_print_page_nav('tree','', $hash_base, undef, undef,
5838 join(' | ', @views_nav));
5839 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5840 } else {
5841 undef $hash_base;
5842 print "<div class=\"page_nav\">\n";
5843 print "<br/><br/></div>\n";
5844 print "<div class=\"title\">$hash</div>\n";
5846 if (defined $file_name) {
5847 $basedir = $file_name;
5848 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5849 $basedir .= '/';
5851 git_print_page_path($file_name, 'tree', $hash_base);
5853 print "<div class=\"page_body\">\n";
5854 print "<table class=\"tree\">\n";
5855 my $alternate = 1;
5856 # '..' (top directory) link if possible
5857 if (defined $hash_base &&
5858 defined $file_name && $file_name =~ m![^/]+$!) {
5859 if ($alternate) {
5860 print "<tr class=\"dark\">\n";
5861 } else {
5862 print "<tr class=\"light\">\n";
5864 $alternate ^= 1;
5866 my $up = $file_name;
5867 $up =~ s!/?[^/]+$!!;
5868 undef $up unless $up;
5869 # based on git_print_tree_entry
5870 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5871 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5872 print '<td class="list">';
5873 print $cgi->a({-href => href(action=>"tree",
5874 hash_base=>$hash_base,
5875 file_name=>$up)},
5876 "..");
5877 print "</td>\n";
5878 print "<td class=\"link\"></td>\n";
5880 print "</tr>\n";
5882 foreach my $line (@entries) {
5883 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5885 if ($alternate) {
5886 print "<tr class=\"dark\">\n";
5887 } else {
5888 print "<tr class=\"light\">\n";
5890 $alternate ^= 1;
5892 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5894 print "</tr>\n";
5896 print "</table>\n" .
5897 "</div>";
5898 git_footer_html();
5901 sub snapshot_name {
5902 my ($project, $hash) = @_;
5904 # path/to/project.git -> project
5905 # path/to/project/.git -> project
5906 my $name = to_utf8($project);
5907 $name =~ s,([^/])/*\.git$,$1,;
5908 $name = basename($name);
5909 # sanitize name
5910 $name =~ s/[[:cntrl:]]/?/g;
5912 my $ver = $hash;
5913 if ($hash =~ /^[0-9a-fA-F]+$/) {
5914 # shorten SHA-1 hash
5915 my $full_hash = git_get_full_hash($project, $hash);
5916 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5917 $ver = git_get_short_hash($project, $hash);
5919 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5920 # tags don't need shortened SHA-1 hash
5921 $ver = $1;
5922 } else {
5923 # branches and other need shortened SHA-1 hash
5924 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5925 $ver = $1;
5927 $ver .= '-' . git_get_short_hash($project, $hash);
5929 # in case of hierarchical branch names
5930 $ver =~ s!/!.!g;
5932 # name = project-version_string
5933 $name = "$name-$ver";
5935 return wantarray ? ($name, $name) : $name;
5938 sub git_snapshot {
5939 my $format = $input_params{'snapshot_format'};
5940 if (!@snapshot_fmts) {
5941 die_error(403, "Snapshots not allowed");
5943 # default to first supported snapshot format
5944 $format ||= $snapshot_fmts[0];
5945 if ($format !~ m/^[a-z0-9]+$/) {
5946 die_error(400, "Invalid snapshot format parameter");
5947 } elsif (!exists($known_snapshot_formats{$format})) {
5948 die_error(400, "Unknown snapshot format");
5949 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5950 die_error(403, "Snapshot format not allowed");
5951 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5952 die_error(403, "Unsupported snapshot format");
5955 my $type = git_get_type("$hash^{}");
5956 if (!$type) {
5957 die_error(404, 'Object does not exist');
5958 } elsif ($type eq 'blob') {
5959 die_error(400, 'Object is not a tree-ish');
5962 my ($name, $prefix) = snapshot_name($project, $hash);
5963 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
5964 my $cmd = quote_command(
5965 git_cmd(), 'archive',
5966 "--format=$known_snapshot_formats{$format}{'format'}",
5967 "--prefix=$prefix/", $hash);
5968 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5969 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5972 $filename =~ s/(["\\])/\\$1/g;
5973 print $cgi->header(
5974 -type => $known_snapshot_formats{$format}{'type'},
5975 -content_disposition => 'inline; filename="' . $filename . '"',
5976 -status => '200 OK');
5978 open my $fd, "-|", $cmd
5979 or die_error(500, "Execute git-archive failed");
5980 binmode STDOUT, ':raw';
5981 print <$fd>;
5982 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5983 close $fd;
5986 sub git_log_generic {
5987 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
5989 my $head = git_get_head_hash($project);
5990 if (!defined $base) {
5991 $base = $head;
5993 if (!defined $page) {
5994 $page = 0;
5996 my $refs = git_get_references();
5998 my $commit_hash = $base;
5999 if (defined $parent) {
6000 $commit_hash = "$parent..$base";
6002 my @commitlist =
6003 parse_commits($commit_hash, 101, (100 * $page),
6004 defined $file_name ? ($file_name, "--full-history") : ());
6006 my $ftype;
6007 if (!defined $file_hash && defined $file_name) {
6008 # some commits could have deleted file in question,
6009 # and not have it in tree, but one of them has to have it
6010 for (my $i = 0; $i < @commitlist; $i++) {
6011 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6012 last if defined $file_hash;
6015 if (defined $file_hash) {
6016 $ftype = git_get_type($file_hash);
6018 if (defined $file_name && !defined $ftype) {
6019 die_error(500, "Unknown type of object");
6021 my %co;
6022 if (defined $file_name) {
6023 %co = parse_commit($base)
6024 or die_error(404, "Unknown commit object");
6028 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6029 my $next_link = '';
6030 if ($#commitlist >= 100) {
6031 $next_link =
6032 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6033 -accesskey => "n", -title => "Alt-n"}, "next");
6035 my $patch_max = gitweb_get_feature('patches');
6036 if ($patch_max && !defined $file_name) {
6037 if ($patch_max < 0 || @commitlist <= $patch_max) {
6038 $paging_nav .= " &sdot; " .
6039 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6040 "patches");
6044 git_header_html();
6045 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6046 if (defined $file_name) {
6047 git_print_header_div('commit', esc_html($co{'title'}), $base);
6048 } else {
6049 git_print_header_div('summary', $project)
6051 git_print_page_path($file_name, $ftype, $hash_base)
6052 if (defined $file_name);
6054 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6055 $file_name, $file_hash, $ftype);
6057 git_footer_html();
6060 sub git_log {
6061 git_log_generic('log', \&git_log_body,
6062 $hash, $hash_parent);
6065 sub git_commit {
6066 $hash ||= $hash_base || "HEAD";
6067 my %co = parse_commit($hash)
6068 or die_error(404, "Unknown commit object");
6070 my $parent = $co{'parent'};
6071 my $parents = $co{'parents'}; # listref
6073 # we need to prepare $formats_nav before any parameter munging
6074 my $formats_nav;
6075 if (!defined $parent) {
6076 # --root commitdiff
6077 $formats_nav .= '(initial)';
6078 } elsif (@$parents == 1) {
6079 # single parent commit
6080 $formats_nav .=
6081 '(parent: ' .
6082 $cgi->a({-href => href(action=>"commit",
6083 hash=>$parent)},
6084 esc_html(substr($parent, 0, 7))) .
6085 ')';
6086 } else {
6087 # merge commit
6088 $formats_nav .=
6089 '(merge: ' .
6090 join(' ', map {
6091 $cgi->a({-href => href(action=>"commit",
6092 hash=>$_)},
6093 esc_html(substr($_, 0, 7)));
6094 } @$parents ) .
6095 ')';
6097 if (gitweb_check_feature('patches') && @$parents <= 1) {
6098 $formats_nav .= " | " .
6099 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6100 "patch");
6103 if (!defined $parent) {
6104 $parent = "--root";
6106 my @difftree;
6107 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6108 @diff_opts,
6109 (@$parents <= 1 ? $parent : '-c'),
6110 $hash, "--"
6111 or die_error(500, "Open git-diff-tree failed");
6112 @difftree = map { chomp; $_ } <$fd>;
6113 close $fd or die_error(404, "Reading git-diff-tree failed");
6115 # non-textual hash id's can be cached
6116 my $expires;
6117 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6118 $expires = "+1d";
6120 my $refs = git_get_references();
6121 my $ref = format_ref_marker($refs, $co{'id'});
6123 git_header_html(undef, $expires);
6124 git_print_page_nav('commit', '',
6125 $hash, $co{'tree'}, $hash,
6126 $formats_nav);
6128 if (defined $co{'parent'}) {
6129 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6130 } else {
6131 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6133 print "<div class=\"title_text\">\n" .
6134 "<table class=\"object_header\">\n";
6135 git_print_authorship_rows(\%co);
6136 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6137 print "<tr>" .
6138 "<td>tree</td>" .
6139 "<td class=\"sha1\">" .
6140 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6141 class => "list"}, $co{'tree'}) .
6142 "</td>" .
6143 "<td class=\"link\">" .
6144 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6145 "tree");
6146 my $snapshot_links = format_snapshot_links($hash);
6147 if (defined $snapshot_links) {
6148 print " | " . $snapshot_links;
6150 print "</td>" .
6151 "</tr>\n";
6153 foreach my $par (@$parents) {
6154 print "<tr>" .
6155 "<td>parent</td>" .
6156 "<td class=\"sha1\">" .
6157 $cgi->a({-href => href(action=>"commit", hash=>$par),
6158 class => "list"}, $par) .
6159 "</td>" .
6160 "<td class=\"link\">" .
6161 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6162 " | " .
6163 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6164 "</td>" .
6165 "</tr>\n";
6167 print "</table>".
6168 "</div>\n";
6170 print "<div class=\"page_body\">\n";
6171 git_print_log($co{'comment'});
6172 print "</div>\n";
6174 git_difftree_body(\@difftree, $hash, @$parents);
6176 git_footer_html();
6179 sub git_object {
6180 # object is defined by:
6181 # - hash or hash_base alone
6182 # - hash_base and file_name
6183 my $type;
6185 # - hash or hash_base alone
6186 if ($hash || ($hash_base && !defined $file_name)) {
6187 my $object_id = $hash || $hash_base;
6189 open my $fd, "-|", quote_command(
6190 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6191 or die_error(404, "Object does not exist");
6192 $type = <$fd>;
6193 chomp $type;
6194 close $fd
6195 or die_error(404, "Object does not exist");
6197 # - hash_base and file_name
6198 } elsif ($hash_base && defined $file_name) {
6199 $file_name =~ s,/+$,,;
6201 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6202 or die_error(404, "Base object does not exist");
6204 # here errors should not hapen
6205 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6206 or die_error(500, "Open git-ls-tree failed");
6207 my $line = <$fd>;
6208 close $fd;
6210 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6211 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6212 die_error(404, "File or directory for given base does not exist");
6214 $type = $2;
6215 $hash = $3;
6216 } else {
6217 die_error(400, "Not enough information to find object");
6220 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6221 hash=>$hash, hash_base=>$hash_base,
6222 file_name=>$file_name),
6223 -status => '302 Found');
6226 sub git_blobdiff {
6227 my $format = shift || 'html';
6229 my $fd;
6230 my @difftree;
6231 my %diffinfo;
6232 my $expires;
6234 # preparing $fd and %diffinfo for git_patchset_body
6235 # new style URI
6236 if (defined $hash_base && defined $hash_parent_base) {
6237 if (defined $file_name) {
6238 # read raw output
6239 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6240 $hash_parent_base, $hash_base,
6241 "--", (defined $file_parent ? $file_parent : ()), $file_name
6242 or die_error(500, "Open git-diff-tree failed");
6243 @difftree = map { chomp; $_ } <$fd>;
6244 close $fd
6245 or die_error(404, "Reading git-diff-tree failed");
6246 @difftree
6247 or die_error(404, "Blob diff not found");
6249 } elsif (defined $hash &&
6250 $hash =~ /[0-9a-fA-F]{40}/) {
6251 # try to find filename from $hash
6253 # read filtered raw output
6254 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6255 $hash_parent_base, $hash_base, "--"
6256 or die_error(500, "Open git-diff-tree failed");
6257 @difftree =
6258 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6259 # $hash == to_id
6260 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6261 map { chomp; $_ } <$fd>;
6262 close $fd
6263 or die_error(404, "Reading git-diff-tree failed");
6264 @difftree
6265 or die_error(404, "Blob diff not found");
6267 } else {
6268 die_error(400, "Missing one of the blob diff parameters");
6271 if (@difftree > 1) {
6272 die_error(400, "Ambiguous blob diff specification");
6275 %diffinfo = parse_difftree_raw_line($difftree[0]);
6276 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6277 $file_name ||= $diffinfo{'to_file'};
6279 $hash_parent ||= $diffinfo{'from_id'};
6280 $hash ||= $diffinfo{'to_id'};
6282 # non-textual hash id's can be cached
6283 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6284 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6285 $expires = '+1d';
6288 # open patch output
6289 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6290 '-p', ($format eq 'html' ? "--full-index" : ()),
6291 $hash_parent_base, $hash_base,
6292 "--", (defined $file_parent ? $file_parent : ()), $file_name
6293 or die_error(500, "Open git-diff-tree failed");
6296 # old/legacy style URI -- not generated anymore since 1.4.3.
6297 if (!%diffinfo) {
6298 die_error('404 Not Found', "Missing one of the blob diff parameters")
6301 # header
6302 if ($format eq 'html') {
6303 my $formats_nav =
6304 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6305 "raw");
6306 git_header_html(undef, $expires);
6307 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6308 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6309 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6310 } else {
6311 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6312 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6314 if (defined $file_name) {
6315 git_print_page_path($file_name, "blob", $hash_base);
6316 } else {
6317 print "<div class=\"page_path\"></div>\n";
6320 } elsif ($format eq 'plain') {
6321 print $cgi->header(
6322 -type => 'text/plain',
6323 -charset => 'utf-8',
6324 -expires => $expires,
6325 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6327 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6329 } else {
6330 die_error(400, "Unknown blobdiff format");
6333 # patch
6334 if ($format eq 'html') {
6335 print "<div class=\"page_body\">\n";
6337 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6338 close $fd;
6340 print "</div>\n"; # class="page_body"
6341 git_footer_html();
6343 } else {
6344 while (my $line = <$fd>) {
6345 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6346 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6348 print $line;
6350 last if $line =~ m!^\+\+\+!;
6352 local $/ = undef;
6353 print <$fd>;
6354 close $fd;
6358 sub git_blobdiff_plain {
6359 git_blobdiff('plain');
6362 sub git_commitdiff {
6363 my %params = @_;
6364 my $format = $params{-format} || 'html';
6366 my ($patch_max) = gitweb_get_feature('patches');
6367 if ($format eq 'patch') {
6368 die_error(403, "Patch view not allowed") unless $patch_max;
6371 $hash ||= $hash_base || "HEAD";
6372 my %co = parse_commit($hash)
6373 or die_error(404, "Unknown commit object");
6375 # choose format for commitdiff for merge
6376 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6377 $hash_parent = '--cc';
6379 # we need to prepare $formats_nav before almost any parameter munging
6380 my $formats_nav;
6381 if ($format eq 'html') {
6382 $formats_nav =
6383 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6384 "raw");
6385 if ($patch_max && @{$co{'parents'}} <= 1) {
6386 $formats_nav .= " | " .
6387 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6388 "patch");
6391 if (defined $hash_parent &&
6392 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6393 # commitdiff with two commits given
6394 my $hash_parent_short = $hash_parent;
6395 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6396 $hash_parent_short = substr($hash_parent, 0, 7);
6398 $formats_nav .=
6399 ' (from';
6400 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6401 if ($co{'parents'}[$i] eq $hash_parent) {
6402 $formats_nav .= ' parent ' . ($i+1);
6403 last;
6406 $formats_nav .= ': ' .
6407 $cgi->a({-href => href(action=>"commitdiff",
6408 hash=>$hash_parent)},
6409 esc_html($hash_parent_short)) .
6410 ')';
6411 } elsif (!$co{'parent'}) {
6412 # --root commitdiff
6413 $formats_nav .= ' (initial)';
6414 } elsif (scalar @{$co{'parents'}} == 1) {
6415 # single parent commit
6416 $formats_nav .=
6417 ' (parent: ' .
6418 $cgi->a({-href => href(action=>"commitdiff",
6419 hash=>$co{'parent'})},
6420 esc_html(substr($co{'parent'}, 0, 7))) .
6421 ')';
6422 } else {
6423 # merge commit
6424 if ($hash_parent eq '--cc') {
6425 $formats_nav .= ' | ' .
6426 $cgi->a({-href => href(action=>"commitdiff",
6427 hash=>$hash, hash_parent=>'-c')},
6428 'combined');
6429 } else { # $hash_parent eq '-c'
6430 $formats_nav .= ' | ' .
6431 $cgi->a({-href => href(action=>"commitdiff",
6432 hash=>$hash, hash_parent=>'--cc')},
6433 'compact');
6435 $formats_nav .=
6436 ' (merge: ' .
6437 join(' ', map {
6438 $cgi->a({-href => href(action=>"commitdiff",
6439 hash=>$_)},
6440 esc_html(substr($_, 0, 7)));
6441 } @{$co{'parents'}} ) .
6442 ')';
6446 my $hash_parent_param = $hash_parent;
6447 if (!defined $hash_parent_param) {
6448 # --cc for multiple parents, --root for parentless
6449 $hash_parent_param =
6450 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6453 # read commitdiff
6454 my $fd;
6455 my @difftree;
6456 if ($format eq 'html') {
6457 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6458 "--no-commit-id", "--patch-with-raw", "--full-index",
6459 $hash_parent_param, $hash, "--"
6460 or die_error(500, "Open git-diff-tree failed");
6462 while (my $line = <$fd>) {
6463 chomp $line;
6464 # empty line ends raw part of diff-tree output
6465 last unless $line;
6466 push @difftree, scalar parse_difftree_raw_line($line);
6469 } elsif ($format eq 'plain') {
6470 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6471 '-p', $hash_parent_param, $hash, "--"
6472 or die_error(500, "Open git-diff-tree failed");
6473 } elsif ($format eq 'patch') {
6474 # For commit ranges, we limit the output to the number of
6475 # patches specified in the 'patches' feature.
6476 # For single commits, we limit the output to a single patch,
6477 # diverging from the git-format-patch default.
6478 my @commit_spec = ();
6479 if ($hash_parent) {
6480 if ($patch_max > 0) {
6481 push @commit_spec, "-$patch_max";
6483 push @commit_spec, '-n', "$hash_parent..$hash";
6484 } else {
6485 if ($params{-single}) {
6486 push @commit_spec, '-1';
6487 } else {
6488 if ($patch_max > 0) {
6489 push @commit_spec, "-$patch_max";
6491 push @commit_spec, "-n";
6493 push @commit_spec, '--root', $hash;
6495 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6496 '--encoding=utf8', '--stdout', @commit_spec
6497 or die_error(500, "Open git-format-patch failed");
6498 } else {
6499 die_error(400, "Unknown commitdiff format");
6502 # non-textual hash id's can be cached
6503 my $expires;
6504 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6505 $expires = "+1d";
6508 # write commit message
6509 if ($format eq 'html') {
6510 my $refs = git_get_references();
6511 my $ref = format_ref_marker($refs, $co{'id'});
6513 git_header_html(undef, $expires);
6514 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6515 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6516 print "<div class=\"title_text\">\n" .
6517 "<table class=\"object_header\">\n";
6518 git_print_authorship_rows(\%co);
6519 print "</table>".
6520 "</div>\n";
6521 print "<div class=\"page_body\">\n";
6522 if (@{$co{'comment'}} > 1) {
6523 print "<div class=\"log\">\n";
6524 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6525 print "</div>\n"; # class="log"
6528 } elsif ($format eq 'plain') {
6529 my $refs = git_get_references("tags");
6530 my $tagname = git_get_rev_name_tags($hash);
6531 my $filename = basename($project) . "-$hash.patch";
6533 print $cgi->header(
6534 -type => 'text/plain',
6535 -charset => 'utf-8',
6536 -expires => $expires,
6537 -content_disposition => 'inline; filename="' . "$filename" . '"');
6538 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6539 print "From: " . to_utf8($co{'author'}) . "\n";
6540 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6541 print "Subject: " . to_utf8($co{'title'}) . "\n";
6543 print "X-Git-Tag: $tagname\n" if $tagname;
6544 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6546 foreach my $line (@{$co{'comment'}}) {
6547 print to_utf8($line) . "\n";
6549 print "---\n\n";
6550 } elsif ($format eq 'patch') {
6551 my $filename = basename($project) . "-$hash.patch";
6553 print $cgi->header(
6554 -type => 'text/plain',
6555 -charset => 'utf-8',
6556 -expires => $expires,
6557 -content_disposition => 'inline; filename="' . "$filename" . '"');
6560 # write patch
6561 if ($format eq 'html') {
6562 my $use_parents = !defined $hash_parent ||
6563 $hash_parent eq '-c' || $hash_parent eq '--cc';
6564 git_difftree_body(\@difftree, $hash,
6565 $use_parents ? @{$co{'parents'}} : $hash_parent);
6566 print "<br/>\n";
6568 git_patchset_body($fd, \@difftree, $hash,
6569 $use_parents ? @{$co{'parents'}} : $hash_parent);
6570 close $fd;
6571 print "</div>\n"; # class="page_body"
6572 git_footer_html();
6574 } elsif ($format eq 'plain') {
6575 local $/ = undef;
6576 print <$fd>;
6577 close $fd
6578 or print "Reading git-diff-tree failed\n";
6579 } elsif ($format eq 'patch') {
6580 local $/ = undef;
6581 print <$fd>;
6582 close $fd
6583 or print "Reading git-format-patch failed\n";
6587 sub git_commitdiff_plain {
6588 git_commitdiff(-format => 'plain');
6591 # format-patch-style patches
6592 sub git_patch {
6593 git_commitdiff(-format => 'patch', -single => 1);
6596 sub git_patches {
6597 git_commitdiff(-format => 'patch');
6600 sub git_history {
6601 git_log_generic('history', \&git_history_body,
6602 $hash_base, $hash_parent_base,
6603 $file_name, $hash);
6606 sub git_search {
6607 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6608 if (!defined $searchtext) {
6609 die_error(400, "Text field is empty");
6611 if (!defined $hash) {
6612 $hash = git_get_head_hash($project);
6614 my %co = parse_commit($hash);
6615 if (!%co) {
6616 die_error(404, "Unknown commit object");
6618 if (!defined $page) {
6619 $page = 0;
6622 $searchtype ||= 'commit';
6623 if ($searchtype eq 'pickaxe') {
6624 # pickaxe may take all resources of your box and run for several minutes
6625 # with every query - so decide by yourself how public you make this feature
6626 gitweb_check_feature('pickaxe')
6627 or die_error(403, "Pickaxe is disabled");
6629 if ($searchtype eq 'grep') {
6630 gitweb_check_feature('grep')
6631 or die_error(403, "Grep is disabled");
6634 git_header_html();
6636 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6637 my $greptype;
6638 if ($searchtype eq 'commit') {
6639 $greptype = "--grep=";
6640 } elsif ($searchtype eq 'author') {
6641 $greptype = "--author=";
6642 } elsif ($searchtype eq 'committer') {
6643 $greptype = "--committer=";
6645 $greptype .= $searchtext;
6646 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6647 $greptype, '--regexp-ignore-case',
6648 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6650 my $paging_nav = '';
6651 if ($page > 0) {
6652 $paging_nav .=
6653 $cgi->a({-href => href(action=>"search", hash=>$hash,
6654 searchtext=>$searchtext,
6655 searchtype=>$searchtype)},
6656 "first");
6657 $paging_nav .= " &sdot; " .
6658 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6659 -accesskey => "p", -title => "Alt-p"}, "prev");
6660 } else {
6661 $paging_nav .= "first";
6662 $paging_nav .= " &sdot; prev";
6664 my $next_link = '';
6665 if ($#commitlist >= 100) {
6666 $next_link =
6667 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6668 -accesskey => "n", -title => "Alt-n"}, "next");
6669 $paging_nav .= " &sdot; $next_link";
6670 } else {
6671 $paging_nav .= " &sdot; next";
6674 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6675 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6676 if ($page == 0 && !@commitlist) {
6677 print "<p>No match.</p>\n";
6678 } else {
6679 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6683 if ($searchtype eq 'pickaxe') {
6684 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6685 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6687 print "<table class=\"pickaxe search\">\n";
6688 my $alternate = 1;
6689 local $/ = "\n";
6690 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6691 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6692 ($search_use_regexp ? '--pickaxe-regex' : ());
6693 undef %co;
6694 my @files;
6695 while (my $line = <$fd>) {
6696 chomp $line;
6697 next unless $line;
6699 my %set = parse_difftree_raw_line($line);
6700 if (defined $set{'commit'}) {
6701 # finish previous commit
6702 if (%co) {
6703 print "</td>\n" .
6704 "<td class=\"link\">" .
6705 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6706 " | " .
6707 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6708 print "</td>\n" .
6709 "</tr>\n";
6712 if ($alternate) {
6713 print "<tr class=\"dark\">\n";
6714 } else {
6715 print "<tr class=\"light\">\n";
6717 $alternate ^= 1;
6718 %co = parse_commit($set{'commit'});
6719 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6720 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6721 "<td><i>$author</i></td>\n" .
6722 "<td>" .
6723 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6724 -class => "list subject"},
6725 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6726 } elsif (defined $set{'to_id'}) {
6727 next if ($set{'to_id'} =~ m/^0{40}$/);
6729 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6730 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6731 -class => "list"},
6732 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6733 "<br/>\n";
6736 close $fd;
6738 # finish last commit (warning: repetition!)
6739 if (%co) {
6740 print "</td>\n" .
6741 "<td class=\"link\">" .
6742 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6743 " | " .
6744 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6745 print "</td>\n" .
6746 "</tr>\n";
6749 print "</table>\n";
6752 if ($searchtype eq 'grep') {
6753 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6754 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6756 print "<table class=\"grep_search\">\n";
6757 my $alternate = 1;
6758 my $matches = 0;
6759 local $/ = "\n";
6760 open my $fd, "-|", git_cmd(), 'grep', '-n',
6761 $search_use_regexp ? ('-E', '-i') : '-F',
6762 $searchtext, $co{'tree'};
6763 my $lastfile = '';
6764 while (my $line = <$fd>) {
6765 chomp $line;
6766 my ($file, $lno, $ltext, $binary);
6767 last if ($matches++ > 1000);
6768 if ($line =~ /^Binary file (.+) matches$/) {
6769 $file = $1;
6770 $binary = 1;
6771 } else {
6772 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6774 if ($file ne $lastfile) {
6775 $lastfile and print "</td></tr>\n";
6776 if ($alternate++) {
6777 print "<tr class=\"dark\">\n";
6778 } else {
6779 print "<tr class=\"light\">\n";
6781 print "<td class=\"list\">".
6782 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6783 file_name=>"$file"),
6784 -class => "list"}, esc_path($file));
6785 print "</td><td>\n";
6786 $lastfile = $file;
6788 if ($binary) {
6789 print "<div class=\"binary\">Binary file</div>\n";
6790 } else {
6791 $ltext = untabify($ltext);
6792 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6793 $ltext = esc_html($1, -nbsp=>1);
6794 $ltext .= '<span class="match">';
6795 $ltext .= esc_html($2, -nbsp=>1);
6796 $ltext .= '</span>';
6797 $ltext .= esc_html($3, -nbsp=>1);
6798 } else {
6799 $ltext = esc_html($ltext, -nbsp=>1);
6801 print "<div class=\"pre\">" .
6802 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6803 file_name=>"$file").'#l'.$lno,
6804 -class => "linenr"}, sprintf('%4i', $lno))
6805 . ' ' . $ltext . "</div>\n";
6808 if ($lastfile) {
6809 print "</td></tr>\n";
6810 if ($matches > 1000) {
6811 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6813 } else {
6814 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6816 close $fd;
6818 print "</table>\n";
6820 git_footer_html();
6823 sub git_search_help {
6824 git_header_html();
6825 git_print_page_nav('','', $hash,$hash,$hash);
6826 print <<EOT;
6827 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6828 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6829 the pattern entered is recognized as the POSIX extended
6830 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6831 insensitive).</p>
6832 <dl>
6833 <dt><b>commit</b></dt>
6834 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6836 my $have_grep = gitweb_check_feature('grep');
6837 if ($have_grep) {
6838 print <<EOT;
6839 <dt><b>grep</b></dt>
6840 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6841 a different one) are searched for the given pattern. On large trees, this search can take
6842 a while and put some strain on the server, so please use it with some consideration. Note that
6843 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6844 case-sensitive.</dd>
6847 print <<EOT;
6848 <dt><b>author</b></dt>
6849 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6850 <dt><b>committer</b></dt>
6851 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6853 my $have_pickaxe = gitweb_check_feature('pickaxe');
6854 if ($have_pickaxe) {
6855 print <<EOT;
6856 <dt><b>pickaxe</b></dt>
6857 <dd>All commits that caused the string to appear or disappear from any file (changes that
6858 added, removed or "modified" the string) will be listed. This search can take a while and
6859 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6860 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6863 print "</dl>\n";
6864 git_footer_html();
6867 sub git_shortlog {
6868 git_log_generic('shortlog', \&git_shortlog_body,
6869 $hash, $hash_parent);
6872 ## ......................................................................
6873 ## feeds (RSS, Atom; OPML)
6875 sub git_feed {
6876 my $format = shift || 'atom';
6877 my $have_blame = gitweb_check_feature('blame');
6879 # Atom: http://www.atomenabled.org/developers/syndication/
6880 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6881 if ($format ne 'rss' && $format ne 'atom') {
6882 die_error(400, "Unknown web feed format");
6885 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6886 my $head = $hash || 'HEAD';
6887 my @commitlist = parse_commits($head, 150, 0, $file_name);
6889 my %latest_commit;
6890 my %latest_date;
6891 my $content_type = "application/$format+xml";
6892 if (defined $cgi->http('HTTP_ACCEPT') &&
6893 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6894 # browser (feed reader) prefers text/xml
6895 $content_type = 'text/xml';
6897 if (defined($commitlist[0])) {
6898 %latest_commit = %{$commitlist[0]};
6899 my $latest_epoch = $latest_commit{'committer_epoch'};
6900 %latest_date = parse_date($latest_epoch);
6901 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6902 if (defined $if_modified) {
6903 my $since;
6904 if (eval { require HTTP::Date; 1; }) {
6905 $since = HTTP::Date::str2time($if_modified);
6906 } elsif (eval { require Time::ParseDate; 1; }) {
6907 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6909 if (defined $since && $latest_epoch <= $since) {
6910 print $cgi->header(
6911 -type => $content_type,
6912 -charset => 'utf-8',
6913 -last_modified => $latest_date{'rfc2822'},
6914 -status => '304 Not Modified');
6915 return;
6918 print $cgi->header(
6919 -type => $content_type,
6920 -charset => 'utf-8',
6921 -last_modified => $latest_date{'rfc2822'});
6922 } else {
6923 print $cgi->header(
6924 -type => $content_type,
6925 -charset => 'utf-8');
6928 # Optimization: skip generating the body if client asks only
6929 # for Last-Modified date.
6930 return if ($cgi->request_method() eq 'HEAD');
6932 # header variables
6933 my $title = "$site_name - $project/$action";
6934 my $feed_type = 'log';
6935 if (defined $hash) {
6936 $title .= " - '$hash'";
6937 $feed_type = 'branch log';
6938 if (defined $file_name) {
6939 $title .= " :: $file_name";
6940 $feed_type = 'history';
6942 } elsif (defined $file_name) {
6943 $title .= " - $file_name";
6944 $feed_type = 'history';
6946 $title .= " $feed_type";
6947 my $descr = git_get_project_description($project);
6948 if (defined $descr) {
6949 $descr = esc_html($descr);
6950 } else {
6951 $descr = "$project " .
6952 ($format eq 'rss' ? 'RSS' : 'Atom') .
6953 " feed";
6955 my $owner = git_get_project_owner($project);
6956 $owner = esc_html($owner);
6958 #header
6959 my $alt_url;
6960 if (defined $file_name) {
6961 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6962 } elsif (defined $hash) {
6963 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6964 } else {
6965 $alt_url = href(-full=>1, action=>"summary");
6967 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6968 if ($format eq 'rss') {
6969 print <<XML;
6970 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6971 <channel>
6973 print "<title>$title</title>\n" .
6974 "<link>$alt_url</link>\n" .
6975 "<description>$descr</description>\n" .
6976 "<language>en</language>\n" .
6977 # project owner is responsible for 'editorial' content
6978 "<managingEditor>$owner</managingEditor>\n";
6979 if (defined $logo || defined $favicon) {
6980 # prefer the logo to the favicon, since RSS
6981 # doesn't allow both
6982 my $img = esc_url($logo || $favicon);
6983 print "<image>\n" .
6984 "<url>$img</url>\n" .
6985 "<title>$title</title>\n" .
6986 "<link>$alt_url</link>\n" .
6987 "</image>\n";
6989 if (%latest_date) {
6990 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6991 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6993 print "<generator>gitweb v.$version/$git_version</generator>\n";
6994 } elsif ($format eq 'atom') {
6995 print <<XML;
6996 <feed xmlns="http://www.w3.org/2005/Atom">
6998 print "<title>$title</title>\n" .
6999 "<subtitle>$descr</subtitle>\n" .
7000 '<link rel="alternate" type="text/html" href="' .
7001 $alt_url . '" />' . "\n" .
7002 '<link rel="self" type="' . $content_type . '" href="' .
7003 $cgi->self_url() . '" />' . "\n" .
7004 "<id>" . href(-full=>1) . "</id>\n" .
7005 # use project owner for feed author
7006 "<author><name>$owner</name></author>\n";
7007 if (defined $favicon) {
7008 print "<icon>" . esc_url($favicon) . "</icon>\n";
7010 if (defined $logo_url) {
7011 # not twice as wide as tall: 72 x 27 pixels
7012 print "<logo>" . esc_url($logo) . "</logo>\n";
7014 if (! %latest_date) {
7015 # dummy date to keep the feed valid until commits trickle in:
7016 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7017 } else {
7018 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7020 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7023 # contents
7024 for (my $i = 0; $i <= $#commitlist; $i++) {
7025 my %co = %{$commitlist[$i]};
7026 my $commit = $co{'id'};
7027 # we read 150, we always show 30 and the ones more recent than 48 hours
7028 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7029 last;
7031 my %cd = parse_date($co{'author_epoch'});
7033 # get list of changed files
7034 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7035 $co{'parent'} || "--root",
7036 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7037 or next;
7038 my @difftree = map { chomp; $_ } <$fd>;
7039 close $fd
7040 or next;
7042 # print element (entry, item)
7043 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7044 if ($format eq 'rss') {
7045 print "<item>\n" .
7046 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7047 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7048 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7049 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7050 "<link>$co_url</link>\n" .
7051 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7052 "<content:encoded>" .
7053 "<![CDATA[\n";
7054 } elsif ($format eq 'atom') {
7055 print "<entry>\n" .
7056 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7057 "<updated>$cd{'iso-8601'}</updated>\n" .
7058 "<author>\n" .
7059 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7060 if ($co{'author_email'}) {
7061 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7063 print "</author>\n" .
7064 # use committer for contributor
7065 "<contributor>\n" .
7066 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7067 if ($co{'committer_email'}) {
7068 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7070 print "</contributor>\n" .
7071 "<published>$cd{'iso-8601'}</published>\n" .
7072 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7073 "<id>$co_url</id>\n" .
7074 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7075 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7077 my $comment = $co{'comment'};
7078 print "<pre>\n";
7079 foreach my $line (@$comment) {
7080 $line = esc_html($line);
7081 print "$line\n";
7083 print "</pre><ul>\n";
7084 foreach my $difftree_line (@difftree) {
7085 my %difftree = parse_difftree_raw_line($difftree_line);
7086 next if !$difftree{'from_id'};
7088 my $file = $difftree{'file'} || $difftree{'to_file'};
7090 print "<li>" .
7091 "[" .
7092 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7093 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7094 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7095 file_name=>$file, file_parent=>$difftree{'from_file'}),
7096 -title => "diff"}, 'D');
7097 if ($have_blame) {
7098 print $cgi->a({-href => href(-full=>1, action=>"blame",
7099 file_name=>$file, hash_base=>$commit),
7100 -title => "blame"}, 'B');
7102 # if this is not a feed of a file history
7103 if (!defined $file_name || $file_name ne $file) {
7104 print $cgi->a({-href => href(-full=>1, action=>"history",
7105 file_name=>$file, hash=>$commit),
7106 -title => "history"}, 'H');
7108 $file = esc_path($file);
7109 print "] ".
7110 "$file</li>\n";
7112 if ($format eq 'rss') {
7113 print "</ul>]]>\n" .
7114 "</content:encoded>\n" .
7115 "</item>\n";
7116 } elsif ($format eq 'atom') {
7117 print "</ul>\n</div>\n" .
7118 "</content>\n" .
7119 "</entry>\n";
7123 # end of feed
7124 if ($format eq 'rss') {
7125 print "</channel>\n</rss>\n";
7126 } elsif ($format eq 'atom') {
7127 print "</feed>\n";
7131 sub git_rss {
7132 git_feed('rss');
7135 sub git_atom {
7136 git_feed('atom');
7139 sub git_opml {
7140 my @list = git_get_projects_list();
7142 print $cgi->header(
7143 -type => 'text/xml',
7144 -charset => 'utf-8',
7145 -content_disposition => 'inline; filename="opml.xml"');
7147 print <<XML;
7148 <?xml version="1.0" encoding="utf-8"?>
7149 <opml version="1.0">
7150 <head>
7151 <title>$site_name OPML Export</title>
7152 </head>
7153 <body>
7154 <outline text="git RSS feeds">
7157 foreach my $pr (@list) {
7158 my %proj = %$pr;
7159 my $head = git_get_head_hash($proj{'path'});
7160 if (!defined $head) {
7161 next;
7163 $git_dir = "$projectroot/$proj{'path'}";
7164 my %co = parse_commit($head);
7165 if (!%co) {
7166 next;
7169 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7170 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7171 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7172 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7174 print <<XML;
7175 </outline>
7176 </body>
7177 </opml>