gitweb: Support legacy options used by kernel.org caching engine
[git/jnareb-git.git] / gitweb / gitweb.perl
blob294fbbbb18d10de4af2821639887ad859b1abb29
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 qw(:mode :flock);
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;
288 # Legacy options configuring behavior of git.kernel.org caching
289 our ($minCacheTime, $maxCacheTime, $cachedir, $backgroundCache, $maxCacheLife);
290 # You define site-wide cache options defaults here; override them with
291 # $GITWEB_CONFIG as necessary.
292 our %cache_options = (
293 # The location in the filesystem that will hold the root of the cache.
294 # This directory will be created as needed (if possible) on the first
295 # cache set. Note that either this directory must exists and web server
296 # has to have write permissions to it, or web server must be able to
297 # create this directory.
298 # Possible values:
299 # * 'cache' (relative to gitweb),
300 # * File::Spec->catdir(File::Spec->tmpdir(), 'gitweb-cache'),
301 # * '/var/cache/gitweb' (FHS compliant, requires being set up),
302 'cache_root' => 'cache',
304 # The number of subdirectories deep to cache object item. This should be
305 # large enough that no cache directory has more than a few hundred
306 # objects. Each non-leaf directory contains up to 256 subdirectories
307 # (00-ff). Must be larger than 0.
308 'cache_depth' => 1,
310 # The (global) minimum expiration time for objects placed in the cache,
311 # in seconds. If the dynamic adaptive cache exporation time is lower
312 # than this number, we set cache timeout to this minimum.
313 'expires_min' => 20, # 20 seconds
315 # The (global) maximum expiration time for dynamic (adaptive) caching
316 # algorithm, in seconds. If the adaptive cache lifetime exceeds this
317 # number, we set cache timeout to this maximum.
318 # (If 'expires_min' >= 'expires_max', there is no adaptive cache timeout,
319 # and 'expires_min' is used as expiration time for objects in cache.)
320 'expires_max' => 1200, # 20 minutes
322 # Cache lifetime will be increased by applying this factor to the result
323 # from 'check_load' callback (see below).
324 'expires_factor' => 60, # expire time in seconds for 1.0 (100% CPU) load
326 # User supplied callback for deciding the cache policy, usually system
327 # load. Multiplied by 'expires_factor' gives adaptive expiration time,
328 # in seconds, subject to the limits imposed by 'expires_min' and
329 # 'expires_max' bounds. Set to undef (or delete) to turn off dynamic
330 # lifetime control.
331 # (Compatibile with Cache::Adaptive.)
332 'check_load' => \&get_loadavg,
334 # Maximum cache file life, in seconds. If cache entry lifetime exceeds
335 # this value, it wouldn't be served as being too stale when waiting for
336 # cache to be regenerated/refreshed, instead of trying to display
337 # existing cache date.
338 # Set it to -1 to always serve existing data if it exists,
339 # set it to 0 to turn off serving stale data - always wait.
340 'max_lifetime' => 5*60*60, # 5 hours
342 # This enables/disables background caching. If it is set to true value,
343 # caching engine would return stale data (if it is not older than
344 # 'max_lifetime' seconds) if it exists, and launch process if regenerating
345 # (refreshing) cache into the background. If it is set to false value,
346 # the process that fills cache must always wait for data to be generated.
347 # In theory this will make gitweb seem more responsive at the price of
348 # serving possibly stale data.
349 'background_cache' => 1,
351 # Subroutine which would be called when gitweb has to wait for data to
352 # be generated (it can't serve stale data because there isn't any,
353 # or if it exists it is older than 'max_lifetime'). The default
354 # is to use git_generating_data_html(), which creates "Generating..."
355 # page, which would then redirect or redraw/rewrite the page when
356 # data is ready.
357 # Set it to `undef' to disable this feature.
359 # Such subroutine (if invoked from GitwebCache::SimpleFileCache)
360 # is passed the following parameters: $cache instance, human-readable
361 # $key to current page, and filehandle $lock_fh to lockfile.
362 'generating_info' => \&git_generating_data_html,
364 # This enables/disables using 'generating_info' subroutine by process
365 # generating data, when not too stale data is not available (data is then
366 # generated in background). Because git_generating_data_html() includes
367 # initial delay (of 1 second by default), and we can assume that die_error
368 # finishes within this time, then generating error pages should be safe
369 # from infinite "Generating page..." loop.
370 'generating_info_is_safe' => 1,
372 # How to handle runtime errors occurring during cache gets and cache
373 # sets. Options are:
374 # * "die" (the default) - call die() with an appropriate message
375 # * "warn" - call warn() with an appropriate message
376 # * "ignore" - do nothing
377 # * <coderef> - call this code reference with an appropriate message
378 # Note that gitweb catches 'die <message>' via custom handle_errors_html
379 # handler, set via set_message() from CGI::Carp. 'warn <message>' are
380 # written to web server logs.
382 # The default is to use cache_error_handler, which wraps die_error.
383 # Only first argument passed to cache_error_handler is used (c.f. CHI)
384 'on_error' => \&cache_error_handler,
386 # You define site-wide options for "Generating..." page (if enabled) here
387 # (which means that $cache_options{'generating_info'} is set to coderef);
388 # override them with $GITWEB_CONFIG as necessary.
389 our %generating_options = (
390 # The delay before displaying "Generating..." page, in seconds. It is
391 # intended for "Generating..." page to be shown only when really needed.
392 'startup_delay' => 1,
393 # The time between generating new piece of output to prevent from
394 # redirection before data is ready, i.e. time between printing each
395 # dot in activity indicator / progress info, in seconds.
396 'print_interval' => 2,
397 # Maximum time "Generating..." page would be present, waiting for data,
398 # before unconditional redirect, in seconds.
399 'timeout' => $cache_options{'expires_min'},
401 # Set to _initialized_ instance of GitwebCache::Capture compatibile capturing
402 # engine, i.e. one implementing ->new() constructor, and ->capture($code)
403 # method. If unset (default), the GitwebCache::Capture::Simple would be used.
404 our $capture;
406 # You define site-wide feature defaults here; override them with
407 # $GITWEB_CONFIG as necessary.
408 our %feature = (
409 # feature => {
410 # 'sub' => feature-sub (subroutine),
411 # 'override' => allow-override (boolean),
412 # 'default' => [ default options...] (array reference)}
414 # if feature is overridable (it means that allow-override has true value),
415 # then feature-sub will be called with default options as parameters;
416 # return value of feature-sub indicates if to enable specified feature
418 # if there is no 'sub' key (no feature-sub), then feature cannot be
419 # overridden
421 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
422 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
423 # is enabled
425 # Enable the 'blame' blob view, showing the last commit that modified
426 # each line in the file. This can be very CPU-intensive.
428 # To enable system wide have in $GITWEB_CONFIG
429 # $feature{'blame'}{'default'} = [1];
430 # To have project specific config enable override in $GITWEB_CONFIG
431 # $feature{'blame'}{'override'} = 1;
432 # and in project config gitweb.blame = 0|1;
433 'blame' => {
434 'sub' => sub { feature_bool('blame', @_) },
435 'override' => 0,
436 'default' => [0]},
438 # Enable the 'snapshot' link, providing a compressed archive of any
439 # tree. This can potentially generate high traffic if you have large
440 # project.
442 # Value is a list of formats defined in %known_snapshot_formats that
443 # you wish to offer.
444 # To disable system wide have in $GITWEB_CONFIG
445 # $feature{'snapshot'}{'default'} = [];
446 # To have project specific config enable override in $GITWEB_CONFIG
447 # $feature{'snapshot'}{'override'} = 1;
448 # and in project config, a comma-separated list of formats or "none"
449 # to disable. Example: gitweb.snapshot = tbz2,zip;
450 'snapshot' => {
451 'sub' => \&feature_snapshot,
452 'override' => 0,
453 'default' => ['tgz']},
455 # Enable text search, which will list the commits which match author,
456 # committer or commit text to a given string. Enabled by default.
457 # Project specific override is not supported.
458 'search' => {
459 'override' => 0,
460 'default' => [1]},
462 # Enable grep search, which will list the files in currently selected
463 # tree containing the given string. Enabled by default. This can be
464 # potentially CPU-intensive, of course.
466 # To enable system wide have in $GITWEB_CONFIG
467 # $feature{'grep'}{'default'} = [1];
468 # To have project specific config enable override in $GITWEB_CONFIG
469 # $feature{'grep'}{'override'} = 1;
470 # and in project config gitweb.grep = 0|1;
471 'grep' => {
472 'sub' => sub { feature_bool('grep', @_) },
473 'override' => 0,
474 'default' => [1]},
476 # Enable the pickaxe search, which will list the commits that modified
477 # a given string in a file. This can be practical and quite faster
478 # alternative to 'blame', but still potentially CPU-intensive.
480 # To enable system wide have in $GITWEB_CONFIG
481 # $feature{'pickaxe'}{'default'} = [1];
482 # To have project specific config enable override in $GITWEB_CONFIG
483 # $feature{'pickaxe'}{'override'} = 1;
484 # and in project config gitweb.pickaxe = 0|1;
485 'pickaxe' => {
486 'sub' => sub { feature_bool('pickaxe', @_) },
487 'override' => 0,
488 'default' => [1]},
490 # Enable showing size of blobs in a 'tree' view, in a separate
491 # column, similar to what 'ls -l' does. This cost a bit of IO.
493 # To disable system wide have in $GITWEB_CONFIG
494 # $feature{'show-sizes'}{'default'} = [0];
495 # To have project specific config enable override in $GITWEB_CONFIG
496 # $feature{'show-sizes'}{'override'} = 1;
497 # and in project config gitweb.showsizes = 0|1;
498 'show-sizes' => {
499 'sub' => sub { feature_bool('showsizes', @_) },
500 'override' => 0,
501 'default' => [1]},
503 # Make gitweb use an alternative format of the URLs which can be
504 # more readable and natural-looking: project name is embedded
505 # directly in the path and the query string contains other
506 # auxiliary information. All gitweb installations recognize
507 # URL in either format; this configures in which formats gitweb
508 # generates links.
510 # To enable system wide have in $GITWEB_CONFIG
511 # $feature{'pathinfo'}{'default'} = [1];
512 # Project specific override is not supported.
514 # Note that you will need to change the default location of CSS,
515 # favicon, logo and possibly other files to an absolute URL. Also,
516 # if gitweb.cgi serves as your indexfile, you will need to force
517 # $my_uri to contain the script name in your $GITWEB_CONFIG.
518 'pathinfo' => {
519 'override' => 0,
520 'default' => [0]},
522 # Make gitweb consider projects in project root subdirectories
523 # to be forks of existing projects. Given project $projname.git,
524 # projects matching $projname/*.git will not be shown in the main
525 # projects list, instead a '+' mark will be added to $projname
526 # there and a 'forks' view will be enabled for the project, listing
527 # all the forks. If project list is taken from a file, forks have
528 # to be listed after the main project.
530 # To enable system wide have in $GITWEB_CONFIG
531 # $feature{'forks'}{'default'} = [1];
532 # Project specific override is not supported.
533 'forks' => {
534 'override' => 0,
535 'default' => [0]},
537 # Insert custom links to the action bar of all project pages.
538 # This enables you mainly to link to third-party scripts integrating
539 # into gitweb; e.g. git-browser for graphical history representation
540 # or custom web-based repository administration interface.
542 # The 'default' value consists of a list of triplets in the form
543 # (label, link, position) where position is the label after which
544 # to insert the link and link is a format string where %n expands
545 # to the project name, %f to the project path within the filesystem,
546 # %h to the current hash (h gitweb parameter) and %b to the current
547 # hash base (hb gitweb parameter); %% expands to %.
549 # To enable system wide have in $GITWEB_CONFIG e.g.
550 # $feature{'actions'}{'default'} = [('graphiclog',
551 # '/git-browser/by-commit.html?r=%n', 'summary')];
552 # Project specific override is not supported.
553 'actions' => {
554 'override' => 0,
555 'default' => []},
557 # Allow gitweb scan project content tags described in ctags/
558 # of project repository, and display the popular Web 2.0-ish
559 # "tag cloud" near the project list. Note that this is something
560 # COMPLETELY different from the normal Git tags.
562 # gitweb by itself can show existing tags, but it does not handle
563 # tagging itself; you need an external application for that.
564 # For an example script, check Girocco's cgi/tagproj.cgi.
565 # You may want to install the HTML::TagCloud Perl module to get
566 # a pretty tag cloud instead of just a list of tags.
568 # To enable system wide have in $GITWEB_CONFIG
569 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
570 # Project specific override is not supported.
571 'ctags' => {
572 'override' => 0,
573 'default' => [0]},
575 # The maximum number of patches in a patchset generated in patch
576 # view. Set this to 0 or undef to disable patch view, or to a
577 # negative number to remove any limit.
579 # To disable system wide have in $GITWEB_CONFIG
580 # $feature{'patches'}{'default'} = [0];
581 # To have project specific config enable override in $GITWEB_CONFIG
582 # $feature{'patches'}{'override'} = 1;
583 # and in project config gitweb.patches = 0|n;
584 # where n is the maximum number of patches allowed in a patchset.
585 'patches' => {
586 'sub' => \&feature_patches,
587 'override' => 0,
588 'default' => [16]},
590 # Avatar support. When this feature is enabled, views such as
591 # shortlog or commit will display an avatar associated with
592 # the email of the committer(s) and/or author(s).
594 # Currently available providers are gravatar and picon.
595 # If an unknown provider is specified, the feature is disabled.
597 # Gravatar depends on Digest::MD5.
598 # Picon currently relies on the indiana.edu database.
600 # To enable system wide have in $GITWEB_CONFIG
601 # $feature{'avatar'}{'default'} = ['<provider>'];
602 # where <provider> is either gravatar or picon.
603 # To have project specific config enable override in $GITWEB_CONFIG
604 # $feature{'avatar'}{'override'} = 1;
605 # and in project config gitweb.avatar = <provider>;
606 'avatar' => {
607 'sub' => \&feature_avatar,
608 'override' => 0,
609 'default' => ['']},
611 # Enable displaying how much time and how many git commands
612 # it took to generate and display page. Disabled by default.
613 # Project specific override is not supported.
614 'timed' => {
615 'override' => 0,
616 'default' => [0]},
618 # Enable turning some links into links to actions which require
619 # JavaScript to run (like 'blame_incremental'). Not enabled by
620 # default. Project specific override is currently not supported.
621 'javascript-actions' => {
622 'override' => 0,
623 'default' => [0]},
625 # Syntax highlighting support. This is based on Daniel Svensson's
626 # and Sham Chukoury's work in gitweb-xmms2.git.
627 # It requires the 'highlight' program present in $PATH,
628 # and therefore is disabled by default.
630 # To enable system wide have in $GITWEB_CONFIG
631 # $feature{'highlight'}{'default'} = [1];
633 'highlight' => {
634 'sub' => sub { feature_bool('highlight', @_) },
635 'override' => 0,
636 'default' => [0]},
639 sub gitweb_get_feature {
640 my ($name) = @_;
641 return unless exists $feature{$name};
642 my ($sub, $override, @defaults) = (
643 $feature{$name}{'sub'},
644 $feature{$name}{'override'},
645 @{$feature{$name}{'default'}});
646 # project specific override is possible only if we have project
647 our $git_dir; # global variable, declared later
648 if (!$override || !defined $git_dir) {
649 return @defaults;
651 if (!defined $sub) {
652 warn "feature $name is not overridable";
653 return @defaults;
655 return $sub->(@defaults);
658 # A wrapper to check if a given feature is enabled.
659 # With this, you can say
661 # my $bool_feat = gitweb_check_feature('bool_feat');
662 # gitweb_check_feature('bool_feat') or somecode;
664 # instead of
666 # my ($bool_feat) = gitweb_get_feature('bool_feat');
667 # (gitweb_get_feature('bool_feat'))[0] or somecode;
669 sub gitweb_check_feature {
670 return (gitweb_get_feature(@_))[0];
674 sub feature_bool {
675 my $key = shift;
676 my ($val) = git_get_project_config($key, '--bool');
678 if (!defined $val) {
679 return ($_[0]);
680 } elsif ($val eq 'true') {
681 return (1);
682 } elsif ($val eq 'false') {
683 return (0);
687 sub feature_snapshot {
688 my (@fmts) = @_;
690 my ($val) = git_get_project_config('snapshot');
692 if ($val) {
693 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
696 return @fmts;
699 sub feature_patches {
700 my @val = (git_get_project_config('patches', '--int'));
702 if (@val) {
703 return @val;
706 return ($_[0]);
709 sub feature_avatar {
710 my @val = (git_get_project_config('avatar'));
712 return @val ? @val : @_;
715 # checking HEAD file with -e is fragile if the repository was
716 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
717 # and then pruned.
718 sub check_head_link {
719 my ($dir) = @_;
720 my $headfile = "$dir/HEAD";
721 return ((-e $headfile) ||
722 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
725 sub check_export_ok {
726 my ($dir) = @_;
727 return (check_head_link($dir) &&
728 (!$export_ok || -e "$dir/$export_ok") &&
729 (!$export_auth_hook || $export_auth_hook->($dir)));
732 # process alternate names for backward compatibility
733 # filter out unsupported (unknown) snapshot formats
734 sub filter_snapshot_fmts {
735 my @fmts = @_;
737 @fmts = map {
738 exists $known_snapshot_format_aliases{$_} ?
739 $known_snapshot_format_aliases{$_} : $_} @fmts;
740 @fmts = grep {
741 exists $known_snapshot_formats{$_} &&
742 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
745 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
746 sub evaluate_gitweb_config {
747 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
748 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
749 # die if there are errors parsing config file
750 if (-e $GITWEB_CONFIG) {
751 do $GITWEB_CONFIG;
752 die $@ if $@;
753 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
754 do $GITWEB_CONFIG_SYSTEM;
755 die $@ if $@;
759 # Get loadavg of system, to compare against $maxload.
760 # Currently it requires '/proc/loadavg' present to get loadavg;
761 # if it is not present it returns 0, which means no load checking.
762 sub get_loadavg {
763 if( -e '/proc/loadavg' ){
764 open my $fd, '<', '/proc/loadavg'
765 or return 0;
766 my @load = split(/\s+/, scalar <$fd>);
767 close $fd;
769 # The first three columns measure CPU and IO utilization of the last one,
770 # five, and 10 minute periods. The fourth column shows the number of
771 # currently running processes and the total number of processes in the m/n
772 # format. The last column displays the last process ID used.
773 return $load[0] || 0;
775 # additional checks for load average should go here for things that don't export
776 # /proc/loadavg
778 return 0;
781 # version of the core git binary
782 our $git_version;
783 sub evaluate_git_version {
784 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
785 $number_of_git_cmds++;
788 sub check_loadavg {
789 if (defined $maxload && get_loadavg() > $maxload) {
790 die_error(503, "The load average on the server is too high");
794 # ======================================================================
795 # input validation and dispatch
797 # input parameters can be collected from a variety of sources (presently, CGI
798 # and PATH_INFO), so we define an %input_params hash that collects them all
799 # together during validation: this allows subsequent uses (e.g. href()) to be
800 # agnostic of the parameter origin
802 our %input_params = ();
804 # input parameters are stored with the long parameter name as key. This will
805 # also be used in the href subroutine to convert parameters to their CGI
806 # equivalent, and since the href() usage is the most frequent one, we store
807 # the name -> CGI key mapping here, instead of the reverse.
809 # XXX: Warning: If you touch this, check the search form for updating,
810 # too.
812 our @cgi_param_mapping = (
813 project => "p",
814 action => "a",
815 file_name => "f",
816 file_parent => "fp",
817 hash => "h",
818 hash_parent => "hp",
819 hash_base => "hb",
820 hash_parent_base => "hpb",
821 page => "pg",
822 order => "o",
823 searchtext => "s",
824 searchtype => "st",
825 snapshot_format => "sf",
826 extra_options => "opt",
827 search_use_regexp => "sr",
828 # this must be last entry (for manipulation from JavaScript)
829 javascript => "js"
831 our %cgi_param_mapping = @cgi_param_mapping;
833 # we will also need to know the possible actions, for validation
834 our %actions = (
835 "blame" => \&git_blame,
836 "blame_incremental" => \&git_blame_incremental,
837 "blame_data" => \&git_blame_data,
838 "blobdiff" => \&git_blobdiff,
839 "blobdiff_plain" => \&git_blobdiff_plain,
840 "blob" => \&git_blob,
841 "blob_plain" => \&git_blob_plain,
842 "commitdiff" => \&git_commitdiff,
843 "commitdiff_plain" => \&git_commitdiff_plain,
844 "commit" => \&git_commit,
845 "forks" => \&git_forks,
846 "heads" => \&git_heads,
847 "history" => \&git_history,
848 "log" => \&git_log,
849 "patch" => \&git_patch,
850 "patches" => \&git_patches,
851 "rss" => \&git_rss,
852 "atom" => \&git_atom,
853 "search" => \&git_search,
854 "search_help" => \&git_search_help,
855 "shortlog" => \&git_shortlog,
856 "summary" => \&git_summary,
857 "tag" => \&git_tag,
858 "tags" => \&git_tags,
859 "tree" => \&git_tree,
860 "snapshot" => \&git_snapshot,
861 "object" => \&git_object,
862 # those below don't need $project
863 "opml" => \&git_opml,
864 "project_list" => \&git_project_list,
865 "project_index" => \&git_project_index,
868 # finally, we have the hash of allowed extra_options for the commands that
869 # allow them
870 our %allowed_options = (
871 "--no-merges" => [ qw(rss atom log shortlog history) ],
874 our %actions_info = ();
875 sub evaluate_actions_info {
876 our %actions_info;
877 our (%actions);
879 # unless explicitely stated otherwise, default output format is html
880 foreach my $action (keys %actions) {
881 $actions_info{$action}{'output_format'} = 'html';
883 # list all exceptions; undef means variable (no definite format)
884 map { $actions_info{$_}{'output_format'} = 'text' }
885 qw(commitdiff_plain patch patches project_index blame_data);
886 map { $actions_info{$_}{'output_format'} = 'xml' }
887 qw(rss atom opml); # there are different types (document formats) of XML
888 map { $actions_info{$_}{'output_format'} = undef }
889 qw(blob_plain object);
890 $actions_info{'snapshot'}{'output_format'} = 'binary';
893 sub action_outputs_html {
894 my $action = shift;
895 return $actions_info{$action}{'output_format'} eq 'html';
898 sub browser_is_robot {
899 return 1 if !exists $ENV{'HTTP_USER_AGENT'}; # gitweb run as script
900 if (eval { require HTTP::BrowserDetect; }) {
901 my $browser = HTTP::BrowserDetect->new();
902 return $browser->robot();
904 # fallback on detecting known web browsers
905 return 0 if ($ENV{'HTTP_USER_AGENT'} =~ /\b(?:Mozilla|Opera|Safari|IE)\b/);
906 # be conservative; if not sure, assume non-interactive
907 return 1;
910 # fill %input_params with the CGI parameters. All values except for 'opt'
911 # should be single values, but opt can be an array. We should probably
912 # build an array of parameters that can be multi-valued, but since for the time
913 # being it's only this one, we just single it out
914 sub evaluate_query_params {
915 our $cgi;
917 while (my ($name, $symbol) = each %cgi_param_mapping) {
918 if ($symbol eq 'opt') {
919 $input_params{$name} = [ $cgi->param($symbol) ];
920 } else {
921 $input_params{$name} = $cgi->param($symbol);
926 # now read PATH_INFO and update the parameter list for missing parameters
927 sub evaluate_path_info {
928 return if defined $input_params{'project'};
929 return if !$path_info;
930 $path_info =~ s,^/+,,;
931 return if !$path_info;
933 # find which part of PATH_INFO is project
934 my $project = $path_info;
935 $project =~ s,/+$,,;
936 while ($project && !check_head_link("$projectroot/$project")) {
937 $project =~ s,/*[^/]*$,,;
939 return unless $project;
940 $input_params{'project'} = $project;
942 # do not change any parameters if an action is given using the query string
943 return if $input_params{'action'};
944 $path_info =~ s,^\Q$project\E/*,,;
946 # next, check if we have an action
947 my $action = $path_info;
948 $action =~ s,/.*$,,;
949 if (exists $actions{$action}) {
950 $path_info =~ s,^$action/*,,;
951 $input_params{'action'} = $action;
954 # list of actions that want hash_base instead of hash, but can have no
955 # pathname (f) parameter
956 my @wants_base = (
957 'tree',
958 'history',
961 # we want to catch, among others
962 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
963 my ($parentrefname, $parentpathname, $refname, $pathname) =
964 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
966 # first, analyze the 'current' part
967 if (defined $pathname) {
968 # we got "branch:filename" or "branch:dir/"
969 # we could use git_get_type(branch:pathname), but:
970 # - it needs $git_dir
971 # - it does a git() call
972 # - the convention of terminating directories with a slash
973 # makes it superfluous
974 # - embedding the action in the PATH_INFO would make it even
975 # more superfluous
976 $pathname =~ s,^/+,,;
977 if (!$pathname || substr($pathname, -1) eq "/") {
978 $input_params{'action'} ||= "tree";
979 $pathname =~ s,/$,,;
980 } else {
981 # the default action depends on whether we had parent info
982 # or not
983 if ($parentrefname) {
984 $input_params{'action'} ||= "blobdiff_plain";
985 } else {
986 $input_params{'action'} ||= "blob_plain";
989 $input_params{'hash_base'} ||= $refname;
990 $input_params{'file_name'} ||= $pathname;
991 } elsif (defined $refname) {
992 # we got "branch". In this case we have to choose if we have to
993 # set hash or hash_base.
995 # Most of the actions without a pathname only want hash to be
996 # set, except for the ones specified in @wants_base that want
997 # hash_base instead. It should also be noted that hand-crafted
998 # links having 'history' as an action and no pathname or hash
999 # set will fail, but that happens regardless of PATH_INFO.
1000 if (defined $parentrefname) {
1001 # if there is parent let the default be 'shortlog' action
1002 # (for http://git.example.com/repo.git/A..B links); if there
1003 # is no parent, dispatch will detect type of object and set
1004 # action appropriately if required (if action is not set)
1005 $input_params{'action'} ||= "shortlog";
1007 if ($input_params{'action'} &&
1008 grep { $_ eq $input_params{'action'} } @wants_base) {
1009 $input_params{'hash_base'} ||= $refname;
1010 } else {
1011 $input_params{'hash'} ||= $refname;
1015 # next, handle the 'parent' part, if present
1016 if (defined $parentrefname) {
1017 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1018 # someproject/blobdiff/oldrev..newrev:/filename
1019 if ($parentpathname) {
1020 $parentpathname =~ s,^/+,,;
1021 $parentpathname =~ s,/$,,;
1022 $input_params{'file_parent'} ||= $parentpathname;
1023 } else {
1024 $input_params{'file_parent'} ||= $input_params{'file_name'};
1026 # we assume that hash_parent_base is wanted if a path was specified,
1027 # or if the action wants hash_base instead of hash
1028 if (defined $input_params{'file_parent'} ||
1029 grep { $_ eq $input_params{'action'} } @wants_base) {
1030 $input_params{'hash_parent_base'} ||= $parentrefname;
1031 } else {
1032 $input_params{'hash_parent'} ||= $parentrefname;
1036 # for the snapshot action, we allow URLs in the form
1037 # $project/snapshot/$hash.ext
1038 # where .ext determines the snapshot and gets removed from the
1039 # passed $refname to provide the $hash.
1041 # To be able to tell that $refname includes the format extension, we
1042 # require the following two conditions to be satisfied:
1043 # - the hash input parameter MUST have been set from the $refname part
1044 # of the URL (i.e. they must be equal)
1045 # - the snapshot format MUST NOT have been defined already (e.g. from
1046 # CGI parameter sf)
1047 # It's also useless to try any matching unless $refname has a dot,
1048 # so we check for that too
1049 if (defined $input_params{'action'} &&
1050 $input_params{'action'} eq 'snapshot' &&
1051 defined $refname && index($refname, '.') != -1 &&
1052 $refname eq $input_params{'hash'} &&
1053 !defined $input_params{'snapshot_format'}) {
1054 # We loop over the known snapshot formats, checking for
1055 # extensions. Allowed extensions are both the defined suffix
1056 # (which includes the initial dot already) and the snapshot
1057 # format key itself, with a prepended dot
1058 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1059 my $hash = $refname;
1060 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1061 next;
1063 my $sfx = $1;
1064 # a valid suffix was found, so set the snapshot format
1065 # and reset the hash parameter
1066 $input_params{'snapshot_format'} = $fmt;
1067 $input_params{'hash'} = $hash;
1068 # we also set the format suffix to the one requested
1069 # in the URL: this way a request for e.g. .tgz returns
1070 # a .tgz instead of a .tar.gz
1071 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1072 last;
1077 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1078 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1079 $searchtext, $search_regexp);
1080 sub evaluate_and_validate_params {
1081 our $action = $input_params{'action'};
1082 if (defined $action) {
1083 if (!validate_action($action)) {
1084 die_error(400, "Invalid action parameter");
1088 # parameters which are pathnames
1089 our $project = $input_params{'project'};
1090 if (defined $project) {
1091 if (!validate_project($project)) {
1092 undef $project;
1093 die_error(404, "No such project");
1097 our $file_name = $input_params{'file_name'};
1098 if (defined $file_name) {
1099 if (!validate_pathname($file_name)) {
1100 die_error(400, "Invalid file parameter");
1104 our $file_parent = $input_params{'file_parent'};
1105 if (defined $file_parent) {
1106 if (!validate_pathname($file_parent)) {
1107 die_error(400, "Invalid file parent parameter");
1111 # parameters which are refnames
1112 our $hash = $input_params{'hash'};
1113 if (defined $hash) {
1114 if (!validate_refname($hash)) {
1115 die_error(400, "Invalid hash parameter");
1119 our $hash_parent = $input_params{'hash_parent'};
1120 if (defined $hash_parent) {
1121 if (!validate_refname($hash_parent)) {
1122 die_error(400, "Invalid hash parent parameter");
1126 our $hash_base = $input_params{'hash_base'};
1127 if (defined $hash_base) {
1128 if (!validate_refname($hash_base)) {
1129 die_error(400, "Invalid hash base parameter");
1133 our @extra_options = @{$input_params{'extra_options'}};
1134 # @extra_options is always defined, since it can only be (currently) set from
1135 # CGI, and $cgi->param() returns the empty array in array context if the param
1136 # is not set
1137 foreach my $opt (@extra_options) {
1138 if (not exists $allowed_options{$opt}) {
1139 die_error(400, "Invalid option parameter");
1141 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1142 die_error(400, "Invalid option parameter for this action");
1146 our $hash_parent_base = $input_params{'hash_parent_base'};
1147 if (defined $hash_parent_base) {
1148 if (!validate_refname($hash_parent_base)) {
1149 die_error(400, "Invalid hash parent base parameter");
1153 # other parameters
1154 our $page = $input_params{'page'};
1155 if (defined $page) {
1156 if ($page =~ m/[^0-9]/) {
1157 die_error(400, "Invalid page parameter");
1161 our $searchtype = $input_params{'searchtype'};
1162 if (defined $searchtype) {
1163 if ($searchtype =~ m/[^a-z]/) {
1164 die_error(400, "Invalid searchtype parameter");
1168 our $search_use_regexp = $input_params{'search_use_regexp'};
1170 our $searchtext = $input_params{'searchtext'};
1171 our $search_regexp;
1172 if (defined $searchtext) {
1173 if (length($searchtext) < 2) {
1174 die_error(403, "At least two characters are required for search parameter");
1176 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1180 # path to the current git repository
1181 our $git_dir;
1182 sub evaluate_git_dir {
1183 our $git_dir = "$projectroot/$project" if $project;
1186 our (@snapshot_fmts, $git_avatar);
1187 sub configure_gitweb_features {
1188 # list of supported snapshot formats
1189 our @snapshot_fmts = gitweb_get_feature('snapshot');
1190 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1192 # check that the avatar feature is set to a known provider name,
1193 # and for each provider check if the dependencies are satisfied.
1194 # if the provider name is invalid or the dependencies are not met,
1195 # reset $git_avatar to the empty string.
1196 our ($git_avatar) = gitweb_get_feature('avatar');
1197 if ($git_avatar eq 'gravatar') {
1198 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1199 } elsif ($git_avatar eq 'picon') {
1200 # no dependencies
1201 } else {
1202 $git_avatar = '';
1206 # custom error handler for caching engine (Internal Server Error)
1207 sub cache_error_handler {
1208 my $error = shift;
1210 $error = to_utf8($error);
1211 $error =
1212 "Error in caching layer: <i>".ref($cache)."</i><br>\n".
1213 CGI::escapeHTML($error);
1214 # die_error() would exit
1215 die_error(undef, undef, $error);
1217 # custom error handler: 'die <message>' is Internal Server Error
1218 sub handle_errors_html {
1219 my $msg = shift; # it is already HTML escaped
1221 # to avoid infinite loop where error occurs in die_error,
1222 # change handler to default handler, disabling handle_errors_html
1223 set_message("Error occured when inside die_error:\n$msg");
1225 # you cannot jump out of die_error when called as error handler;
1226 # the subroutine set via CGI::Carp::set_message is called _after_
1227 # HTTP headers are already written, so it cannot write them itself
1228 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1230 set_message(\&handle_errors_html);
1232 # dispatch
1233 sub dispatch {
1234 if (!defined $action) {
1235 if (defined $hash) {
1236 $action = git_get_type($hash);
1237 } elsif (defined $hash_base && defined $file_name) {
1238 $action = git_get_type("$hash_base:$file_name");
1239 } elsif (defined $project) {
1240 $action = 'summary';
1241 } else {
1242 $action = 'project_list';
1245 if (!defined($actions{$action})) {
1246 die_error(400, "Unknown action");
1248 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1249 !$project) {
1250 die_error(400, "Project needed");
1253 if ($caching_enabled) {
1254 # human readable key identifying gitweb output
1255 my $output_key = href(-replay => 1, -full => 1, -path_info => 0);
1257 cache_output($cache, $capture, $output_key, $actions{$action});
1258 } else {
1259 $actions{$action}->();
1263 sub reset_timer {
1264 our $t0 = [Time::HiRes::gettimeofday()]
1265 if defined $t0;
1266 our $number_of_git_cmds = 0;
1269 sub run_request {
1270 reset_timer();
1272 evaluate_uri();
1273 evaluate_gitweb_config();
1274 evaluate_git_version();
1275 check_loadavg();
1276 configure_caching()
1277 if ($caching_enabled);
1279 # $projectroot and $projects_list might be set in gitweb config file
1280 $projects_list ||= $projectroot;
1282 evaluate_query_params();
1283 evaluate_path_info();
1284 evaluate_and_validate_params();
1285 evaluate_git_dir();
1287 configure_gitweb_features();
1289 dispatch();
1292 our $is_last_request = sub { 1 };
1293 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1294 our $CGI = 'CGI';
1295 our $cgi;
1296 sub configure_as_fcgi {
1297 require CGI::Fast;
1298 our $CGI = 'CGI::Fast';
1300 my $request_number = 0;
1301 # let each child service 100 requests
1302 our $is_last_request = sub { ++$request_number > 100 };
1304 sub evaluate_argv {
1305 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1306 configure_as_fcgi()
1307 if $script_name =~ /\.fcgi$/;
1309 return unless (@ARGV);
1311 require Getopt::Long;
1312 Getopt::Long::GetOptions(
1313 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1314 'nproc|n=i' => sub {
1315 my ($arg, $val) = @_;
1316 return unless eval { require FCGI::ProcManager; 1; };
1317 my $proc_manager = FCGI::ProcManager->new({
1318 n_processes => $val,
1320 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1321 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1322 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1327 sub run {
1328 evaluate_argv();
1329 evaluate_actions_info();
1331 $pre_listen_hook->()
1332 if $pre_listen_hook;
1334 REQUEST:
1335 while ($cgi = $CGI->new()) {
1336 $pre_dispatch_hook->()
1337 if $pre_dispatch_hook;
1339 run_request();
1341 $post_dispatch_hook->()
1342 if $post_dispatch_hook;
1344 last REQUEST if ($is_last_request->());
1347 DONE_GITWEB:
1351 sub configure_caching {
1352 if (!eval { require GitwebCache::CacheOutput; 1; }) {
1353 # cache is configured _before_ handling request, so $cgi is not defined,
1354 # so we can't just "die" with sending error message to web browser
1355 #die_error(500, "Caching enabled and GitwebCache::CacheOutput not found");
1357 # turn off caching and warn instead
1358 $caching_enabled = 0;
1359 warn "Caching enabled and GitwebCache::CacheOutput not found";
1361 GitwebCache::CacheOutput->import();
1363 # $cache might be initialized (instantiated) cache, i.e. cache object,
1364 # or it might be name of class, or it might be undefined
1365 unless (defined $cache && ref($cache)) {
1366 $cache ||= 'GitwebCache::FileCacheWithLocking';
1367 eval "require $cache";
1368 die $@ if $@;
1370 # support for legacy config variables configuring cache behavior
1371 # (those variables are/were used by caching engine by John Hawley,
1372 # used among others by custom gitweb at http://git.kernel.org);
1373 # it assumes that if those variables are defined, then we should
1374 # use them - no provision is made for having both legacy variables
1375 # and new %cache_options set in config file(s).
1376 $cache_options{'cache_root'} = $cachedir if defined $cachedir;
1377 $cache_options{'expires_min'} = $minCacheTime if defined $minCacheTime;
1378 $cache_options{'expires_max'} = $maxCacheTime if defined $maxCacheTime;
1379 $cache_options{'background_cache'} = $backgroundCache if defined $backgroundCache;
1380 $cache_options{'max_lifetime'} = $maxCacheLife if defined $maxCacheLife;
1382 $cache = $cache->new({
1383 %cache_options,
1384 #'cache_root' => '/tmp/cache',
1385 #'cache_depth' => 2,
1386 #'expires_in' => 20, # in seconds (CHI compatibile)
1387 # (Cache::Cache compatibile initialization)
1388 'default_expires_in' => $cache_options{'expires_in'},
1389 # (CHI compatibile initialization)
1390 'root_dir' => $cache_options{'cache_root'},
1391 'depth' => $cache_options{'cache_depth'},
1392 'on_get_error' => $cache_options{'on_error'},
1393 'on_set_error' => $cache_options{'on_error'},
1396 unless (defined $capture && ref($capture)) {
1397 require GitwebCache::Capture::Simple;
1398 $capture = GitwebCache::Capture::Simple->new();
1402 run();
1404 if (defined caller) {
1405 # wrapped in a subroutine processing requests,
1406 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1407 return;
1408 } else {
1409 # pure CGI script, serving single request
1410 exit;
1413 ## ======================================================================
1414 ## action links
1416 # possible values of extra options
1417 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1418 # -replay => 1 - start from a current view (replay with modifications)
1419 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1420 sub href {
1421 my %params = @_;
1422 # default is to use -absolute url() i.e. $my_uri
1423 my $href = $params{-full} ? $my_url : $my_uri;
1425 $params{'project'} = $project unless exists $params{'project'};
1427 if ($params{-replay}) {
1428 while (my ($name, $symbol) = each %cgi_param_mapping) {
1429 if (!exists $params{$name}) {
1430 $params{$name} = $input_params{$name};
1435 my $use_pathinfo = gitweb_check_feature('pathinfo');
1436 if (defined $params{'project'} &&
1437 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1438 # try to put as many parameters as possible in PATH_INFO:
1439 # - project name
1440 # - action
1441 # - hash_parent or hash_parent_base:/file_parent
1442 # - hash or hash_base:/filename
1443 # - the snapshot_format as an appropriate suffix
1445 # When the script is the root DirectoryIndex for the domain,
1446 # $href here would be something like http://gitweb.example.com/
1447 # Thus, we strip any trailing / from $href, to spare us double
1448 # slashes in the final URL
1449 $href =~ s,/$,,;
1451 # Then add the project name, if present
1452 $href .= "/".esc_url($params{'project'});
1453 delete $params{'project'};
1455 # since we destructively absorb parameters, we keep this
1456 # boolean that remembers if we're handling a snapshot
1457 my $is_snapshot = $params{'action'} eq 'snapshot';
1459 # Summary just uses the project path URL, any other action is
1460 # added to the URL
1461 if (defined $params{'action'}) {
1462 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1463 delete $params{'action'};
1466 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1467 # stripping nonexistent or useless pieces
1468 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1469 || $params{'hash_parent'} || $params{'hash'});
1470 if (defined $params{'hash_base'}) {
1471 if (defined $params{'hash_parent_base'}) {
1472 $href .= esc_url($params{'hash_parent_base'});
1473 # skip the file_parent if it's the same as the file_name
1474 if (defined $params{'file_parent'}) {
1475 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1476 delete $params{'file_parent'};
1477 } elsif ($params{'file_parent'} !~ /\.\./) {
1478 $href .= ":/".esc_url($params{'file_parent'});
1479 delete $params{'file_parent'};
1482 $href .= "..";
1483 delete $params{'hash_parent'};
1484 delete $params{'hash_parent_base'};
1485 } elsif (defined $params{'hash_parent'}) {
1486 $href .= esc_url($params{'hash_parent'}). "..";
1487 delete $params{'hash_parent'};
1490 $href .= esc_url($params{'hash_base'});
1491 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1492 $href .= ":/".esc_url($params{'file_name'});
1493 delete $params{'file_name'};
1495 delete $params{'hash'};
1496 delete $params{'hash_base'};
1497 } elsif (defined $params{'hash'}) {
1498 $href .= esc_url($params{'hash'});
1499 delete $params{'hash'};
1502 # If the action was a snapshot, we can absorb the
1503 # snapshot_format parameter too
1504 if ($is_snapshot) {
1505 my $fmt = $params{'snapshot_format'};
1506 # snapshot_format should always be defined when href()
1507 # is called, but just in case some code forgets, we
1508 # fall back to the default
1509 $fmt ||= $snapshot_fmts[0];
1510 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1511 delete $params{'snapshot_format'};
1515 # now encode the parameters explicitly
1516 my @result = ();
1517 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1518 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1519 if (defined $params{$name}) {
1520 if (ref($params{$name}) eq "ARRAY") {
1521 foreach my $par (@{$params{$name}}) {
1522 push @result, $symbol . "=" . esc_param($par);
1524 } else {
1525 push @result, $symbol . "=" . esc_param($params{$name});
1529 $href .= "?" . join(';', @result) if scalar @result;
1531 return $href;
1535 ## ======================================================================
1536 ## validation, quoting/unquoting and escaping
1538 sub validate_action {
1539 my $input = shift || return undef;
1540 return undef unless exists $actions{$input};
1541 return $input;
1544 sub validate_project {
1545 my $input = shift || return undef;
1546 if (!validate_pathname($input) ||
1547 !(-d "$projectroot/$input") ||
1548 !check_export_ok("$projectroot/$input") ||
1549 ($strict_export && !project_in_list($input))) {
1550 return undef;
1551 } else {
1552 return $input;
1556 sub validate_pathname {
1557 my $input = shift || return undef;
1559 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1560 # at the beginning, at the end, and between slashes.
1561 # also this catches doubled slashes
1562 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1563 return undef;
1565 # no null characters
1566 if ($input =~ m!\0!) {
1567 return undef;
1569 return $input;
1572 sub validate_refname {
1573 my $input = shift || return undef;
1575 # textual hashes are O.K.
1576 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1577 return $input;
1579 # it must be correct pathname
1580 $input = validate_pathname($input)
1581 or return undef;
1582 # restrictions on ref name according to git-check-ref-format
1583 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1584 return undef;
1586 return $input;
1589 # decode sequences of octets in utf8 into Perl's internal form,
1590 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1591 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1592 sub to_utf8 {
1593 my $str = shift;
1594 return undef unless defined $str;
1595 if (utf8::valid($str)) {
1596 utf8::decode($str);
1597 return $str;
1598 } else {
1599 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1603 # quote unsafe chars, but keep the slash, even when it's not
1604 # correct, but quoted slashes look too horrible in bookmarks
1605 sub esc_param {
1606 my $str = shift;
1607 return undef unless defined $str;
1608 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1609 $str =~ s/ /\+/g;
1610 return $str;
1613 # quote unsafe chars in whole URL, so some characters cannot be quoted
1614 sub esc_url {
1615 my $str = shift;
1616 return undef unless defined $str;
1617 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1618 $str =~ s/ /\+/g;
1619 return $str;
1622 # replace invalid utf8 character with SUBSTITUTION sequence
1623 sub esc_html {
1624 my $str = shift;
1625 my %opts = @_;
1627 return undef unless defined $str;
1629 $str = to_utf8($str);
1630 $str = $cgi->escapeHTML($str);
1631 if ($opts{'-nbsp'}) {
1632 $str =~ s/ /&nbsp;/g;
1634 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1635 return $str;
1638 # quote control characters and escape filename to HTML
1639 sub esc_path {
1640 my $str = shift;
1641 my %opts = @_;
1643 return undef unless defined $str;
1645 $str = to_utf8($str);
1646 $str = $cgi->escapeHTML($str);
1647 if ($opts{'-nbsp'}) {
1648 $str =~ s/ /&nbsp;/g;
1650 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1651 return $str;
1654 # Make control characters "printable", using character escape codes (CEC)
1655 sub quot_cec {
1656 my $cntrl = shift;
1657 my %opts = @_;
1658 my %es = ( # character escape codes, aka escape sequences
1659 "\t" => '\t', # tab (HT)
1660 "\n" => '\n', # line feed (LF)
1661 "\r" => '\r', # carrige return (CR)
1662 "\f" => '\f', # form feed (FF)
1663 "\b" => '\b', # backspace (BS)
1664 "\a" => '\a', # alarm (bell) (BEL)
1665 "\e" => '\e', # escape (ESC)
1666 "\013" => '\v', # vertical tab (VT)
1667 "\000" => '\0', # nul character (NUL)
1669 my $chr = ( (exists $es{$cntrl})
1670 ? $es{$cntrl}
1671 : sprintf('\%2x', ord($cntrl)) );
1672 if ($opts{-nohtml}) {
1673 return $chr;
1674 } else {
1675 return "<span class=\"cntrl\">$chr</span>";
1679 # Alternatively use unicode control pictures codepoints,
1680 # Unicode "printable representation" (PR)
1681 sub quot_upr {
1682 my $cntrl = shift;
1683 my %opts = @_;
1685 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1686 if ($opts{-nohtml}) {
1687 return $chr;
1688 } else {
1689 return "<span class=\"cntrl\">$chr</span>";
1693 # git may return quoted and escaped filenames
1694 sub unquote {
1695 my $str = shift;
1697 sub unq {
1698 my $seq = shift;
1699 my %es = ( # character escape codes, aka escape sequences
1700 't' => "\t", # tab (HT, TAB)
1701 'n' => "\n", # newline (NL)
1702 'r' => "\r", # return (CR)
1703 'f' => "\f", # form feed (FF)
1704 'b' => "\b", # backspace (BS)
1705 'a' => "\a", # alarm (bell) (BEL)
1706 'e' => "\e", # escape (ESC)
1707 'v' => "\013", # vertical tab (VT)
1710 if ($seq =~ m/^[0-7]{1,3}$/) {
1711 # octal char sequence
1712 return chr(oct($seq));
1713 } elsif (exists $es{$seq}) {
1714 # C escape sequence, aka character escape code
1715 return $es{$seq};
1717 # quoted ordinary character
1718 return $seq;
1721 if ($str =~ m/^"(.*)"$/) {
1722 # needs unquoting
1723 $str = $1;
1724 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1726 return $str;
1729 # escape tabs (convert tabs to spaces)
1730 sub untabify {
1731 my $line = shift;
1733 while ((my $pos = index($line, "\t")) != -1) {
1734 if (my $count = (8 - ($pos % 8))) {
1735 my $spaces = ' ' x $count;
1736 $line =~ s/\t/$spaces/;
1740 return $line;
1743 sub project_in_list {
1744 my $project = shift;
1745 my @list = git_get_projects_list();
1746 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1749 ## ----------------------------------------------------------------------
1750 ## HTML aware string manipulation
1752 # Try to chop given string on a word boundary between position
1753 # $len and $len+$add_len. If there is no word boundary there,
1754 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1755 # (marking chopped part) would be longer than given string.
1756 sub chop_str {
1757 my $str = shift;
1758 my $len = shift;
1759 my $add_len = shift || 10;
1760 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1762 # Make sure perl knows it is utf8 encoded so we don't
1763 # cut in the middle of a utf8 multibyte char.
1764 $str = to_utf8($str);
1766 # allow only $len chars, but don't cut a word if it would fit in $add_len
1767 # if it doesn't fit, cut it if it's still longer than the dots we would add
1768 # remove chopped character entities entirely
1770 # when chopping in the middle, distribute $len into left and right part
1771 # return early if chopping wouldn't make string shorter
1772 if ($where eq 'center') {
1773 return $str if ($len + 5 >= length($str)); # filler is length 5
1774 $len = int($len/2);
1775 } else {
1776 return $str if ($len + 4 >= length($str)); # filler is length 4
1779 # regexps: ending and beginning with word part up to $add_len
1780 my $endre = qr/.{$len}\w{0,$add_len}/;
1781 my $begre = qr/\w{0,$add_len}.{$len}/;
1783 if ($where eq 'left') {
1784 $str =~ m/^(.*?)($begre)$/;
1785 my ($lead, $body) = ($1, $2);
1786 if (length($lead) > 4) {
1787 $lead = " ...";
1789 return "$lead$body";
1791 } elsif ($where eq 'center') {
1792 $str =~ m/^($endre)(.*)$/;
1793 my ($left, $str) = ($1, $2);
1794 $str =~ m/^(.*?)($begre)$/;
1795 my ($mid, $right) = ($1, $2);
1796 if (length($mid) > 5) {
1797 $mid = " ... ";
1799 return "$left$mid$right";
1801 } else {
1802 $str =~ m/^($endre)(.*)$/;
1803 my $body = $1;
1804 my $tail = $2;
1805 if (length($tail) > 4) {
1806 $tail = "... ";
1808 return "$body$tail";
1812 # takes the same arguments as chop_str, but also wraps a <span> around the
1813 # result with a title attribute if it does get chopped. Additionally, the
1814 # string is HTML-escaped.
1815 sub chop_and_escape_str {
1816 my ($str) = @_;
1818 my $chopped = chop_str(@_);
1819 if ($chopped eq $str) {
1820 return esc_html($chopped);
1821 } else {
1822 $str =~ s/[[:cntrl:]]/?/g;
1823 return $cgi->span({-title=>$str}, esc_html($chopped));
1827 ## ----------------------------------------------------------------------
1828 ## functions returning short strings
1830 # CSS class for given age value (in seconds)
1831 sub age_class {
1832 my $age = shift;
1834 if (!defined $age) {
1835 return "noage";
1836 } elsif ($age < 60*60*2) {
1837 return "age0";
1838 } elsif ($age < 60*60*24*2) {
1839 return "age1";
1840 } else {
1841 return "age2";
1845 # convert age in seconds to "nn units ago" string
1846 sub age_string {
1847 my $age = shift;
1848 my $age_str;
1850 if ($age > 60*60*24*365*2) {
1851 $age_str = (int $age/60/60/24/365);
1852 $age_str .= " years ago";
1853 } elsif ($age > 60*60*24*(365/12)*2) {
1854 $age_str = int $age/60/60/24/(365/12);
1855 $age_str .= " months ago";
1856 } elsif ($age > 60*60*24*7*2) {
1857 $age_str = int $age/60/60/24/7;
1858 $age_str .= " weeks ago";
1859 } elsif ($age > 60*60*24*2) {
1860 $age_str = int $age/60/60/24;
1861 $age_str .= " days ago";
1862 } elsif ($age > 60*60*2) {
1863 $age_str = int $age/60/60;
1864 $age_str .= " hours ago";
1865 } elsif ($age > 60*2) {
1866 $age_str = int $age/60;
1867 $age_str .= " min ago";
1868 } elsif ($age > 2) {
1869 $age_str = int $age;
1870 $age_str .= " sec ago";
1871 } else {
1872 $age_str .= " right now";
1874 return $age_str;
1877 use constant {
1878 S_IFINVALID => 0030000,
1879 S_IFGITLINK => 0160000,
1882 # submodule/subproject, a commit object reference
1883 sub S_ISGITLINK {
1884 my $mode = shift;
1886 return (($mode & S_IFMT) == S_IFGITLINK)
1889 # convert file mode in octal to symbolic file mode string
1890 sub mode_str {
1891 my $mode = oct shift;
1893 if (S_ISGITLINK($mode)) {
1894 return 'm---------';
1895 } elsif (S_ISDIR($mode & S_IFMT)) {
1896 return 'drwxr-xr-x';
1897 } elsif (S_ISLNK($mode)) {
1898 return 'lrwxrwxrwx';
1899 } elsif (S_ISREG($mode)) {
1900 # git cares only about the executable bit
1901 if ($mode & S_IXUSR) {
1902 return '-rwxr-xr-x';
1903 } else {
1904 return '-rw-r--r--';
1906 } else {
1907 return '----------';
1911 # convert file mode in octal to file type string
1912 sub file_type {
1913 my $mode = shift;
1915 if ($mode !~ m/^[0-7]+$/) {
1916 return $mode;
1917 } else {
1918 $mode = oct $mode;
1921 if (S_ISGITLINK($mode)) {
1922 return "submodule";
1923 } elsif (S_ISDIR($mode & S_IFMT)) {
1924 return "directory";
1925 } elsif (S_ISLNK($mode)) {
1926 return "symlink";
1927 } elsif (S_ISREG($mode)) {
1928 return "file";
1929 } else {
1930 return "unknown";
1934 # convert file mode in octal to file type description string
1935 sub file_type_long {
1936 my $mode = shift;
1938 if ($mode !~ m/^[0-7]+$/) {
1939 return $mode;
1940 } else {
1941 $mode = oct $mode;
1944 if (S_ISGITLINK($mode)) {
1945 return "submodule";
1946 } elsif (S_ISDIR($mode & S_IFMT)) {
1947 return "directory";
1948 } elsif (S_ISLNK($mode)) {
1949 return "symlink";
1950 } elsif (S_ISREG($mode)) {
1951 if ($mode & S_IXUSR) {
1952 return "executable";
1953 } else {
1954 return "file";
1956 } else {
1957 return "unknown";
1962 ## ----------------------------------------------------------------------
1963 ## functions returning short HTML fragments, or transforming HTML fragments
1964 ## which don't belong to other sections
1966 # format line of commit message.
1967 sub format_log_line_html {
1968 my $line = shift;
1970 $line = esc_html($line, -nbsp=>1);
1971 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1972 $cgi->a({-href => href(action=>"object", hash=>$1),
1973 -class => "text"}, $1);
1974 }eg;
1976 return $line;
1979 # format marker of refs pointing to given object
1981 # the destination action is chosen based on object type and current context:
1982 # - for annotated tags, we choose the tag view unless it's the current view
1983 # already, in which case we go to shortlog view
1984 # - for other refs, we keep the current view if we're in history, shortlog or
1985 # log view, and select shortlog otherwise
1986 sub format_ref_marker {
1987 my ($refs, $id) = @_;
1988 my $markers = '';
1990 if (defined $refs->{$id}) {
1991 foreach my $ref (@{$refs->{$id}}) {
1992 # this code exploits the fact that non-lightweight tags are the
1993 # only indirect objects, and that they are the only objects for which
1994 # we want to use tag instead of shortlog as action
1995 my ($type, $name) = qw();
1996 my $indirect = ($ref =~ s/\^\{\}$//);
1997 # e.g. tags/v2.6.11 or heads/next
1998 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1999 $type = $1;
2000 $name = $2;
2001 } else {
2002 $type = "ref";
2003 $name = $ref;
2006 my $class = $type;
2007 $class .= " indirect" if $indirect;
2009 my $dest_action = "shortlog";
2011 if ($indirect) {
2012 $dest_action = "tag" unless $action eq "tag";
2013 } elsif ($action =~ /^(history|(short)?log)$/) {
2014 $dest_action = $action;
2017 my $dest = "";
2018 $dest .= "refs/" unless $ref =~ m!^refs/!;
2019 $dest .= $ref;
2021 my $link = $cgi->a({
2022 -href => href(
2023 action=>$dest_action,
2024 hash=>$dest
2025 )}, $name);
2027 $markers .= " <span class=\"$class\" title=\"$ref\">" .
2028 $link . "</span>";
2032 if ($markers) {
2033 return ' <span class="refs">'. $markers . '</span>';
2034 } else {
2035 return "";
2039 # format, perhaps shortened and with markers, title line
2040 sub format_subject_html {
2041 my ($long, $short, $href, $extra) = @_;
2042 $extra = '' unless defined($extra);
2044 if (length($short) < length($long)) {
2045 $long =~ s/[[:cntrl:]]/?/g;
2046 return $cgi->a({-href => $href, -class => "list subject",
2047 -title => to_utf8($long)},
2048 esc_html($short)) . $extra;
2049 } else {
2050 return $cgi->a({-href => $href, -class => "list subject"},
2051 esc_html($long)) . $extra;
2055 # Rather than recomputing the url for an email multiple times, we cache it
2056 # after the first hit. This gives a visible benefit in views where the avatar
2057 # for the same email is used repeatedly (e.g. shortlog).
2058 # The cache is shared by all avatar engines (currently gravatar only), which
2059 # are free to use it as preferred. Since only one avatar engine is used for any
2060 # given page, there's no risk for cache conflicts.
2061 our %avatar_cache = ();
2063 # Compute the picon url for a given email, by using the picon search service over at
2064 # http://www.cs.indiana.edu/picons/search.html
2065 sub picon_url {
2066 my $email = lc shift;
2067 if (!$avatar_cache{$email}) {
2068 my ($user, $domain) = split('@', $email);
2069 $avatar_cache{$email} =
2070 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2071 "$domain/$user/" .
2072 "users+domains+unknown/up/single";
2074 return $avatar_cache{$email};
2077 # Compute the gravatar url for a given email, if it's not in the cache already.
2078 # Gravatar stores only the part of the URL before the size, since that's the
2079 # one computationally more expensive. This also allows reuse of the cache for
2080 # different sizes (for this particular engine).
2081 sub gravatar_url {
2082 my $email = lc shift;
2083 my $size = shift;
2084 $avatar_cache{$email} ||=
2085 "http://www.gravatar.com/avatar/" .
2086 Digest::MD5::md5_hex($email) . "?s=";
2087 return $avatar_cache{$email} . $size;
2090 # Insert an avatar for the given $email at the given $size if the feature
2091 # is enabled.
2092 sub git_get_avatar {
2093 my ($email, %opts) = @_;
2094 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2095 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2096 $opts{-size} ||= 'default';
2097 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2098 my $url = "";
2099 if ($git_avatar eq 'gravatar') {
2100 $url = gravatar_url($email, $size);
2101 } elsif ($git_avatar eq 'picon') {
2102 $url = picon_url($email);
2104 # Other providers can be added by extending the if chain, defining $url
2105 # as needed. If no variant puts something in $url, we assume avatars
2106 # are completely disabled/unavailable.
2107 if ($url) {
2108 return $pre_white .
2109 "<img width=\"$size\" " .
2110 "class=\"avatar\" " .
2111 "src=\"$url\" " .
2112 "alt=\"\" " .
2113 "/>" . $post_white;
2114 } else {
2115 return "";
2119 sub format_search_author {
2120 my ($author, $searchtype, $displaytext) = @_;
2121 my $have_search = gitweb_check_feature('search');
2123 if ($have_search) {
2124 my $performed = "";
2125 if ($searchtype eq 'author') {
2126 $performed = "authored";
2127 } elsif ($searchtype eq 'committer') {
2128 $performed = "committed";
2131 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2132 searchtext=>$author,
2133 searchtype=>$searchtype), class=>"list",
2134 title=>"Search for commits $performed by $author"},
2135 $displaytext);
2137 } else {
2138 return $displaytext;
2142 # format the author name of the given commit with the given tag
2143 # the author name is chopped and escaped according to the other
2144 # optional parameters (see chop_str).
2145 sub format_author_html {
2146 my $tag = shift;
2147 my $co = shift;
2148 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2149 return "<$tag class=\"author\">" .
2150 format_search_author($co->{'author_name'}, "author",
2151 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2152 $author) .
2153 "</$tag>";
2156 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2157 sub format_git_diff_header_line {
2158 my $line = shift;
2159 my $diffinfo = shift;
2160 my ($from, $to) = @_;
2162 if ($diffinfo->{'nparents'}) {
2163 # combined diff
2164 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2165 if ($to->{'href'}) {
2166 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2167 esc_path($to->{'file'}));
2168 } else { # file was deleted (no href)
2169 $line .= esc_path($to->{'file'});
2171 } else {
2172 # "ordinary" diff
2173 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2174 if ($from->{'href'}) {
2175 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2176 'a/' . esc_path($from->{'file'}));
2177 } else { # file was added (no href)
2178 $line .= 'a/' . esc_path($from->{'file'});
2180 $line .= ' ';
2181 if ($to->{'href'}) {
2182 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2183 'b/' . esc_path($to->{'file'}));
2184 } else { # file was deleted
2185 $line .= 'b/' . esc_path($to->{'file'});
2189 return "<div class=\"diff header\">$line</div>\n";
2192 # format extended diff header line, before patch itself
2193 sub format_extended_diff_header_line {
2194 my $line = shift;
2195 my $diffinfo = shift;
2196 my ($from, $to) = @_;
2198 # match <path>
2199 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2200 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2201 esc_path($from->{'file'}));
2203 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2204 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2205 esc_path($to->{'file'}));
2207 # match single <mode>
2208 if ($line =~ m/\s(\d{6})$/) {
2209 $line .= '<span class="info"> (' .
2210 file_type_long($1) .
2211 ')</span>';
2213 # match <hash>
2214 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2215 # can match only for combined diff
2216 $line = 'index ';
2217 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2218 if ($from->{'href'}[$i]) {
2219 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2220 -class=>"hash"},
2221 substr($diffinfo->{'from_id'}[$i],0,7));
2222 } else {
2223 $line .= '0' x 7;
2225 # separator
2226 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2228 $line .= '..';
2229 if ($to->{'href'}) {
2230 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2231 substr($diffinfo->{'to_id'},0,7));
2232 } else {
2233 $line .= '0' x 7;
2236 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2237 # can match only for ordinary diff
2238 my ($from_link, $to_link);
2239 if ($from->{'href'}) {
2240 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2241 substr($diffinfo->{'from_id'},0,7));
2242 } else {
2243 $from_link = '0' x 7;
2245 if ($to->{'href'}) {
2246 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2247 substr($diffinfo->{'to_id'},0,7));
2248 } else {
2249 $to_link = '0' x 7;
2251 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2252 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2255 return $line . "<br/>\n";
2258 # format from-file/to-file diff header
2259 sub format_diff_from_to_header {
2260 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2261 my $line;
2262 my $result = '';
2264 $line = $from_line;
2265 #assert($line =~ m/^---/) if DEBUG;
2266 # no extra formatting for "^--- /dev/null"
2267 if (! $diffinfo->{'nparents'}) {
2268 # ordinary (single parent) diff
2269 if ($line =~ m!^--- "?a/!) {
2270 if ($from->{'href'}) {
2271 $line = '--- a/' .
2272 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2273 esc_path($from->{'file'}));
2274 } else {
2275 $line = '--- a/' .
2276 esc_path($from->{'file'});
2279 $result .= qq!<div class="diff from_file">$line</div>\n!;
2281 } else {
2282 # combined diff (merge commit)
2283 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2284 if ($from->{'href'}[$i]) {
2285 $line = '--- ' .
2286 $cgi->a({-href=>href(action=>"blobdiff",
2287 hash_parent=>$diffinfo->{'from_id'}[$i],
2288 hash_parent_base=>$parents[$i],
2289 file_parent=>$from->{'file'}[$i],
2290 hash=>$diffinfo->{'to_id'},
2291 hash_base=>$hash,
2292 file_name=>$to->{'file'}),
2293 -class=>"path",
2294 -title=>"diff" . ($i+1)},
2295 $i+1) .
2296 '/' .
2297 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2298 esc_path($from->{'file'}[$i]));
2299 } else {
2300 $line = '--- /dev/null';
2302 $result .= qq!<div class="diff from_file">$line</div>\n!;
2306 $line = $to_line;
2307 #assert($line =~ m/^\+\+\+/) if DEBUG;
2308 # no extra formatting for "^+++ /dev/null"
2309 if ($line =~ m!^\+\+\+ "?b/!) {
2310 if ($to->{'href'}) {
2311 $line = '+++ b/' .
2312 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2313 esc_path($to->{'file'}));
2314 } else {
2315 $line = '+++ b/' .
2316 esc_path($to->{'file'});
2319 $result .= qq!<div class="diff to_file">$line</div>\n!;
2321 return $result;
2324 # create note for patch simplified by combined diff
2325 sub format_diff_cc_simplified {
2326 my ($diffinfo, @parents) = @_;
2327 my $result = '';
2329 $result .= "<div class=\"diff header\">" .
2330 "diff --cc ";
2331 if (!is_deleted($diffinfo)) {
2332 $result .= $cgi->a({-href => href(action=>"blob",
2333 hash_base=>$hash,
2334 hash=>$diffinfo->{'to_id'},
2335 file_name=>$diffinfo->{'to_file'}),
2336 -class => "path"},
2337 esc_path($diffinfo->{'to_file'}));
2338 } else {
2339 $result .= esc_path($diffinfo->{'to_file'});
2341 $result .= "</div>\n" . # class="diff header"
2342 "<div class=\"diff nodifferences\">" .
2343 "Simple merge" .
2344 "</div>\n"; # class="diff nodifferences"
2346 return $result;
2349 # format patch (diff) line (not to be used for diff headers)
2350 sub format_diff_line {
2351 my $line = shift;
2352 my ($from, $to) = @_;
2353 my $diff_class = "";
2355 chomp $line;
2357 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2358 # combined diff
2359 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2360 if ($line =~ m/^\@{3}/) {
2361 $diff_class = " chunk_header";
2362 } elsif ($line =~ m/^\\/) {
2363 $diff_class = " incomplete";
2364 } elsif ($prefix =~ tr/+/+/) {
2365 $diff_class = " add";
2366 } elsif ($prefix =~ tr/-/-/) {
2367 $diff_class = " rem";
2369 } else {
2370 # assume ordinary diff
2371 my $char = substr($line, 0, 1);
2372 if ($char eq '+') {
2373 $diff_class = " add";
2374 } elsif ($char eq '-') {
2375 $diff_class = " rem";
2376 } elsif ($char eq '@') {
2377 $diff_class = " chunk_header";
2378 } elsif ($char eq "\\") {
2379 $diff_class = " incomplete";
2382 $line = untabify($line);
2383 if ($from && $to && $line =~ m/^\@{2} /) {
2384 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2385 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2387 $from_lines = 0 unless defined $from_lines;
2388 $to_lines = 0 unless defined $to_lines;
2390 if ($from->{'href'}) {
2391 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2392 -class=>"list"}, $from_text);
2394 if ($to->{'href'}) {
2395 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2396 -class=>"list"}, $to_text);
2398 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2399 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2400 return "<div class=\"diff$diff_class\">$line</div>\n";
2401 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2402 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2403 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2405 @from_text = split(' ', $ranges);
2406 for (my $i = 0; $i < @from_text; ++$i) {
2407 ($from_start[$i], $from_nlines[$i]) =
2408 (split(',', substr($from_text[$i], 1)), 0);
2411 $to_text = pop @from_text;
2412 $to_start = pop @from_start;
2413 $to_nlines = pop @from_nlines;
2415 $line = "<span class=\"chunk_info\">$prefix ";
2416 for (my $i = 0; $i < @from_text; ++$i) {
2417 if ($from->{'href'}[$i]) {
2418 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2419 -class=>"list"}, $from_text[$i]);
2420 } else {
2421 $line .= $from_text[$i];
2423 $line .= " ";
2425 if ($to->{'href'}) {
2426 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2427 -class=>"list"}, $to_text);
2428 } else {
2429 $line .= $to_text;
2431 $line .= " $prefix</span>" .
2432 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2433 return "<div class=\"diff$diff_class\">$line</div>\n";
2435 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2438 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2439 # linked. Pass the hash of the tree/commit to snapshot.
2440 sub format_snapshot_links {
2441 my ($hash) = @_;
2442 my $num_fmts = @snapshot_fmts;
2443 if ($num_fmts > 1) {
2444 # A parenthesized list of links bearing format names.
2445 # e.g. "snapshot (_tar.gz_ _zip_)"
2446 return "snapshot (" . join(' ', map
2447 $cgi->a({
2448 -href => href(
2449 action=>"snapshot",
2450 hash=>$hash,
2451 snapshot_format=>$_
2453 }, $known_snapshot_formats{$_}{'display'})
2454 , @snapshot_fmts) . ")";
2455 } elsif ($num_fmts == 1) {
2456 # A single "snapshot" link whose tooltip bears the format name.
2457 # i.e. "_snapshot_"
2458 my ($fmt) = @snapshot_fmts;
2459 return
2460 $cgi->a({
2461 -href => href(
2462 action=>"snapshot",
2463 hash=>$hash,
2464 snapshot_format=>$fmt
2466 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2467 }, "snapshot");
2468 } else { # $num_fmts == 0
2469 return undef;
2473 ## ......................................................................
2474 ## functions returning values to be passed, perhaps after some
2475 ## transformation, to other functions; e.g. returning arguments to href()
2477 # returns hash to be passed to href to generate gitweb URL
2478 # in -title key it returns description of link
2479 sub get_feed_info {
2480 my $format = shift || 'Atom';
2481 my %res = (action => lc($format));
2483 # feed links are possible only for project views
2484 return unless (defined $project);
2485 # some views should link to OPML, or to generic project feed,
2486 # or don't have specific feed yet (so they should use generic)
2487 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2489 my $branch;
2490 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2491 # from tag links; this also makes possible to detect branch links
2492 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2493 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2494 $branch = $1;
2496 # find log type for feed description (title)
2497 my $type = 'log';
2498 if (defined $file_name) {
2499 $type = "history of $file_name";
2500 $type .= "/" if ($action eq 'tree');
2501 $type .= " on '$branch'" if (defined $branch);
2502 } else {
2503 $type = "log of $branch" if (defined $branch);
2506 $res{-title} = $type;
2507 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2508 $res{'file_name'} = $file_name;
2510 return %res;
2513 ## ----------------------------------------------------------------------
2514 ## git utility subroutines, invoking git commands
2516 # returns path to the core git executable and the --git-dir parameter as list
2517 sub git_cmd {
2518 $number_of_git_cmds++;
2519 return $GIT, '--git-dir='.$git_dir;
2522 # quote the given arguments for passing them to the shell
2523 # quote_command("command", "arg 1", "arg with ' and ! characters")
2524 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2525 # Try to avoid using this function wherever possible.
2526 sub quote_command {
2527 return join(' ',
2528 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2531 # get HEAD ref of given project as hash
2532 sub git_get_head_hash {
2533 return git_get_full_hash(shift, 'HEAD');
2536 sub git_get_full_hash {
2537 return git_get_hash(@_);
2540 sub git_get_short_hash {
2541 return git_get_hash(@_, '--short=7');
2544 sub git_get_hash {
2545 my ($project, $hash, @options) = @_;
2546 my $o_git_dir = $git_dir;
2547 my $retval = undef;
2548 $git_dir = "$projectroot/$project";
2549 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2550 '--verify', '-q', @options, $hash) {
2551 $retval = <$fd>;
2552 chomp $retval if defined $retval;
2553 close $fd;
2555 if (defined $o_git_dir) {
2556 $git_dir = $o_git_dir;
2558 return $retval;
2561 # get type of given object
2562 sub git_get_type {
2563 my $hash = shift;
2565 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2566 my $type = <$fd>;
2567 close $fd or return;
2568 chomp $type;
2569 return $type;
2572 # repository configuration
2573 our $config_file = '';
2574 our %config;
2576 # store multiple values for single key as anonymous array reference
2577 # single values stored directly in the hash, not as [ <value> ]
2578 sub hash_set_multi {
2579 my ($hash, $key, $value) = @_;
2581 if (!exists $hash->{$key}) {
2582 $hash->{$key} = $value;
2583 } elsif (!ref $hash->{$key}) {
2584 $hash->{$key} = [ $hash->{$key}, $value ];
2585 } else {
2586 push @{$hash->{$key}}, $value;
2590 # return hash of git project configuration
2591 # optionally limited to some section, e.g. 'gitweb'
2592 sub git_parse_project_config {
2593 my $section_regexp = shift;
2594 my %config;
2596 local $/ = "\0";
2598 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2599 or return;
2601 while (my $keyval = <$fh>) {
2602 chomp $keyval;
2603 my ($key, $value) = split(/\n/, $keyval, 2);
2605 hash_set_multi(\%config, $key, $value)
2606 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2608 close $fh;
2610 return %config;
2613 # convert config value to boolean: 'true' or 'false'
2614 # no value, number > 0, 'true' and 'yes' values are true
2615 # rest of values are treated as false (never as error)
2616 sub config_to_bool {
2617 my $val = shift;
2619 return 1 if !defined $val; # section.key
2621 # strip leading and trailing whitespace
2622 $val =~ s/^\s+//;
2623 $val =~ s/\s+$//;
2625 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2626 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2629 # convert config value to simple decimal number
2630 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2631 # to be multiplied by 1024, 1048576, or 1073741824
2632 sub config_to_int {
2633 my $val = shift;
2635 # strip leading and trailing whitespace
2636 $val =~ s/^\s+//;
2637 $val =~ s/\s+$//;
2639 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2640 $unit = lc($unit);
2641 # unknown unit is treated as 1
2642 return $num * ($unit eq 'g' ? 1073741824 :
2643 $unit eq 'm' ? 1048576 :
2644 $unit eq 'k' ? 1024 : 1);
2646 return $val;
2649 # convert config value to array reference, if needed
2650 sub config_to_multi {
2651 my $val = shift;
2653 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2656 sub git_get_project_config {
2657 my ($key, $type) = @_;
2659 return unless defined $git_dir;
2661 # key sanity check
2662 return unless ($key);
2663 $key =~ s/^gitweb\.//;
2664 return if ($key =~ m/\W/);
2666 # type sanity check
2667 if (defined $type) {
2668 $type =~ s/^--//;
2669 $type = undef
2670 unless ($type eq 'bool' || $type eq 'int');
2673 # get config
2674 if (!defined $config_file ||
2675 $config_file ne "$git_dir/config") {
2676 %config = git_parse_project_config('gitweb');
2677 $config_file = "$git_dir/config";
2680 # check if config variable (key) exists
2681 return unless exists $config{"gitweb.$key"};
2683 # ensure given type
2684 if (!defined $type) {
2685 return $config{"gitweb.$key"};
2686 } elsif ($type eq 'bool') {
2687 # backward compatibility: 'git config --bool' returns true/false
2688 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2689 } elsif ($type eq 'int') {
2690 return config_to_int($config{"gitweb.$key"});
2692 return $config{"gitweb.$key"};
2695 # get hash of given path at given ref
2696 sub git_get_hash_by_path {
2697 my $base = shift;
2698 my $path = shift || return undef;
2699 my $type = shift;
2701 $path =~ s,/+$,,;
2703 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2704 or die_error(500, "Open git-ls-tree failed");
2705 my $line = <$fd>;
2706 close $fd or return undef;
2708 if (!defined $line) {
2709 # there is no tree or hash given by $path at $base
2710 return undef;
2713 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2714 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2715 if (defined $type && $type ne $2) {
2716 # type doesn't match
2717 return undef;
2719 return $3;
2722 # get path of entry with given hash at given tree-ish (ref)
2723 # used to get 'from' filename for combined diff (merge commit) for renames
2724 sub git_get_path_by_hash {
2725 my $base = shift || return;
2726 my $hash = shift || return;
2728 local $/ = "\0";
2730 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2731 or return undef;
2732 while (my $line = <$fd>) {
2733 chomp $line;
2735 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2736 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2737 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2738 close $fd;
2739 return $1;
2742 close $fd;
2743 return undef;
2746 ## ......................................................................
2747 ## git utility functions, directly accessing git repository
2749 sub git_get_project_description {
2750 my $path = shift;
2752 $git_dir = "$projectroot/$path";
2753 open my $fd, '<', "$git_dir/description"
2754 or return git_get_project_config('description');
2755 my $descr = <$fd>;
2756 close $fd;
2757 if (defined $descr) {
2758 chomp $descr;
2760 return $descr;
2763 sub git_get_project_ctags {
2764 my $path = shift;
2765 my $ctags = {};
2767 $git_dir = "$projectroot/$path";
2768 opendir my $dh, "$git_dir/ctags"
2769 or return $ctags;
2770 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2771 open my $ct, '<', $_ or next;
2772 my $val = <$ct>;
2773 chomp $val;
2774 close $ct;
2775 my $ctag = $_; $ctag =~ s#.*/##;
2776 $ctags->{$ctag} = $val;
2778 closedir $dh;
2779 $ctags;
2782 sub git_populate_project_tagcloud {
2783 my $ctags = shift;
2785 # First, merge different-cased tags; tags vote on casing
2786 my %ctags_lc;
2787 foreach (keys %$ctags) {
2788 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2789 if (not $ctags_lc{lc $_}->{topcount}
2790 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2791 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2792 $ctags_lc{lc $_}->{topname} = $_;
2796 my $cloud;
2797 if (eval { require HTML::TagCloud; 1; }) {
2798 $cloud = HTML::TagCloud->new;
2799 foreach (sort keys %ctags_lc) {
2800 # Pad the title with spaces so that the cloud looks
2801 # less crammed.
2802 my $title = $ctags_lc{$_}->{topname};
2803 $title =~ s/ /&nbsp;/g;
2804 $title =~ s/^/&nbsp;/g;
2805 $title =~ s/$/&nbsp;/g;
2806 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2808 } else {
2809 $cloud = \%ctags_lc;
2811 $cloud;
2814 sub git_show_project_tagcloud {
2815 my ($cloud, $count) = @_;
2816 print STDERR ref($cloud)."..\n";
2817 if (ref $cloud eq 'HTML::TagCloud') {
2818 return $cloud->html_and_css($count);
2819 } else {
2820 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2821 return '<p align="center">' . join (', ', map {
2822 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2823 } splice(@tags, 0, $count)) . '</p>';
2827 sub git_get_project_url_list {
2828 my $path = shift;
2830 $git_dir = "$projectroot/$path";
2831 open my $fd, '<', "$git_dir/cloneurl"
2832 or return wantarray ?
2833 @{ config_to_multi(git_get_project_config('url')) } :
2834 config_to_multi(git_get_project_config('url'));
2835 my @git_project_url_list = map { chomp; $_ } <$fd>;
2836 close $fd;
2838 return wantarray ? @git_project_url_list : \@git_project_url_list;
2841 sub git_get_projects_list {
2842 my ($filter) = @_;
2843 my @list;
2845 $filter ||= '';
2846 $filter =~ s/\.git$//;
2848 my $check_forks = gitweb_check_feature('forks');
2850 if (-d $projects_list) {
2851 # search in directory
2852 my $dir = $projects_list . ($filter ? "/$filter" : '');
2853 # remove the trailing "/"
2854 $dir =~ s!/+$!!;
2855 my $pfxlen = length("$dir");
2856 my $pfxdepth = ($dir =~ tr!/!!);
2858 File::Find::find({
2859 follow_fast => 1, # follow symbolic links
2860 follow_skip => 2, # ignore duplicates
2861 dangling_symlinks => 0, # ignore dangling symlinks, silently
2862 wanted => sub {
2863 # global variables
2864 our $project_maxdepth;
2865 our $projectroot;
2866 # skip project-list toplevel, if we get it.
2867 return if (m!^[/.]$!);
2868 # only directories can be git repositories
2869 return unless (-d $_);
2870 # don't traverse too deep (Find is super slow on os x)
2871 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2872 $File::Find::prune = 1;
2873 return;
2876 my $subdir = substr($File::Find::name, $pfxlen + 1);
2877 # we check related file in $projectroot
2878 my $path = ($filter ? "$filter/" : '') . $subdir;
2879 if (check_export_ok("$projectroot/$path")) {
2880 push @list, { path => $path };
2881 $File::Find::prune = 1;
2884 }, "$dir");
2886 } elsif (-f $projects_list) {
2887 # read from file(url-encoded):
2888 # 'git%2Fgit.git Linus+Torvalds'
2889 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2890 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2891 my %paths;
2892 open my $fd, '<', $projects_list or return;
2893 PROJECT:
2894 while (my $line = <$fd>) {
2895 chomp $line;
2896 my ($path, $owner) = split ' ', $line;
2897 $path = unescape($path);
2898 $owner = unescape($owner);
2899 if (!defined $path) {
2900 next;
2902 if ($filter ne '') {
2903 # looking for forks;
2904 my $pfx = substr($path, 0, length($filter));
2905 if ($pfx ne $filter) {
2906 next PROJECT;
2908 my $sfx = substr($path, length($filter));
2909 if ($sfx !~ /^\/.*\.git$/) {
2910 next PROJECT;
2912 } elsif ($check_forks) {
2913 PATH:
2914 foreach my $filter (keys %paths) {
2915 # looking for forks;
2916 my $pfx = substr($path, 0, length($filter));
2917 if ($pfx ne $filter) {
2918 next PATH;
2920 my $sfx = substr($path, length($filter));
2921 if ($sfx !~ /^\/.*\.git$/) {
2922 next PATH;
2924 # is a fork, don't include it in
2925 # the list
2926 next PROJECT;
2929 if (check_export_ok("$projectroot/$path")) {
2930 my $pr = {
2931 path => $path,
2932 owner => to_utf8($owner),
2934 push @list, $pr;
2935 (my $forks_path = $path) =~ s/\.git$//;
2936 $paths{$forks_path}++;
2939 close $fd;
2941 return @list;
2944 our $gitweb_project_owner = undef;
2945 sub git_get_project_list_from_file {
2947 return if (defined $gitweb_project_owner);
2949 $gitweb_project_owner = {};
2950 # read from file (url-encoded):
2951 # 'git%2Fgit.git Linus+Torvalds'
2952 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2953 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2954 if (-f $projects_list) {
2955 open(my $fd, '<', $projects_list);
2956 while (my $line = <$fd>) {
2957 chomp $line;
2958 my ($pr, $ow) = split ' ', $line;
2959 $pr = unescape($pr);
2960 $ow = unescape($ow);
2961 $gitweb_project_owner->{$pr} = to_utf8($ow);
2963 close $fd;
2967 sub git_get_project_owner {
2968 my $project = shift;
2969 my $owner;
2971 return undef unless $project;
2972 $git_dir = "$projectroot/$project";
2974 if (!defined $gitweb_project_owner) {
2975 git_get_project_list_from_file();
2978 if (exists $gitweb_project_owner->{$project}) {
2979 $owner = $gitweb_project_owner->{$project};
2981 if (!defined $owner){
2982 $owner = git_get_project_config('owner');
2984 if (!defined $owner) {
2985 $owner = get_file_owner("$git_dir");
2988 return $owner;
2991 sub git_get_last_activity {
2992 my ($path) = @_;
2993 my $fd;
2995 $git_dir = "$projectroot/$path";
2996 open($fd, "-|", git_cmd(), 'for-each-ref',
2997 '--format=%(committer)',
2998 '--sort=-committerdate',
2999 '--count=1',
3000 'refs/heads') or return;
3001 my $most_recent = <$fd>;
3002 close $fd or return;
3003 if (defined $most_recent &&
3004 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3005 my $timestamp = $1;
3006 my $age = time - $timestamp;
3007 return ($age, age_string($age));
3009 return (undef, undef);
3012 sub git_get_references {
3013 my $type = shift || "";
3014 my %refs;
3015 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3016 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3017 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3018 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3019 or return;
3021 while (my $line = <$fd>) {
3022 chomp $line;
3023 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3024 if (defined $refs{$1}) {
3025 push @{$refs{$1}}, $2;
3026 } else {
3027 $refs{$1} = [ $2 ];
3031 close $fd or return;
3032 return \%refs;
3035 sub git_get_rev_name_tags {
3036 my $hash = shift || return undef;
3038 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3039 or return;
3040 my $name_rev = <$fd>;
3041 close $fd;
3043 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3044 return $1;
3045 } else {
3046 # catches also '$hash undefined' output
3047 return undef;
3051 ## ----------------------------------------------------------------------
3052 ## parse to hash functions
3054 sub parse_date {
3055 my $epoch = shift;
3056 my $tz = shift || "-0000";
3058 my %date;
3059 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3060 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3061 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3062 $date{'hour'} = $hour;
3063 $date{'minute'} = $min;
3064 $date{'mday'} = $mday;
3065 $date{'day'} = $days[$wday];
3066 $date{'month'} = $months[$mon];
3067 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3068 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3069 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3070 $mday, $months[$mon], $hour ,$min;
3071 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3072 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3074 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
3075 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
3076 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3077 $date{'hour_local'} = $hour;
3078 $date{'minute_local'} = $min;
3079 $date{'tz_local'} = $tz;
3080 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3081 1900+$year, $mon+1, $mday,
3082 $hour, $min, $sec, $tz);
3083 return %date;
3086 sub parse_tag {
3087 my $tag_id = shift;
3088 my %tag;
3089 my @comment;
3091 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3092 $tag{'id'} = $tag_id;
3093 while (my $line = <$fd>) {
3094 chomp $line;
3095 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3096 $tag{'object'} = $1;
3097 } elsif ($line =~ m/^type (.+)$/) {
3098 $tag{'type'} = $1;
3099 } elsif ($line =~ m/^tag (.+)$/) {
3100 $tag{'name'} = $1;
3101 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3102 $tag{'author'} = $1;
3103 $tag{'author_epoch'} = $2;
3104 $tag{'author_tz'} = $3;
3105 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3106 $tag{'author_name'} = $1;
3107 $tag{'author_email'} = $2;
3108 } else {
3109 $tag{'author_name'} = $tag{'author'};
3111 } elsif ($line =~ m/--BEGIN/) {
3112 push @comment, $line;
3113 last;
3114 } elsif ($line eq "") {
3115 last;
3118 push @comment, <$fd>;
3119 $tag{'comment'} = \@comment;
3120 close $fd or return;
3121 if (!defined $tag{'name'}) {
3122 return
3124 return %tag
3127 sub parse_commit_text {
3128 my ($commit_text, $withparents) = @_;
3129 my @commit_lines = split '\n', $commit_text;
3130 my %co;
3132 pop @commit_lines; # Remove '\0'
3134 if (! @commit_lines) {
3135 return;
3138 my $header = shift @commit_lines;
3139 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3140 return;
3142 ($co{'id'}, my @parents) = split ' ', $header;
3143 while (my $line = shift @commit_lines) {
3144 last if $line eq "\n";
3145 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3146 $co{'tree'} = $1;
3147 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3148 push @parents, $1;
3149 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3150 $co{'author'} = to_utf8($1);
3151 $co{'author_epoch'} = $2;
3152 $co{'author_tz'} = $3;
3153 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3154 $co{'author_name'} = $1;
3155 $co{'author_email'} = $2;
3156 } else {
3157 $co{'author_name'} = $co{'author'};
3159 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3160 $co{'committer'} = to_utf8($1);
3161 $co{'committer_epoch'} = $2;
3162 $co{'committer_tz'} = $3;
3163 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3164 $co{'committer_name'} = $1;
3165 $co{'committer_email'} = $2;
3166 } else {
3167 $co{'committer_name'} = $co{'committer'};
3171 if (!defined $co{'tree'}) {
3172 return;
3174 $co{'parents'} = \@parents;
3175 $co{'parent'} = $parents[0];
3177 foreach my $title (@commit_lines) {
3178 $title =~ s/^ //;
3179 if ($title ne "") {
3180 $co{'title'} = chop_str($title, 80, 5);
3181 # remove leading stuff of merges to make the interesting part visible
3182 if (length($title) > 50) {
3183 $title =~ s/^Automatic //;
3184 $title =~ s/^merge (of|with) /Merge ... /i;
3185 if (length($title) > 50) {
3186 $title =~ s/(http|rsync):\/\///;
3188 if (length($title) > 50) {
3189 $title =~ s/(master|www|rsync)\.//;
3191 if (length($title) > 50) {
3192 $title =~ s/kernel.org:?//;
3194 if (length($title) > 50) {
3195 $title =~ s/\/pub\/scm//;
3198 $co{'title_short'} = chop_str($title, 50, 5);
3199 last;
3202 if (! defined $co{'title'} || $co{'title'} eq "") {
3203 $co{'title'} = $co{'title_short'} = '(no commit message)';
3205 # remove added spaces
3206 foreach my $line (@commit_lines) {
3207 $line =~ s/^ //;
3209 $co{'comment'} = \@commit_lines;
3211 my $age = time - $co{'committer_epoch'};
3212 $co{'age'} = $age;
3213 $co{'age_string'} = age_string($age);
3214 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3215 if ($age > 60*60*24*7*2) {
3216 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3217 $co{'age_string_age'} = $co{'age_string'};
3218 } else {
3219 $co{'age_string_date'} = $co{'age_string'};
3220 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3222 return %co;
3225 sub parse_commit {
3226 my ($commit_id) = @_;
3227 my %co;
3229 local $/ = "\0";
3231 open my $fd, "-|", git_cmd(), "rev-list",
3232 "--parents",
3233 "--header",
3234 "--max-count=1",
3235 $commit_id,
3236 "--",
3237 or die_error(500, "Open git-rev-list failed");
3238 %co = parse_commit_text(<$fd>, 1);
3239 close $fd;
3241 return %co;
3244 sub parse_commits {
3245 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3246 my @cos;
3248 $maxcount ||= 1;
3249 $skip ||= 0;
3251 local $/ = "\0";
3253 open my $fd, "-|", git_cmd(), "rev-list",
3254 "--header",
3255 @args,
3256 ("--max-count=" . $maxcount),
3257 ("--skip=" . $skip),
3258 @extra_options,
3259 $commit_id,
3260 "--",
3261 ($filename ? ($filename) : ())
3262 or die_error(500, "Open git-rev-list failed");
3263 while (my $line = <$fd>) {
3264 my %co = parse_commit_text($line);
3265 push @cos, \%co;
3267 close $fd;
3269 return wantarray ? @cos : \@cos;
3272 # parse line of git-diff-tree "raw" output
3273 sub parse_difftree_raw_line {
3274 my $line = shift;
3275 my %res;
3277 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3278 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3279 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3280 $res{'from_mode'} = $1;
3281 $res{'to_mode'} = $2;
3282 $res{'from_id'} = $3;
3283 $res{'to_id'} = $4;
3284 $res{'status'} = $5;
3285 $res{'similarity'} = $6;
3286 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3287 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3288 } else {
3289 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3292 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3293 # combined diff (for merge commit)
3294 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3295 $res{'nparents'} = length($1);
3296 $res{'from_mode'} = [ split(' ', $2) ];
3297 $res{'to_mode'} = pop @{$res{'from_mode'}};
3298 $res{'from_id'} = [ split(' ', $3) ];
3299 $res{'to_id'} = pop @{$res{'from_id'}};
3300 $res{'status'} = [ split('', $4) ];
3301 $res{'to_file'} = unquote($5);
3303 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3304 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3305 $res{'commit'} = $1;
3308 return wantarray ? %res : \%res;
3311 # wrapper: return parsed line of git-diff-tree "raw" output
3312 # (the argument might be raw line, or parsed info)
3313 sub parsed_difftree_line {
3314 my $line_or_ref = shift;
3316 if (ref($line_or_ref) eq "HASH") {
3317 # pre-parsed (or generated by hand)
3318 return $line_or_ref;
3319 } else {
3320 return parse_difftree_raw_line($line_or_ref);
3324 # parse line of git-ls-tree output
3325 sub parse_ls_tree_line {
3326 my $line = shift;
3327 my %opts = @_;
3328 my %res;
3330 if ($opts{'-l'}) {
3331 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3332 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3334 $res{'mode'} = $1;
3335 $res{'type'} = $2;
3336 $res{'hash'} = $3;
3337 $res{'size'} = $4;
3338 if ($opts{'-z'}) {
3339 $res{'name'} = $5;
3340 } else {
3341 $res{'name'} = unquote($5);
3343 } else {
3344 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3345 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3347 $res{'mode'} = $1;
3348 $res{'type'} = $2;
3349 $res{'hash'} = $3;
3350 if ($opts{'-z'}) {
3351 $res{'name'} = $4;
3352 } else {
3353 $res{'name'} = unquote($4);
3357 return wantarray ? %res : \%res;
3360 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3361 sub parse_from_to_diffinfo {
3362 my ($diffinfo, $from, $to, @parents) = @_;
3364 if ($diffinfo->{'nparents'}) {
3365 # combined diff
3366 $from->{'file'} = [];
3367 $from->{'href'} = [];
3368 fill_from_file_info($diffinfo, @parents)
3369 unless exists $diffinfo->{'from_file'};
3370 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3371 $from->{'file'}[$i] =
3372 defined $diffinfo->{'from_file'}[$i] ?
3373 $diffinfo->{'from_file'}[$i] :
3374 $diffinfo->{'to_file'};
3375 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3376 $from->{'href'}[$i] = href(action=>"blob",
3377 hash_base=>$parents[$i],
3378 hash=>$diffinfo->{'from_id'}[$i],
3379 file_name=>$from->{'file'}[$i]);
3380 } else {
3381 $from->{'href'}[$i] = undef;
3384 } else {
3385 # ordinary (not combined) diff
3386 $from->{'file'} = $diffinfo->{'from_file'};
3387 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3388 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3389 hash=>$diffinfo->{'from_id'},
3390 file_name=>$from->{'file'});
3391 } else {
3392 delete $from->{'href'};
3396 $to->{'file'} = $diffinfo->{'to_file'};
3397 if (!is_deleted($diffinfo)) { # file exists in result
3398 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3399 hash=>$diffinfo->{'to_id'},
3400 file_name=>$to->{'file'});
3401 } else {
3402 delete $to->{'href'};
3406 ## ......................................................................
3407 ## parse to array of hashes functions
3409 sub git_get_heads_list {
3410 my $limit = shift;
3411 my @headslist;
3413 open my $fd, '-|', git_cmd(), 'for-each-ref',
3414 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3415 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3416 'refs/heads'
3417 or return;
3418 while (my $line = <$fd>) {
3419 my %ref_item;
3421 chomp $line;
3422 my ($refinfo, $committerinfo) = split(/\0/, $line);
3423 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3424 my ($committer, $epoch, $tz) =
3425 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3426 $ref_item{'fullname'} = $name;
3427 $name =~ s!^refs/heads/!!;
3429 $ref_item{'name'} = $name;
3430 $ref_item{'id'} = $hash;
3431 $ref_item{'title'} = $title || '(no commit message)';
3432 $ref_item{'epoch'} = $epoch;
3433 if ($epoch) {
3434 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3435 } else {
3436 $ref_item{'age'} = "unknown";
3439 push @headslist, \%ref_item;
3441 close $fd;
3443 return wantarray ? @headslist : \@headslist;
3446 sub git_get_tags_list {
3447 my $limit = shift;
3448 my @tagslist;
3450 open my $fd, '-|', git_cmd(), 'for-each-ref',
3451 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3452 '--format=%(objectname) %(objecttype) %(refname) '.
3453 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3454 'refs/tags'
3455 or return;
3456 while (my $line = <$fd>) {
3457 my %ref_item;
3459 chomp $line;
3460 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3461 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3462 my ($creator, $epoch, $tz) =
3463 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3464 $ref_item{'fullname'} = $name;
3465 $name =~ s!^refs/tags/!!;
3467 $ref_item{'type'} = $type;
3468 $ref_item{'id'} = $id;
3469 $ref_item{'name'} = $name;
3470 if ($type eq "tag") {
3471 $ref_item{'subject'} = $title;
3472 $ref_item{'reftype'} = $reftype;
3473 $ref_item{'refid'} = $refid;
3474 } else {
3475 $ref_item{'reftype'} = $type;
3476 $ref_item{'refid'} = $id;
3479 if ($type eq "tag" || $type eq "commit") {
3480 $ref_item{'epoch'} = $epoch;
3481 if ($epoch) {
3482 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3483 } else {
3484 $ref_item{'age'} = "unknown";
3488 push @tagslist, \%ref_item;
3490 close $fd;
3492 return wantarray ? @tagslist : \@tagslist;
3495 ## ----------------------------------------------------------------------
3496 ## filesystem-related functions
3498 sub get_file_owner {
3499 my $path = shift;
3501 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3502 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3503 if (!defined $gcos) {
3504 return undef;
3506 my $owner = $gcos;
3507 $owner =~ s/[,;].*$//;
3508 return to_utf8($owner);
3511 # assume that file exists
3512 sub insert_file {
3513 my $filename = shift;
3515 open my $fd, '<', $filename;
3516 print map { to_utf8($_) } <$fd>;
3517 close $fd;
3520 ## ......................................................................
3521 ## mimetype related functions
3523 sub mimetype_guess_file {
3524 my $filename = shift;
3525 my $mimemap = shift;
3526 -r $mimemap or return undef;
3528 my %mimemap;
3529 open(my $mh, '<', $mimemap) or return undef;
3530 while (<$mh>) {
3531 next if m/^#/; # skip comments
3532 my ($mimetype, $exts) = split(/\t+/);
3533 if (defined $exts) {
3534 my @exts = split(/\s+/, $exts);
3535 foreach my $ext (@exts) {
3536 $mimemap{$ext} = $mimetype;
3540 close($mh);
3542 $filename =~ /\.([^.]*)$/;
3543 return $mimemap{$1};
3546 sub mimetype_guess {
3547 my $filename = shift;
3548 my $mime;
3549 $filename =~ /\./ or return undef;
3551 if ($mimetypes_file) {
3552 my $file = $mimetypes_file;
3553 if ($file !~ m!^/!) { # if it is relative path
3554 # it is relative to project
3555 $file = "$projectroot/$project/$file";
3557 $mime = mimetype_guess_file($filename, $file);
3559 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3560 return $mime;
3563 sub blob_mimetype {
3564 my $fd = shift;
3565 my $filename = shift;
3567 if ($filename) {
3568 my $mime = mimetype_guess($filename);
3569 $mime and return $mime;
3572 # just in case
3573 return $default_blob_plain_mimetype unless $fd;
3575 if (-T $fd) {
3576 return 'text/plain';
3577 } elsif (! $filename) {
3578 return 'application/octet-stream';
3579 } elsif ($filename =~ m/\.png$/i) {
3580 return 'image/png';
3581 } elsif ($filename =~ m/\.gif$/i) {
3582 return 'image/gif';
3583 } elsif ($filename =~ m/\.jpe?g$/i) {
3584 return 'image/jpeg';
3585 } else {
3586 return 'application/octet-stream';
3590 sub blob_contenttype {
3591 my ($fd, $file_name, $type) = @_;
3593 $type ||= blob_mimetype($fd, $file_name);
3594 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3595 $type .= "; charset=$default_text_plain_charset";
3598 return $type;
3601 # guess file syntax for syntax highlighting; return undef if no highlighting
3602 # the name of syntax can (in the future) depend on syntax highlighter used
3603 sub guess_file_syntax {
3604 my ($highlight, $mimetype, $file_name) = @_;
3605 return undef unless ($highlight && defined $file_name);
3606 my $basename = basename($file_name, '.in');
3607 return $highlight_basename{$basename}
3608 if exists $highlight_basename{$basename};
3610 $basename =~ /\.([^.]*)$/;
3611 my $ext = $1 or return undef;
3612 return $highlight_ext{$ext}
3613 if exists $highlight_ext{$ext};
3615 return undef;
3618 # run highlighter and return FD of its output,
3619 # or return original FD if no highlighting
3620 sub run_highlighter {
3621 my ($fd, $highlight, $syntax) = @_;
3622 return $fd unless ($highlight && defined $syntax);
3624 close $fd
3625 or die_error(404, "Reading blob failed");
3626 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3627 quote_command($highlight_bin).
3628 " --xhtml --fragment --syntax $syntax |"
3629 or die_error(500, "Couldn't open file or run syntax highlighter");
3630 return $fd;
3633 ## ======================================================================
3634 ## functions printing HTML: header, footer, error page
3636 sub get_page_title {
3637 my $title = to_utf8($site_name);
3639 return $title unless (defined $project);
3640 $title .= " - " . to_utf8($project);
3642 return $title unless (defined $action);
3643 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3645 return $title unless (defined $file_name);
3646 $title .= " - " . esc_path($file_name);
3647 if ($action eq "tree" && $file_name !~ m|/$|) {
3648 $title .= "/";
3651 return $title;
3654 # creates "Generating..." page when caching enabled and not in cache
3655 sub git_generating_data_html {
3656 my ($cache, $key, $lock_fh) = @_;
3658 # whitelist of actions that should get "Generating..." page
3659 if (!action_outputs_html($action) ||
3660 browser_is_robot()) {
3661 return;
3664 # Initial delay
3665 if ($generating_options{'startup_delay'} > 0) {
3666 eval {
3667 local $SIG{ALRM} = sub { die "alarm clock restart\n" }; # NB: \n required
3668 alarm $generating_options{'startup_delay'};
3669 flock($lock_fh, LOCK_SH); # blocking readers lock
3670 alarm 0;
3672 if ($@) {
3673 # propagate unexpected errors
3674 die $@ if $@ !~ /alarm clock restart/;
3675 } else {
3676 # we got response within 'startup_delay' timeout
3677 return;
3681 my $title = "[Generating...] " . get_page_title();
3682 # TODO: the following line of code duplicates the one
3683 # in git_header_html, and it should probably be refactored.
3684 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3686 # Use the trick that 'refresh' HTTP header equivalent (set via http-equiv)
3687 # with timeout of 0 seconds would redirect as soon as page is finished.
3688 # It assumes that browser would display partially received page.
3689 # This "Generating..." redirect page should not be cached (externally).
3690 my %no_cache = (
3691 # HTTP/1.0
3692 -Pragma => 'no-cache',
3693 # HTTP/1.1
3694 -Cache_Control => join(', ', qw(private no-cache no-store must-revalidate
3695 max-age=0 pre-check=0 post-check=0)),
3697 print STDOUT $cgi->header(-type => 'text/html', -charset => 'utf-8',
3698 -status=> '200 OK', -expires => 'now',
3699 %no_cache);
3700 print STDOUT <<"EOF";
3701 <?xml version="1.0" encoding="utf-8"?>
3702 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3703 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3704 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3705 <!-- git web interface version $version -->
3706 <!-- git core binaries version $git_version -->
3707 <head>
3708 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
3709 <meta http-equiv="refresh" content="0" />
3710 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version" />
3711 <meta name="robots" content="noindex, nofollow" />
3712 <title>$title</title>
3713 </head>
3714 <body>
3717 local $| = 1; # autoflush
3718 print STDOUT 'Generating...';
3720 my $total_time = 0;
3721 my $interval = $generating_options{'print_interval'} || 1;
3722 my $timeout = $generating_options{'timeout'};
3723 my $alarm_handler = sub {
3724 local $! = 1;
3725 print STDOUT '.';
3726 $total_time += $interval;
3727 if ($total_time > $timeout) {
3728 die "timeout\n";
3731 eval {
3732 local $SIG{ALRM} = $alarm_handler;
3733 Time::HiRes::alarm($interval, $interval);
3734 my $lock_acquired;
3735 do {
3736 # loop is needed here because SIGALRM (from 'alarm')
3737 # can interrupt process of acquiring lock
3738 $lock_acquired = flock($lock_fh, LOCK_SH); # blocking readers lock
3739 } until ($lock_acquired);
3740 alarm 0;
3742 # It doesn't really matter if we got lock, or timed-out
3743 # but we should re-throw unknown (unexpected) errors
3744 die $@ if ($@ and $@ !~ /timeout/);
3746 print STDOUT <<"EOF";
3748 </body>
3749 </html>
3752 # after refresh web browser would reload page and send new request
3753 goto DONE_GITWEB;
3754 #exit 0;
3755 #return;
3758 sub git_header_html {
3759 my $status = shift || "200 OK";
3760 my $expires = shift;
3761 my %opts = @_;
3763 my $title = get_page_title();
3764 my $content_type;
3765 # require explicit support from the UA if we are to send the page as
3766 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3767 # we have to do this because MSIE sometimes globs '*/*', pretending to
3768 # support xhtml+xml but choking when it gets what it asked for.
3769 # Disable content-type negotiation when caching (use mimetype good for all).
3770 if (!$caching_enabled &&
3771 defined $cgi->http('HTTP_ACCEPT') &&
3772 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3773 $cgi->Accept('application/xhtml+xml') != 0) {
3774 $content_type = 'application/xhtml+xml';
3775 } else {
3776 $content_type = 'text/html';
3778 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3779 -status=> $status, -expires => $expires)
3780 unless ($opts{'-no_http_header'});
3781 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3782 print <<EOF;
3783 <?xml version="1.0" encoding="utf-8"?>
3784 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3785 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3786 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3787 <!-- git core binaries version $git_version -->
3788 <head>
3789 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3790 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3791 <meta name="robots" content="index, nofollow"/>
3792 <title>$title</title>
3794 # the stylesheet, favicon etc urls won't work correctly with path_info
3795 # unless we set the appropriate base URL
3796 # if caching is enabled we can get it from cache for path_info when it
3797 # is generated without path_info
3798 if ($ENV{'PATH_INFO'} || $caching_enabled) {
3799 print "<base href=\"".esc_url($base_url)."\" />\n";
3801 # print out each stylesheet that exist, providing backwards capability
3802 # for those people who defined $stylesheet in a config file
3803 if (defined $stylesheet) {
3804 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3805 } else {
3806 foreach my $stylesheet (@stylesheets) {
3807 next unless $stylesheet;
3808 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3811 if (defined $project) {
3812 my %href_params = get_feed_info();
3813 if (!exists $href_params{'-title'}) {
3814 $href_params{'-title'} = 'log';
3817 foreach my $format qw(RSS Atom) {
3818 my $type = lc($format);
3819 my %link_attr = (
3820 '-rel' => 'alternate',
3821 '-title' => "$project - $href_params{'-title'} - $format feed",
3822 '-type' => "application/$type+xml"
3825 $href_params{'action'} = $type;
3826 $link_attr{'-href'} = href(%href_params);
3827 print "<link ".
3828 "rel=\"$link_attr{'-rel'}\" ".
3829 "title=\"$link_attr{'-title'}\" ".
3830 "href=\"$link_attr{'-href'}\" ".
3831 "type=\"$link_attr{'-type'}\" ".
3832 "/>\n";
3834 $href_params{'extra_options'} = '--no-merges';
3835 $link_attr{'-href'} = href(%href_params);
3836 $link_attr{'-title'} .= ' (no merges)';
3837 print "<link ".
3838 "rel=\"$link_attr{'-rel'}\" ".
3839 "title=\"$link_attr{'-title'}\" ".
3840 "href=\"$link_attr{'-href'}\" ".
3841 "type=\"$link_attr{'-type'}\" ".
3842 "/>\n";
3845 } else {
3846 printf('<link rel="alternate" title="%s projects list" '.
3847 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3848 $site_name, href(project=>undef, action=>"project_index"));
3849 printf('<link rel="alternate" title="%s projects feeds" '.
3850 'href="%s" type="text/x-opml" />'."\n",
3851 $site_name, href(project=>undef, action=>"opml"));
3853 if (defined $favicon) {
3854 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3857 print "</head>\n" .
3858 "<body>\n";
3860 if (defined $site_header && -f $site_header) {
3861 insert_file($site_header);
3864 print "<div class=\"page_header\">\n" .
3865 $cgi->a({-href => esc_url($logo_url),
3866 -title => $logo_label},
3867 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3868 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3869 if (defined $project) {
3870 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3871 if (defined $action) {
3872 print " / $action";
3874 print "\n";
3876 print "</div>\n";
3878 my $have_search = gitweb_check_feature('search');
3879 if (defined $project && $have_search) {
3880 if (!defined $searchtext) {
3881 $searchtext = "";
3883 my $search_hash;
3884 if (defined $hash_base) {
3885 $search_hash = $hash_base;
3886 } elsif (defined $hash) {
3887 $search_hash = $hash;
3888 } else {
3889 $search_hash = "HEAD";
3891 my $action = $my_uri;
3892 my $use_pathinfo = gitweb_check_feature('pathinfo');
3893 if ($use_pathinfo) {
3894 $action .= "/".esc_url($project);
3896 print $cgi->startform(-method => "get", -action => $action) .
3897 "<div class=\"search\">\n" .
3898 (!$use_pathinfo &&
3899 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3900 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3901 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3902 $cgi->popup_menu(-name => 'st', -default => 'commit',
3903 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3904 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3905 " search:\n",
3906 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3907 "<span title=\"Extended regular expression\">" .
3908 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3909 -checked => $search_use_regexp) .
3910 "</span>" .
3911 "</div>" .
3912 $cgi->end_form() . "\n";
3916 sub git_footer_html {
3917 my $feed_class = 'rss_logo';
3919 print "<div class=\"page_footer\">\n";
3920 if (defined $project) {
3921 my $descr = git_get_project_description($project);
3922 if (defined $descr) {
3923 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3926 my %href_params = get_feed_info();
3927 if (!%href_params) {
3928 $feed_class .= ' generic';
3930 $href_params{'-title'} ||= 'log';
3932 foreach my $format qw(RSS Atom) {
3933 $href_params{'action'} = lc($format);
3934 print $cgi->a({-href => href(%href_params),
3935 -title => "$href_params{'-title'} $format feed",
3936 -class => $feed_class}, $format)."\n";
3939 } else {
3940 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3941 -class => $feed_class}, "OPML") . " ";
3942 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3943 -class => $feed_class}, "TXT") . "\n";
3945 print "</div>\n"; # class="page_footer"
3947 # timing info doesn't make much sense with output (response) caching,
3948 # so when caching is enabled gitweb prints the time of page generation
3949 if ((defined $t0 || $caching_enabled) &&
3950 gitweb_check_feature('timed')) {
3951 print "<div id=\"generating_info\">\n";
3952 if ($caching_enabled) {
3953 print 'This page was generated at '.
3954 gmtime( time() )." GMT\n";
3955 } else {
3956 print 'This page took '.
3957 '<span id="generating_time" class="time_span">'.
3958 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3959 ' seconds </span>'.
3960 ' and '.
3961 '<span id="generating_cmd">'.
3962 $number_of_git_cmds.
3963 '</span> git commands '.
3964 " to generate.\n";
3966 print "</div>\n"; # class="page_footer"
3969 if (defined $site_footer && -f $site_footer) {
3970 insert_file($site_footer);
3973 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3974 if (!$caching_enabled &&
3975 defined $action && $action eq 'blame_incremental') {
3976 print qq!<script type="text/javascript">\n!.
3977 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3978 qq! "!. href() .qq!");\n!.
3979 qq!</script>\n!;
3980 } elsif (gitweb_check_feature('javascript-actions')) {
3981 print qq!<script type="text/javascript">\n!.
3982 qq!window.onload = fixLinks;\n!.
3983 qq!</script>\n!;
3986 print "</body>\n" .
3987 "</html>";
3990 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3991 # Example: die_error(404, 'Hash not found')
3992 # By convention, use the following status codes (as defined in RFC 2616):
3993 # 400: Invalid or missing CGI parameters, or
3994 # requested object exists but has wrong type.
3995 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3996 # this server or project.
3997 # 404: Requested object/revision/project doesn't exist.
3998 # 500: The server isn't configured properly, or
3999 # an internal error occurred (e.g. failed assertions caused by bugs), or
4000 # an unknown error occurred (e.g. the git binary died unexpectedly).
4001 # 503: The server is currently unavailable (because it is overloaded,
4002 # or down for maintenance). Generally, this is a temporary state.
4003 sub die_error {
4004 my $status = shift || 500;
4005 my $error = esc_html(shift) || "Internal Server Error";
4006 my $extra = shift;
4007 my %opts = @_;
4009 my %http_responses = (
4010 400 => '400 Bad Request',
4011 403 => '403 Forbidden',
4012 404 => '404 Not Found',
4013 500 => '500 Internal Server Error',
4014 503 => '503 Service Unavailable',
4017 # Do not cache error pages
4018 capture_stop($cache, $capture) if ($capture && $caching_enabled);
4020 git_header_html($http_responses{$status}, undef, %opts);
4021 print <<EOF;
4022 <div class="page_body">
4023 <br /><br />
4024 $status - $error
4025 <br />
4027 if (defined $extra) {
4028 print "<hr />\n" .
4029 "$extra\n";
4031 print "</div>\n";
4033 git_footer_html();
4034 goto DONE_GITWEB
4035 unless ($opts{'-error_handler'});
4038 ## ----------------------------------------------------------------------
4039 ## functions printing or outputting HTML: navigation
4041 sub git_print_page_nav {
4042 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4043 $extra = '' if !defined $extra; # pager or formats
4045 my @navs = qw(summary shortlog log commit commitdiff tree);
4046 if ($suppress) {
4047 @navs = grep { $_ ne $suppress } @navs;
4050 my %arg = map { $_ => {action=>$_} } @navs;
4051 if (defined $head) {
4052 for (qw(commit commitdiff)) {
4053 $arg{$_}{'hash'} = $head;
4055 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4056 for (qw(shortlog log)) {
4057 $arg{$_}{'hash'} = $head;
4062 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4063 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4065 my @actions = gitweb_get_feature('actions');
4066 my %repl = (
4067 '%' => '%',
4068 'n' => $project, # project name
4069 'f' => $git_dir, # project path within filesystem
4070 'h' => $treehead || '', # current hash ('h' parameter)
4071 'b' => $treebase || '', # hash base ('hb' parameter)
4073 while (@actions) {
4074 my ($label, $link, $pos) = splice(@actions,0,3);
4075 # insert
4076 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4077 # munch munch
4078 $link =~ s/%([%nfhb])/$repl{$1}/g;
4079 $arg{$label}{'_href'} = $link;
4082 print "<div class=\"page_nav\">\n" .
4083 (join " | ",
4084 map { $_ eq $current ?
4085 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4086 } @navs);
4087 print "<br/>\n$extra<br/>\n" .
4088 "</div>\n";
4091 sub format_paging_nav {
4092 my ($action, $page, $has_next_link) = @_;
4093 my $paging_nav;
4096 if ($page > 0) {
4097 $paging_nav .=
4098 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4099 " &sdot; " .
4100 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4101 -accesskey => "p", -title => "Alt-p"}, "prev");
4102 } else {
4103 $paging_nav .= "first &sdot; prev";
4106 if ($has_next_link) {
4107 $paging_nav .= " &sdot; " .
4108 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4109 -accesskey => "n", -title => "Alt-n"}, "next");
4110 } else {
4111 $paging_nav .= " &sdot; next";
4114 return $paging_nav;
4117 ## ......................................................................
4118 ## functions printing or outputting HTML: div
4120 sub git_print_header_div {
4121 my ($action, $title, $hash, $hash_base) = @_;
4122 my %args = ();
4124 $args{'action'} = $action;
4125 $args{'hash'} = $hash if $hash;
4126 $args{'hash_base'} = $hash_base if $hash_base;
4128 print "<div class=\"header\">\n" .
4129 $cgi->a({-href => href(%args), -class => "title"},
4130 $title ? $title : $action) .
4131 "\n</div>\n";
4134 sub print_local_time {
4135 print format_local_time(@_);
4138 sub format_local_time {
4139 my $localtime = '';
4140 my %date = @_;
4141 if ($date{'hour_local'} < 6) {
4142 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4143 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4144 } else {
4145 $localtime .= sprintf(" (%02d:%02d %s)",
4146 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4149 return $localtime;
4152 # Outputs the author name and date in long form
4153 sub git_print_authorship {
4154 my $co = shift;
4155 my %opts = @_;
4156 my $tag = $opts{-tag} || 'div';
4157 my $author = $co->{'author_name'};
4159 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4160 print "<$tag class=\"author_date\">" .
4161 format_search_author($author, "author", esc_html($author)) .
4162 " [$ad{'rfc2822'}";
4163 print_local_time(%ad) if ($opts{-localtime});
4164 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
4165 . "</$tag>\n";
4168 # Outputs table rows containing the full author or committer information,
4169 # in the format expected for 'commit' view (& similar).
4170 # Parameters are a commit hash reference, followed by the list of people
4171 # to output information for. If the list is empty it defaults to both
4172 # author and committer.
4173 sub git_print_authorship_rows {
4174 my $co = shift;
4175 # too bad we can't use @people = @_ || ('author', 'committer')
4176 my @people = @_;
4177 @people = ('author', 'committer') unless @people;
4178 foreach my $who (@people) {
4179 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4180 print "<tr><td>$who</td><td>" .
4181 format_search_author($co->{"${who}_name"}, $who,
4182 esc_html($co->{"${who}_name"})) . " " .
4183 format_search_author($co->{"${who}_email"}, $who,
4184 esc_html("<" . $co->{"${who}_email"} . ">")) .
4185 "</td><td rowspan=\"2\">" .
4186 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4187 "</td></tr>\n" .
4188 "<tr>" .
4189 "<td></td><td> $wd{'rfc2822'}";
4190 print_local_time(%wd);
4191 print "</td>" .
4192 "</tr>\n";
4196 sub git_print_page_path {
4197 my $name = shift;
4198 my $type = shift;
4199 my $hb = shift;
4202 print "<div class=\"page_path\">";
4203 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4204 -title => 'tree root'}, to_utf8("[$project]"));
4205 print " / ";
4206 if (defined $name) {
4207 my @dirname = split '/', $name;
4208 my $basename = pop @dirname;
4209 my $fullname = '';
4211 foreach my $dir (@dirname) {
4212 $fullname .= ($fullname ? '/' : '') . $dir;
4213 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4214 hash_base=>$hb),
4215 -title => $fullname}, esc_path($dir));
4216 print " / ";
4218 if (defined $type && $type eq 'blob') {
4219 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4220 hash_base=>$hb),
4221 -title => $name}, esc_path($basename));
4222 } elsif (defined $type && $type eq 'tree') {
4223 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4224 hash_base=>$hb),
4225 -title => $name}, esc_path($basename));
4226 print " / ";
4227 } else {
4228 print esc_path($basename);
4231 print "<br/></div>\n";
4234 sub git_print_log {
4235 my $log = shift;
4236 my %opts = @_;
4238 if ($opts{'-remove_title'}) {
4239 # remove title, i.e. first line of log
4240 shift @$log;
4242 # remove leading empty lines
4243 while (defined $log->[0] && $log->[0] eq "") {
4244 shift @$log;
4247 # print log
4248 my $signoff = 0;
4249 my $empty = 0;
4250 foreach my $line (@$log) {
4251 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4252 $signoff = 1;
4253 $empty = 0;
4254 if (! $opts{'-remove_signoff'}) {
4255 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4256 next;
4257 } else {
4258 # remove signoff lines
4259 next;
4261 } else {
4262 $signoff = 0;
4265 # print only one empty line
4266 # do not print empty line after signoff
4267 if ($line eq "") {
4268 next if ($empty || $signoff);
4269 $empty = 1;
4270 } else {
4271 $empty = 0;
4274 print format_log_line_html($line) . "<br/>\n";
4277 if ($opts{'-final_empty_line'}) {
4278 # end with single empty line
4279 print "<br/>\n" unless $empty;
4283 # return link target (what link points to)
4284 sub git_get_link_target {
4285 my $hash = shift;
4286 my $link_target;
4288 # read link
4289 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4290 or return;
4292 local $/ = undef;
4293 $link_target = <$fd>;
4295 close $fd
4296 or return;
4298 return $link_target;
4301 # given link target, and the directory (basedir) the link is in,
4302 # return target of link relative to top directory (top tree);
4303 # return undef if it is not possible (including absolute links).
4304 sub normalize_link_target {
4305 my ($link_target, $basedir) = @_;
4307 # absolute symlinks (beginning with '/') cannot be normalized
4308 return if (substr($link_target, 0, 1) eq '/');
4310 # normalize link target to path from top (root) tree (dir)
4311 my $path;
4312 if ($basedir) {
4313 $path = $basedir . '/' . $link_target;
4314 } else {
4315 # we are in top (root) tree (dir)
4316 $path = $link_target;
4319 # remove //, /./, and /../
4320 my @path_parts;
4321 foreach my $part (split('/', $path)) {
4322 # discard '.' and ''
4323 next if (!$part || $part eq '.');
4324 # handle '..'
4325 if ($part eq '..') {
4326 if (@path_parts) {
4327 pop @path_parts;
4328 } else {
4329 # link leads outside repository (outside top dir)
4330 return;
4332 } else {
4333 push @path_parts, $part;
4336 $path = join('/', @path_parts);
4338 return $path;
4341 # print tree entry (row of git_tree), but without encompassing <tr> element
4342 sub git_print_tree_entry {
4343 my ($t, $basedir, $hash_base, $have_blame) = @_;
4345 my %base_key = ();
4346 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4348 # The format of a table row is: mode list link. Where mode is
4349 # the mode of the entry, list is the name of the entry, an href,
4350 # and link is the action links of the entry.
4352 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4353 if (exists $t->{'size'}) {
4354 print "<td class=\"size\">$t->{'size'}</td>\n";
4356 if ($t->{'type'} eq "blob") {
4357 print "<td class=\"list\">" .
4358 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4359 file_name=>"$basedir$t->{'name'}", %base_key),
4360 -class => "list"}, esc_path($t->{'name'}));
4361 if (S_ISLNK(oct $t->{'mode'})) {
4362 my $link_target = git_get_link_target($t->{'hash'});
4363 if ($link_target) {
4364 my $norm_target = normalize_link_target($link_target, $basedir);
4365 if (defined $norm_target) {
4366 print " -> " .
4367 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4368 file_name=>$norm_target),
4369 -title => $norm_target}, esc_path($link_target));
4370 } else {
4371 print " -> " . esc_path($link_target);
4375 print "</td>\n";
4376 print "<td class=\"link\">";
4377 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4378 file_name=>"$basedir$t->{'name'}", %base_key)},
4379 "blob");
4380 if ($have_blame) {
4381 print " | " .
4382 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4383 file_name=>"$basedir$t->{'name'}", %base_key)},
4384 "blame");
4386 if (defined $hash_base) {
4387 print " | " .
4388 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4389 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4390 "history");
4392 print " | " .
4393 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4394 file_name=>"$basedir$t->{'name'}")},
4395 "raw");
4396 print "</td>\n";
4398 } elsif ($t->{'type'} eq "tree") {
4399 print "<td class=\"list\">";
4400 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4401 file_name=>"$basedir$t->{'name'}",
4402 %base_key)},
4403 esc_path($t->{'name'}));
4404 print "</td>\n";
4405 print "<td class=\"link\">";
4406 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4407 file_name=>"$basedir$t->{'name'}",
4408 %base_key)},
4409 "tree");
4410 if (defined $hash_base) {
4411 print " | " .
4412 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4413 file_name=>"$basedir$t->{'name'}")},
4414 "history");
4416 print "</td>\n";
4417 } else {
4418 # unknown object: we can only present history for it
4419 # (this includes 'commit' object, i.e. submodule support)
4420 print "<td class=\"list\">" .
4421 esc_path($t->{'name'}) .
4422 "</td>\n";
4423 print "<td class=\"link\">";
4424 if (defined $hash_base) {
4425 print $cgi->a({-href => href(action=>"history",
4426 hash_base=>$hash_base,
4427 file_name=>"$basedir$t->{'name'}")},
4428 "history");
4430 print "</td>\n";
4434 ## ......................................................................
4435 ## functions printing large fragments of HTML
4437 # get pre-image filenames for merge (combined) diff
4438 sub fill_from_file_info {
4439 my ($diff, @parents) = @_;
4441 $diff->{'from_file'} = [ ];
4442 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4443 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4444 if ($diff->{'status'}[$i] eq 'R' ||
4445 $diff->{'status'}[$i] eq 'C') {
4446 $diff->{'from_file'}[$i] =
4447 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4451 return $diff;
4454 # is current raw difftree line of file deletion
4455 sub is_deleted {
4456 my $diffinfo = shift;
4458 return $diffinfo->{'to_id'} eq ('0' x 40);
4461 # does patch correspond to [previous] difftree raw line
4462 # $diffinfo - hashref of parsed raw diff format
4463 # $patchinfo - hashref of parsed patch diff format
4464 # (the same keys as in $diffinfo)
4465 sub is_patch_split {
4466 my ($diffinfo, $patchinfo) = @_;
4468 return defined $diffinfo && defined $patchinfo
4469 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4473 sub git_difftree_body {
4474 my ($difftree, $hash, @parents) = @_;
4475 my ($parent) = $parents[0];
4476 my $have_blame = gitweb_check_feature('blame');
4477 print "<div class=\"list_head\">\n";
4478 if ($#{$difftree} > 10) {
4479 print(($#{$difftree} + 1) . " files changed:\n");
4481 print "</div>\n";
4483 print "<table class=\"" .
4484 (@parents > 1 ? "combined " : "") .
4485 "diff_tree\">\n";
4487 # header only for combined diff in 'commitdiff' view
4488 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4489 if ($has_header) {
4490 # table header
4491 print "<thead><tr>\n" .
4492 "<th></th><th></th>\n"; # filename, patchN link
4493 for (my $i = 0; $i < @parents; $i++) {
4494 my $par = $parents[$i];
4495 print "<th>" .
4496 $cgi->a({-href => href(action=>"commitdiff",
4497 hash=>$hash, hash_parent=>$par),
4498 -title => 'commitdiff to parent number ' .
4499 ($i+1) . ': ' . substr($par,0,7)},
4500 $i+1) .
4501 "&nbsp;</th>\n";
4503 print "</tr></thead>\n<tbody>\n";
4506 my $alternate = 1;
4507 my $patchno = 0;
4508 foreach my $line (@{$difftree}) {
4509 my $diff = parsed_difftree_line($line);
4511 if ($alternate) {
4512 print "<tr class=\"dark\">\n";
4513 } else {
4514 print "<tr class=\"light\">\n";
4516 $alternate ^= 1;
4518 if (exists $diff->{'nparents'}) { # combined diff
4520 fill_from_file_info($diff, @parents)
4521 unless exists $diff->{'from_file'};
4523 if (!is_deleted($diff)) {
4524 # file exists in the result (child) commit
4525 print "<td>" .
4526 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4527 file_name=>$diff->{'to_file'},
4528 hash_base=>$hash),
4529 -class => "list"}, esc_path($diff->{'to_file'})) .
4530 "</td>\n";
4531 } else {
4532 print "<td>" .
4533 esc_path($diff->{'to_file'}) .
4534 "</td>\n";
4537 if ($action eq 'commitdiff') {
4538 # link to patch
4539 $patchno++;
4540 print "<td class=\"link\">" .
4541 $cgi->a({-href => "#patch$patchno"}, "patch") .
4542 " | " .
4543 "</td>\n";
4546 my $has_history = 0;
4547 my $not_deleted = 0;
4548 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4549 my $hash_parent = $parents[$i];
4550 my $from_hash = $diff->{'from_id'}[$i];
4551 my $from_path = $diff->{'from_file'}[$i];
4552 my $status = $diff->{'status'}[$i];
4554 $has_history ||= ($status ne 'A');
4555 $not_deleted ||= ($status ne 'D');
4557 if ($status eq 'A') {
4558 print "<td class=\"link\" align=\"right\"> | </td>\n";
4559 } elsif ($status eq 'D') {
4560 print "<td class=\"link\">" .
4561 $cgi->a({-href => href(action=>"blob",
4562 hash_base=>$hash,
4563 hash=>$from_hash,
4564 file_name=>$from_path)},
4565 "blob" . ($i+1)) .
4566 " | </td>\n";
4567 } else {
4568 if ($diff->{'to_id'} eq $from_hash) {
4569 print "<td class=\"link nochange\">";
4570 } else {
4571 print "<td class=\"link\">";
4573 print $cgi->a({-href => href(action=>"blobdiff",
4574 hash=>$diff->{'to_id'},
4575 hash_parent=>$from_hash,
4576 hash_base=>$hash,
4577 hash_parent_base=>$hash_parent,
4578 file_name=>$diff->{'to_file'},
4579 file_parent=>$from_path)},
4580 "diff" . ($i+1)) .
4581 " | </td>\n";
4585 print "<td class=\"link\">";
4586 if ($not_deleted) {
4587 print $cgi->a({-href => href(action=>"blob",
4588 hash=>$diff->{'to_id'},
4589 file_name=>$diff->{'to_file'},
4590 hash_base=>$hash)},
4591 "blob");
4592 print " | " if ($has_history);
4594 if ($has_history) {
4595 print $cgi->a({-href => href(action=>"history",
4596 file_name=>$diff->{'to_file'},
4597 hash_base=>$hash)},
4598 "history");
4600 print "</td>\n";
4602 print "</tr>\n";
4603 next; # instead of 'else' clause, to avoid extra indent
4605 # else ordinary diff
4607 my ($to_mode_oct, $to_mode_str, $to_file_type);
4608 my ($from_mode_oct, $from_mode_str, $from_file_type);
4609 if ($diff->{'to_mode'} ne ('0' x 6)) {
4610 $to_mode_oct = oct $diff->{'to_mode'};
4611 if (S_ISREG($to_mode_oct)) { # only for regular file
4612 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4614 $to_file_type = file_type($diff->{'to_mode'});
4616 if ($diff->{'from_mode'} ne ('0' x 6)) {
4617 $from_mode_oct = oct $diff->{'from_mode'};
4618 if (S_ISREG($to_mode_oct)) { # only for regular file
4619 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4621 $from_file_type = file_type($diff->{'from_mode'});
4624 if ($diff->{'status'} eq "A") { # created
4625 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4626 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4627 $mode_chng .= "]</span>";
4628 print "<td>";
4629 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4630 hash_base=>$hash, file_name=>$diff->{'file'}),
4631 -class => "list"}, esc_path($diff->{'file'}));
4632 print "</td>\n";
4633 print "<td>$mode_chng</td>\n";
4634 print "<td class=\"link\">";
4635 if ($action eq 'commitdiff') {
4636 # link to patch
4637 $patchno++;
4638 print $cgi->a({-href => "#patch$patchno"}, "patch");
4639 print " | ";
4641 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4642 hash_base=>$hash, file_name=>$diff->{'file'})},
4643 "blob");
4644 print "</td>\n";
4646 } elsif ($diff->{'status'} eq "D") { # deleted
4647 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4648 print "<td>";
4649 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4650 hash_base=>$parent, file_name=>$diff->{'file'}),
4651 -class => "list"}, esc_path($diff->{'file'}));
4652 print "</td>\n";
4653 print "<td>$mode_chng</td>\n";
4654 print "<td class=\"link\">";
4655 if ($action eq 'commitdiff') {
4656 # link to patch
4657 $patchno++;
4658 print $cgi->a({-href => "#patch$patchno"}, "patch");
4659 print " | ";
4661 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4662 hash_base=>$parent, file_name=>$diff->{'file'})},
4663 "blob") . " | ";
4664 if ($have_blame) {
4665 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4666 file_name=>$diff->{'file'})},
4667 "blame") . " | ";
4669 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4670 file_name=>$diff->{'file'})},
4671 "history");
4672 print "</td>\n";
4674 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4675 my $mode_chnge = "";
4676 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4677 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4678 if ($from_file_type ne $to_file_type) {
4679 $mode_chnge .= " from $from_file_type to $to_file_type";
4681 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4682 if ($from_mode_str && $to_mode_str) {
4683 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4684 } elsif ($to_mode_str) {
4685 $mode_chnge .= " mode: $to_mode_str";
4688 $mode_chnge .= "]</span>\n";
4690 print "<td>";
4691 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4692 hash_base=>$hash, file_name=>$diff->{'file'}),
4693 -class => "list"}, esc_path($diff->{'file'}));
4694 print "</td>\n";
4695 print "<td>$mode_chnge</td>\n";
4696 print "<td class=\"link\">";
4697 if ($action eq 'commitdiff') {
4698 # link to patch
4699 $patchno++;
4700 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4701 " | ";
4702 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4703 # "commit" view and modified file (not onlu mode changed)
4704 print $cgi->a({-href => href(action=>"blobdiff",
4705 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4706 hash_base=>$hash, hash_parent_base=>$parent,
4707 file_name=>$diff->{'file'})},
4708 "diff") .
4709 " | ";
4711 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4712 hash_base=>$hash, file_name=>$diff->{'file'})},
4713 "blob") . " | ";
4714 if ($have_blame) {
4715 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4716 file_name=>$diff->{'file'})},
4717 "blame") . " | ";
4719 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4720 file_name=>$diff->{'file'})},
4721 "history");
4722 print "</td>\n";
4724 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4725 my %status_name = ('R' => 'moved', 'C' => 'copied');
4726 my $nstatus = $status_name{$diff->{'status'}};
4727 my $mode_chng = "";
4728 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4729 # mode also for directories, so we cannot use $to_mode_str
4730 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4732 print "<td>" .
4733 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4734 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4735 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4736 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4737 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4738 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4739 -class => "list"}, esc_path($diff->{'from_file'})) .
4740 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4741 "<td class=\"link\">";
4742 if ($action eq 'commitdiff') {
4743 # link to patch
4744 $patchno++;
4745 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4746 " | ";
4747 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4748 # "commit" view and modified file (not only pure rename or copy)
4749 print $cgi->a({-href => href(action=>"blobdiff",
4750 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4751 hash_base=>$hash, hash_parent_base=>$parent,
4752 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4753 "diff") .
4754 " | ";
4756 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4757 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4758 "blob") . " | ";
4759 if ($have_blame) {
4760 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4761 file_name=>$diff->{'to_file'})},
4762 "blame") . " | ";
4764 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4765 file_name=>$diff->{'to_file'})},
4766 "history");
4767 print "</td>\n";
4769 } # we should not encounter Unmerged (U) or Unknown (X) status
4770 print "</tr>\n";
4772 print "</tbody>" if $has_header;
4773 print "</table>\n";
4776 sub git_patchset_body {
4777 my ($fd, $difftree, $hash, @hash_parents) = @_;
4778 my ($hash_parent) = $hash_parents[0];
4780 my $is_combined = (@hash_parents > 1);
4781 my $patch_idx = 0;
4782 my $patch_number = 0;
4783 my $patch_line;
4784 my $diffinfo;
4785 my $to_name;
4786 my (%from, %to);
4788 print "<div class=\"patchset\">\n";
4790 # skip to first patch
4791 while ($patch_line = <$fd>) {
4792 chomp $patch_line;
4794 last if ($patch_line =~ m/^diff /);
4797 PATCH:
4798 while ($patch_line) {
4800 # parse "git diff" header line
4801 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4802 # $1 is from_name, which we do not use
4803 $to_name = unquote($2);
4804 $to_name =~ s!^b/!!;
4805 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4806 # $1 is 'cc' or 'combined', which we do not use
4807 $to_name = unquote($2);
4808 } else {
4809 $to_name = undef;
4812 # check if current patch belong to current raw line
4813 # and parse raw git-diff line if needed
4814 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4815 # this is continuation of a split patch
4816 print "<div class=\"patch cont\">\n";
4817 } else {
4818 # advance raw git-diff output if needed
4819 $patch_idx++ if defined $diffinfo;
4821 # read and prepare patch information
4822 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4824 # compact combined diff output can have some patches skipped
4825 # find which patch (using pathname of result) we are at now;
4826 if ($is_combined) {
4827 while ($to_name ne $diffinfo->{'to_file'}) {
4828 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4829 format_diff_cc_simplified($diffinfo, @hash_parents) .
4830 "</div>\n"; # class="patch"
4832 $patch_idx++;
4833 $patch_number++;
4835 last if $patch_idx > $#$difftree;
4836 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4840 # modifies %from, %to hashes
4841 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4843 # this is first patch for raw difftree line with $patch_idx index
4844 # we index @$difftree array from 0, but number patches from 1
4845 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4848 # git diff header
4849 #assert($patch_line =~ m/^diff /) if DEBUG;
4850 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4851 $patch_number++;
4852 # print "git diff" header
4853 print format_git_diff_header_line($patch_line, $diffinfo,
4854 \%from, \%to);
4856 # print extended diff header
4857 print "<div class=\"diff extended_header\">\n";
4858 EXTENDED_HEADER:
4859 while ($patch_line = <$fd>) {
4860 chomp $patch_line;
4862 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4864 print format_extended_diff_header_line($patch_line, $diffinfo,
4865 \%from, \%to);
4867 print "</div>\n"; # class="diff extended_header"
4869 # from-file/to-file diff header
4870 if (! $patch_line) {
4871 print "</div>\n"; # class="patch"
4872 last PATCH;
4874 next PATCH if ($patch_line =~ m/^diff /);
4875 #assert($patch_line =~ m/^---/) if DEBUG;
4877 my $last_patch_line = $patch_line;
4878 $patch_line = <$fd>;
4879 chomp $patch_line;
4880 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4882 print format_diff_from_to_header($last_patch_line, $patch_line,
4883 $diffinfo, \%from, \%to,
4884 @hash_parents);
4886 # the patch itself
4887 LINE:
4888 while ($patch_line = <$fd>) {
4889 chomp $patch_line;
4891 next PATCH if ($patch_line =~ m/^diff /);
4893 print format_diff_line($patch_line, \%from, \%to);
4896 } continue {
4897 print "</div>\n"; # class="patch"
4900 # for compact combined (--cc) format, with chunk and patch simplification
4901 # the patchset might be empty, but there might be unprocessed raw lines
4902 for (++$patch_idx if $patch_number > 0;
4903 $patch_idx < @$difftree;
4904 ++$patch_idx) {
4905 # read and prepare patch information
4906 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4908 # generate anchor for "patch" links in difftree / whatchanged part
4909 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4910 format_diff_cc_simplified($diffinfo, @hash_parents) .
4911 "</div>\n"; # class="patch"
4913 $patch_number++;
4916 if ($patch_number == 0) {
4917 if (@hash_parents > 1) {
4918 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4919 } else {
4920 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4924 print "</div>\n"; # class="patchset"
4927 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4929 # fills project list info (age, description, owner, forks) for each
4930 # project in the list, removing invalid projects from returned list
4931 # NOTE: modifies $projlist, but does not remove entries from it
4932 sub fill_project_list_info {
4933 my ($projlist, $check_forks) = @_;
4934 my @projects;
4936 my $show_ctags = gitweb_check_feature('ctags');
4937 PROJECT:
4938 foreach my $pr (@$projlist) {
4939 my (@activity) = git_get_last_activity($pr->{'path'});
4940 unless (@activity) {
4941 next PROJECT;
4943 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4944 if (!defined $pr->{'descr'}) {
4945 my $descr = git_get_project_description($pr->{'path'}) || "";
4946 $descr = to_utf8($descr);
4947 $pr->{'descr_long'} = $descr;
4948 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4950 if (!defined $pr->{'owner'}) {
4951 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4953 if ($check_forks) {
4954 my $pname = $pr->{'path'};
4955 if (($pname =~ s/\.git$//) &&
4956 ($pname !~ /\/$/) &&
4957 (-d "$projectroot/$pname")) {
4958 $pr->{'forks'} = "-d $projectroot/$pname";
4959 } else {
4960 $pr->{'forks'} = 0;
4963 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4964 push @projects, $pr;
4967 return @projects;
4970 # print 'sort by' <th> element, generating 'sort by $name' replay link
4971 # if that order is not selected
4972 sub print_sort_th {
4973 print format_sort_th(@_);
4976 sub format_sort_th {
4977 my ($name, $order, $header) = @_;
4978 my $sort_th = "";
4979 $header ||= ucfirst($name);
4981 if ($order eq $name) {
4982 $sort_th .= "<th>$header</th>\n";
4983 } else {
4984 $sort_th .= "<th>" .
4985 $cgi->a({-href => href(-replay=>1, order=>$name),
4986 -class => "header"}, $header) .
4987 "</th>\n";
4990 return $sort_th;
4993 sub git_project_list_body {
4994 # actually uses global variable $project
4995 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4997 my $check_forks = gitweb_check_feature('forks');
4998 my @projects = fill_project_list_info($projlist, $check_forks);
5000 $order ||= $default_projects_order;
5001 $from = 0 unless defined $from;
5002 $to = $#projects if (!defined $to || $#projects < $to);
5004 my %order_info = (
5005 project => { key => 'path', type => 'str' },
5006 descr => { key => 'descr_long', type => 'str' },
5007 owner => { key => 'owner', type => 'str' },
5008 age => { key => 'age', type => 'num' }
5010 my $oi = $order_info{$order};
5011 if ($oi->{'type'} eq 'str') {
5012 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
5013 } else {
5014 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
5017 my $show_ctags = gitweb_check_feature('ctags');
5018 if ($show_ctags) {
5019 my %ctags;
5020 foreach my $p (@projects) {
5021 foreach my $ct (keys %{$p->{'ctags'}}) {
5022 $ctags{$ct} += $p->{'ctags'}->{$ct};
5025 my $cloud = git_populate_project_tagcloud(\%ctags);
5026 print git_show_project_tagcloud($cloud, 64);
5029 print "<table class=\"project_list\">\n";
5030 unless ($no_header) {
5031 print "<tr>\n";
5032 if ($check_forks) {
5033 print "<th></th>\n";
5035 print_sort_th('project', $order, 'Project');
5036 print_sort_th('descr', $order, 'Description');
5037 print_sort_th('owner', $order, 'Owner');
5038 print_sort_th('age', $order, 'Last Change');
5039 print "<th></th>\n" . # for links
5040 "</tr>\n";
5042 my $alternate = 1;
5043 my $tagfilter = $cgi->param('by_tag');
5044 for (my $i = $from; $i <= $to; $i++) {
5045 my $pr = $projects[$i];
5047 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
5048 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
5049 and not $pr->{'descr_long'} =~ /$searchtext/;
5050 # Weed out forks or non-matching entries of search
5051 if ($check_forks) {
5052 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
5053 $forkbase="^$forkbase" if $forkbase;
5054 next if not $searchtext and not $tagfilter and $show_ctags
5055 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
5058 if ($alternate) {
5059 print "<tr class=\"dark\">\n";
5060 } else {
5061 print "<tr class=\"light\">\n";
5063 $alternate ^= 1;
5064 if ($check_forks) {
5065 print "<td>";
5066 if ($pr->{'forks'}) {
5067 print "<!-- $pr->{'forks'} -->\n";
5068 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
5070 print "</td>\n";
5072 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5073 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
5074 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5075 -class => "list", -title => $pr->{'descr_long'}},
5076 esc_html($pr->{'descr'})) . "</td>\n" .
5077 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5078 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5079 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
5080 "<td class=\"link\">" .
5081 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5082 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5083 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5084 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5085 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5086 "</td>\n" .
5087 "</tr>\n";
5089 if (defined $extra) {
5090 print "<tr>\n";
5091 if ($check_forks) {
5092 print "<td></td>\n";
5094 print "<td colspan=\"5\">$extra</td>\n" .
5095 "</tr>\n";
5097 print "</table>\n";
5100 sub git_log_body {
5101 # uses global variable $project
5102 my ($commitlist, $from, $to, $refs, $extra) = @_;
5104 $from = 0 unless defined $from;
5105 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5107 for (my $i = 0; $i <= $to; $i++) {
5108 my %co = %{$commitlist->[$i]};
5109 next if !%co;
5110 my $commit = $co{'id'};
5111 my $ref = format_ref_marker($refs, $commit);
5112 my %ad = parse_date($co{'author_epoch'});
5113 git_print_header_div('commit',
5114 "<span class=\"age\">$co{'age_string'}</span>" .
5115 esc_html($co{'title'}) . $ref,
5116 $commit);
5117 print "<div class=\"title_text\">\n" .
5118 "<div class=\"log_link\">\n" .
5119 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5120 " | " .
5121 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5122 " | " .
5123 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5124 "<br/>\n" .
5125 "</div>\n";
5126 git_print_authorship(\%co, -tag => 'span');
5127 print "<br/>\n</div>\n";
5129 print "<div class=\"log_body\">\n";
5130 git_print_log($co{'comment'}, -final_empty_line=> 1);
5131 print "</div>\n";
5133 if ($extra) {
5134 print "<div class=\"page_nav\">\n";
5135 print "$extra\n";
5136 print "</div>\n";
5140 sub git_shortlog_body {
5141 # uses global variable $project
5142 my ($commitlist, $from, $to, $refs, $extra) = @_;
5144 $from = 0 unless defined $from;
5145 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5147 print "<table class=\"shortlog\">\n";
5148 my $alternate = 1;
5149 for (my $i = $from; $i <= $to; $i++) {
5150 my %co = %{$commitlist->[$i]};
5151 my $commit = $co{'id'};
5152 my $ref = format_ref_marker($refs, $commit);
5153 if ($alternate) {
5154 print "<tr class=\"dark\">\n";
5155 } else {
5156 print "<tr class=\"light\">\n";
5158 $alternate ^= 1;
5159 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5160 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5161 format_author_html('td', \%co, 10) . "<td>";
5162 print format_subject_html($co{'title'}, $co{'title_short'},
5163 href(action=>"commit", hash=>$commit), $ref);
5164 print "</td>\n" .
5165 "<td class=\"link\">" .
5166 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5167 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5168 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5169 my $snapshot_links = format_snapshot_links($commit);
5170 if (defined $snapshot_links) {
5171 print " | " . $snapshot_links;
5173 print "</td>\n" .
5174 "</tr>\n";
5176 if (defined $extra) {
5177 print "<tr>\n" .
5178 "<td colspan=\"4\">$extra</td>\n" .
5179 "</tr>\n";
5181 print "</table>\n";
5184 sub git_history_body {
5185 # Warning: assumes constant type (blob or tree) during history
5186 my ($commitlist, $from, $to, $refs, $extra,
5187 $file_name, $file_hash, $ftype) = @_;
5189 $from = 0 unless defined $from;
5190 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5192 print "<table class=\"history\">\n";
5193 my $alternate = 1;
5194 for (my $i = $from; $i <= $to; $i++) {
5195 my %co = %{$commitlist->[$i]};
5196 if (!%co) {
5197 next;
5199 my $commit = $co{'id'};
5201 my $ref = format_ref_marker($refs, $commit);
5203 if ($alternate) {
5204 print "<tr class=\"dark\">\n";
5205 } else {
5206 print "<tr class=\"light\">\n";
5208 $alternate ^= 1;
5209 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5210 # shortlog: format_author_html('td', \%co, 10)
5211 format_author_html('td', \%co, 15, 3) . "<td>";
5212 # originally git_history used chop_str($co{'title'}, 50)
5213 print format_subject_html($co{'title'}, $co{'title_short'},
5214 href(action=>"commit", hash=>$commit), $ref);
5215 print "</td>\n" .
5216 "<td class=\"link\">" .
5217 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5218 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5220 if ($ftype eq 'blob') {
5221 my $blob_current = $file_hash;
5222 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5223 if (defined $blob_current && defined $blob_parent &&
5224 $blob_current ne $blob_parent) {
5225 print " | " .
5226 $cgi->a({-href => href(action=>"blobdiff",
5227 hash=>$blob_current, hash_parent=>$blob_parent,
5228 hash_base=>$hash_base, hash_parent_base=>$commit,
5229 file_name=>$file_name)},
5230 "diff to current");
5233 print "</td>\n" .
5234 "</tr>\n";
5236 if (defined $extra) {
5237 print "<tr>\n" .
5238 "<td colspan=\"4\">$extra</td>\n" .
5239 "</tr>\n";
5241 print "</table>\n";
5244 sub git_tags_body {
5245 # uses global variable $project
5246 my ($taglist, $from, $to, $extra) = @_;
5247 $from = 0 unless defined $from;
5248 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5250 print "<table class=\"tags\">\n";
5251 my $alternate = 1;
5252 for (my $i = $from; $i <= $to; $i++) {
5253 my $entry = $taglist->[$i];
5254 my %tag = %$entry;
5255 my $comment = $tag{'subject'};
5256 my $comment_short;
5257 if (defined $comment) {
5258 $comment_short = chop_str($comment, 30, 5);
5260 if ($alternate) {
5261 print "<tr class=\"dark\">\n";
5262 } else {
5263 print "<tr class=\"light\">\n";
5265 $alternate ^= 1;
5266 if (defined $tag{'age'}) {
5267 print "<td><i>$tag{'age'}</i></td>\n";
5268 } else {
5269 print "<td></td>\n";
5271 print "<td>" .
5272 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5273 -class => "list name"}, esc_html($tag{'name'})) .
5274 "</td>\n" .
5275 "<td>";
5276 if (defined $comment) {
5277 print format_subject_html($comment, $comment_short,
5278 href(action=>"tag", hash=>$tag{'id'}));
5280 print "</td>\n" .
5281 "<td class=\"selflink\">";
5282 if ($tag{'type'} eq "tag") {
5283 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5284 } else {
5285 print "&nbsp;";
5287 print "</td>\n" .
5288 "<td class=\"link\">" . " | " .
5289 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5290 if ($tag{'reftype'} eq "commit") {
5291 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5292 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5293 } elsif ($tag{'reftype'} eq "blob") {
5294 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5296 print "</td>\n" .
5297 "</tr>";
5299 if (defined $extra) {
5300 print "<tr>\n" .
5301 "<td colspan=\"5\">$extra</td>\n" .
5302 "</tr>\n";
5304 print "</table>\n";
5307 sub git_heads_body {
5308 # uses global variable $project
5309 my ($headlist, $head, $from, $to, $extra) = @_;
5310 $from = 0 unless defined $from;
5311 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5313 print "<table class=\"heads\">\n";
5314 my $alternate = 1;
5315 for (my $i = $from; $i <= $to; $i++) {
5316 my $entry = $headlist->[$i];
5317 my %ref = %$entry;
5318 my $curr = $ref{'id'} eq $head;
5319 if ($alternate) {
5320 print "<tr class=\"dark\">\n";
5321 } else {
5322 print "<tr class=\"light\">\n";
5324 $alternate ^= 1;
5325 print "<td><i>$ref{'age'}</i></td>\n" .
5326 ($curr ? "<td class=\"current_head\">" : "<td>") .
5327 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5328 -class => "list name"},esc_html($ref{'name'})) .
5329 "</td>\n" .
5330 "<td class=\"link\">" .
5331 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5332 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5333 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
5334 "</td>\n" .
5335 "</tr>";
5337 if (defined $extra) {
5338 print "<tr>\n" .
5339 "<td colspan=\"3\">$extra</td>\n" .
5340 "</tr>\n";
5342 print "</table>\n";
5345 sub git_search_grep_body {
5346 my ($commitlist, $from, $to, $extra) = @_;
5347 $from = 0 unless defined $from;
5348 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5350 print "<table class=\"commit_search\">\n";
5351 my $alternate = 1;
5352 for (my $i = $from; $i <= $to; $i++) {
5353 my %co = %{$commitlist->[$i]};
5354 if (!%co) {
5355 next;
5357 my $commit = $co{'id'};
5358 if ($alternate) {
5359 print "<tr class=\"dark\">\n";
5360 } else {
5361 print "<tr class=\"light\">\n";
5363 $alternate ^= 1;
5364 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5365 format_author_html('td', \%co, 15, 5) .
5366 "<td>" .
5367 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5368 -class => "list subject"},
5369 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5370 my $comment = $co{'comment'};
5371 foreach my $line (@$comment) {
5372 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5373 my ($lead, $match, $trail) = ($1, $2, $3);
5374 $match = chop_str($match, 70, 5, 'center');
5375 my $contextlen = int((80 - length($match))/2);
5376 $contextlen = 30 if ($contextlen > 30);
5377 $lead = chop_str($lead, $contextlen, 10, 'left');
5378 $trail = chop_str($trail, $contextlen, 10, 'right');
5380 $lead = esc_html($lead);
5381 $match = esc_html($match);
5382 $trail = esc_html($trail);
5384 print "$lead<span class=\"match\">$match</span>$trail<br />";
5387 print "</td>\n" .
5388 "<td class=\"link\">" .
5389 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5390 " | " .
5391 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5392 " | " .
5393 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5394 print "</td>\n" .
5395 "</tr>\n";
5397 if (defined $extra) {
5398 print "<tr>\n" .
5399 "<td colspan=\"3\">$extra</td>\n" .
5400 "</tr>\n";
5402 print "</table>\n";
5405 ## ======================================================================
5406 ## ======================================================================
5407 ## actions
5409 sub git_project_list {
5410 my $order = $input_params{'order'};
5411 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5412 die_error(400, "Unknown order parameter");
5415 my @list = git_get_projects_list();
5416 if (!@list) {
5417 die_error(404, "No projects found");
5420 git_header_html();
5421 if (defined $home_text && -f $home_text) {
5422 print "<div class=\"index_include\">\n";
5423 insert_file($home_text);
5424 print "</div>\n";
5426 print $cgi->startform(-method => "get") .
5427 "<p class=\"projsearch\">Search:\n" .
5428 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5429 "</p>" .
5430 $cgi->end_form() . "\n";
5431 git_project_list_body(\@list, $order);
5432 git_footer_html();
5435 sub git_forks {
5436 my $order = $input_params{'order'};
5437 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5438 die_error(400, "Unknown order parameter");
5441 my @list = git_get_projects_list($project);
5442 if (!@list) {
5443 die_error(404, "No forks found");
5446 git_header_html();
5447 git_print_page_nav('','');
5448 git_print_header_div('summary', "$project forks");
5449 git_project_list_body(\@list, $order);
5450 git_footer_html();
5453 sub git_project_index {
5454 my @projects = git_get_projects_list($project);
5456 print $cgi->header(
5457 -type => 'text/plain',
5458 -charset => 'utf-8',
5459 -content_disposition => 'inline; filename="index.aux"');
5461 foreach my $pr (@projects) {
5462 if (!exists $pr->{'owner'}) {
5463 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5466 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5467 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5468 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5469 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5470 $path =~ s/ /\+/g;
5471 $owner =~ s/ /\+/g;
5473 print "$path $owner\n";
5477 sub git_summary {
5478 my $descr = git_get_project_description($project) || "none";
5479 my %co = parse_commit("HEAD");
5480 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5481 my $head = $co{'id'};
5483 my $owner = git_get_project_owner($project);
5485 my $refs = git_get_references();
5486 # These get_*_list functions return one more to allow us to see if
5487 # there are more ...
5488 my @taglist = git_get_tags_list(16);
5489 my @headlist = git_get_heads_list(16);
5490 my @forklist;
5491 my $check_forks = gitweb_check_feature('forks');
5493 if ($check_forks) {
5494 @forklist = git_get_projects_list($project);
5497 git_header_html();
5498 git_print_page_nav('summary','', $head);
5500 print "<div class=\"title\">&nbsp;</div>\n";
5501 print "<table class=\"projects_list\">\n" .
5502 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5503 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5504 if (defined $cd{'rfc2822'}) {
5505 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5508 # use per project git URL list in $projectroot/$project/cloneurl
5509 # or make project git URL from git base URL and project name
5510 my $url_tag = "URL";
5511 my @url_list = git_get_project_url_list($project);
5512 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5513 foreach my $git_url (@url_list) {
5514 next unless $git_url;
5515 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5516 $url_tag = "";
5519 # Tag cloud
5520 my $show_ctags = gitweb_check_feature('ctags');
5521 if ($show_ctags) {
5522 my $ctags = git_get_project_ctags($project);
5523 my $cloud = git_populate_project_tagcloud($ctags);
5524 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5525 print "</td>\n<td>" unless %$ctags;
5526 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5527 print "</td>\n<td>" if %$ctags;
5528 print git_show_project_tagcloud($cloud, 48);
5529 print "</td></tr>";
5532 print "</table>\n";
5534 # If XSS prevention is on, we don't include README.html.
5535 # TODO: Allow a readme in some safe format.
5536 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5537 print "<div class=\"title\">readme</div>\n" .
5538 "<div class=\"readme\">\n";
5539 insert_file("$projectroot/$project/README.html");
5540 print "\n</div>\n"; # class="readme"
5543 # we need to request one more than 16 (0..15) to check if
5544 # those 16 are all
5545 my @commitlist = $head ? parse_commits($head, 17) : ();
5546 if (@commitlist) {
5547 git_print_header_div('shortlog');
5548 git_shortlog_body(\@commitlist, 0, 15, $refs,
5549 $#commitlist <= 15 ? undef :
5550 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5553 if (@taglist) {
5554 git_print_header_div('tags');
5555 git_tags_body(\@taglist, 0, 15,
5556 $#taglist <= 15 ? undef :
5557 $cgi->a({-href => href(action=>"tags")}, "..."));
5560 if (@headlist) {
5561 git_print_header_div('heads');
5562 git_heads_body(\@headlist, $head, 0, 15,
5563 $#headlist <= 15 ? undef :
5564 $cgi->a({-href => href(action=>"heads")}, "..."));
5567 if (@forklist) {
5568 git_print_header_div('forks');
5569 git_project_list_body(\@forklist, 'age', 0, 15,
5570 $#forklist <= 15 ? undef :
5571 $cgi->a({-href => href(action=>"forks")}, "..."),
5572 'no_header');
5575 git_footer_html();
5578 sub git_tag {
5579 my %tag = parse_tag($hash);
5581 if (! %tag) {
5582 die_error(404, "Unknown tag object");
5585 my $head = git_get_head_hash($project);
5586 git_header_html();
5587 git_print_page_nav('','', $head,undef,$head);
5588 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5589 print "<div class=\"title_text\">\n" .
5590 "<table class=\"object_header\">\n" .
5591 "<tr>\n" .
5592 "<td>object</td>\n" .
5593 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5594 $tag{'object'}) . "</td>\n" .
5595 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5596 $tag{'type'}) . "</td>\n" .
5597 "</tr>\n";
5598 if (defined($tag{'author'})) {
5599 git_print_authorship_rows(\%tag, 'author');
5601 print "</table>\n\n" .
5602 "</div>\n";
5603 print "<div class=\"page_body\">";
5604 my $comment = $tag{'comment'};
5605 foreach my $line (@$comment) {
5606 chomp $line;
5607 print esc_html($line, -nbsp=>1) . "<br/>\n";
5609 print "</div>\n";
5610 git_footer_html();
5613 sub git_blame_common {
5614 my $format = shift || 'porcelain';
5615 if ($format eq 'porcelain' && $cgi->param('js') &&
5616 !$caching_enabled) {
5617 $format = 'incremental';
5618 $action = 'blame_incremental'; # for page title etc
5621 # permissions
5622 gitweb_check_feature('blame')
5623 or die_error(403, "Blame view not allowed");
5625 # error checking
5626 die_error(400, "No file name given") unless $file_name;
5627 $hash_base ||= git_get_head_hash($project);
5628 die_error(404, "Couldn't find base commit") unless $hash_base;
5629 my %co = parse_commit($hash_base)
5630 or die_error(404, "Commit not found");
5631 my $ftype = "blob";
5632 if (!defined $hash) {
5633 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5634 or die_error(404, "Error looking up file");
5635 } else {
5636 $ftype = git_get_type($hash);
5637 if ($ftype !~ "blob") {
5638 die_error(400, "Object is not a blob");
5642 my $fd;
5643 if ($format eq 'incremental') {
5644 # get file contents (as base)
5645 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5646 or die_error(500, "Open git-cat-file failed");
5647 } elsif ($format eq 'data') {
5648 # run git-blame --incremental
5649 open $fd, "-|", git_cmd(), "blame", "--incremental",
5650 $hash_base, "--", $file_name
5651 or die_error(500, "Open git-blame --incremental failed");
5652 } else {
5653 # run git-blame --porcelain
5654 open $fd, "-|", git_cmd(), "blame", '-p',
5655 $hash_base, '--', $file_name
5656 or die_error(500, "Open git-blame --porcelain failed");
5659 # incremental blame data returns early
5660 if ($format eq 'data') {
5661 print $cgi->header(
5662 -type=>"text/plain", -charset => "utf-8",
5663 -status=> "200 OK");
5664 local $| = 1; # output autoflush
5665 print while <$fd>;
5666 close $fd
5667 or print "ERROR $!\n";
5669 print 'END';
5670 if (!$caching_enabled &&
5671 defined $t0 && gitweb_check_feature('timed')) {
5672 print ' '.
5673 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5674 ' '.$number_of_git_cmds;
5676 print "\n";
5678 return;
5681 # page header
5682 git_header_html();
5683 my $formats_nav =
5684 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5685 "blob") .
5686 " | ";
5687 if ($format eq 'incremental') {
5688 $formats_nav .=
5689 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5690 "blame") . " (non-incremental)";
5691 } elsif (!$caching_enabled) {
5692 $formats_nav .=
5693 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5694 "blame") . " (incremental)";
5696 $formats_nav .=
5697 " | " .
5698 $cgi->a({-href => href(action=>"history", -replay=>1)},
5699 "history") .
5700 " | " .
5701 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5702 "HEAD");
5703 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5704 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5705 git_print_page_path($file_name, $ftype, $hash_base);
5707 # page body
5708 if ($format eq 'incremental') {
5709 print "<noscript>\n<div class=\"error\"><center><b>\n".
5710 "This page requires JavaScript to run.\n Use ".
5711 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5712 'this page').
5713 " instead.\n".
5714 "</b></center></div>\n</noscript>\n";
5716 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5719 print qq!<div class="page_body">\n!;
5720 print qq!<div id="progress_info">... / ...</div>\n!
5721 if ($format eq 'incremental');
5722 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5723 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5724 qq!<thead>\n!.
5725 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5726 qq!</thead>\n!.
5727 qq!<tbody>\n!;
5729 my @rev_color = qw(light dark);
5730 my $num_colors = scalar(@rev_color);
5731 my $current_color = 0;
5733 if ($format eq 'incremental') {
5734 my $color_class = $rev_color[$current_color];
5736 #contents of a file
5737 my $linenr = 0;
5738 LINE:
5739 while (my $line = <$fd>) {
5740 chomp $line;
5741 $linenr++;
5743 print qq!<tr id="l$linenr" class="$color_class">!.
5744 qq!<td class="sha1"><a href=""> </a></td>!.
5745 qq!<td class="linenr">!.
5746 qq!<a class="linenr" href="">$linenr</a></td>!;
5747 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5748 print qq!</tr>\n!;
5751 } else { # porcelain, i.e. ordinary blame
5752 my %metainfo = (); # saves information about commits
5754 # blame data
5755 LINE:
5756 while (my $line = <$fd>) {
5757 chomp $line;
5758 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5759 # no <lines in group> for subsequent lines in group of lines
5760 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5761 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5762 if (!exists $metainfo{$full_rev}) {
5763 $metainfo{$full_rev} = { 'nprevious' => 0 };
5765 my $meta = $metainfo{$full_rev};
5766 my $data;
5767 while ($data = <$fd>) {
5768 chomp $data;
5769 last if ($data =~ s/^\t//); # contents of line
5770 if ($data =~ /^(\S+)(?: (.*))?$/) {
5771 $meta->{$1} = $2 unless exists $meta->{$1};
5773 if ($data =~ /^previous /) {
5774 $meta->{'nprevious'}++;
5777 my $short_rev = substr($full_rev, 0, 8);
5778 my $author = $meta->{'author'};
5779 my %date =
5780 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5781 my $date = $date{'iso-tz'};
5782 if ($group_size) {
5783 $current_color = ($current_color + 1) % $num_colors;
5785 my $tr_class = $rev_color[$current_color];
5786 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5787 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5788 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5789 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5790 if ($group_size) {
5791 print "<td class=\"sha1\"";
5792 print " title=\"". esc_html($author) . ", $date\"";
5793 print " rowspan=\"$group_size\"" if ($group_size > 1);
5794 print ">";
5795 print $cgi->a({-href => href(action=>"commit",
5796 hash=>$full_rev,
5797 file_name=>$file_name)},
5798 esc_html($short_rev));
5799 if ($group_size >= 2) {
5800 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5801 if (@author_initials) {
5802 print "<br />" .
5803 esc_html(join('', @author_initials));
5804 # or join('.', ...)
5807 print "</td>\n";
5809 # 'previous' <sha1 of parent commit> <filename at commit>
5810 if (exists $meta->{'previous'} &&
5811 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5812 $meta->{'parent'} = $1;
5813 $meta->{'file_parent'} = unquote($2);
5815 my $linenr_commit =
5816 exists($meta->{'parent'}) ?
5817 $meta->{'parent'} : $full_rev;
5818 my $linenr_filename =
5819 exists($meta->{'file_parent'}) ?
5820 $meta->{'file_parent'} : unquote($meta->{'filename'});
5821 my $blamed = href(action => 'blame',
5822 file_name => $linenr_filename,
5823 hash_base => $linenr_commit);
5824 print "<td class=\"linenr\">";
5825 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5826 -class => "linenr" },
5827 esc_html($lineno));
5828 print "</td>";
5829 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5830 print "</tr>\n";
5831 } # end while
5835 # footer
5836 print "</tbody>\n".
5837 "</table>\n"; # class="blame"
5838 print "</div>\n"; # class="blame_body"
5839 close $fd
5840 or print "Reading blob failed\n";
5842 git_footer_html();
5845 sub git_blame {
5846 git_blame_common();
5849 sub git_blame_incremental {
5850 git_blame_common(!$caching_enabled ? 'incremental' : undef);
5853 sub git_blame_data {
5854 git_blame_common('data');
5857 sub git_tags {
5858 my $head = git_get_head_hash($project);
5859 git_header_html();
5860 git_print_page_nav('','', $head,undef,$head);
5861 git_print_header_div('summary', $project);
5863 my @tagslist = git_get_tags_list();
5864 if (@tagslist) {
5865 git_tags_body(\@tagslist);
5867 git_footer_html();
5870 sub git_heads {
5871 my $head = git_get_head_hash($project);
5872 git_header_html();
5873 git_print_page_nav('','', $head,undef,$head);
5874 git_print_header_div('summary', $project);
5876 my @headslist = git_get_heads_list();
5877 if (@headslist) {
5878 git_heads_body(\@headslist, $head);
5880 git_footer_html();
5883 sub git_blob_plain {
5884 my $type = shift;
5885 my $expires;
5887 if (!defined $hash) {
5888 if (defined $file_name) {
5889 my $base = $hash_base || git_get_head_hash($project);
5890 $hash = git_get_hash_by_path($base, $file_name, "blob")
5891 or die_error(404, "Cannot find file");
5892 } else {
5893 die_error(400, "No file name defined");
5895 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5896 # blobs defined by non-textual hash id's can be cached
5897 $expires = "+1d";
5900 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5901 or die_error(500, "Open git-cat-file blob '$hash' failed");
5903 # content-type (can include charset)
5904 $type = blob_contenttype($fd, $file_name, $type);
5906 # "save as" filename, even when no $file_name is given
5907 my $save_as = "$hash";
5908 if (defined $file_name) {
5909 $save_as = $file_name;
5910 } elsif ($type =~ m/^text\//) {
5911 $save_as .= '.txt';
5914 # With XSS prevention on, blobs of all types except a few known safe
5915 # ones are served with "Content-Disposition: attachment" to make sure
5916 # they don't run in our security domain. For certain image types,
5917 # blob view writes an <img> tag referring to blob_plain view, and we
5918 # want to be sure not to break that by serving the image as an
5919 # attachment (though Firefox 3 doesn't seem to care).
5920 my $sandbox = $prevent_xss &&
5921 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5923 print $cgi->header(
5924 -type => $type,
5925 -expires => $expires,
5926 -content_disposition =>
5927 ($sandbox ? 'attachment' : 'inline')
5928 . '; filename="' . $save_as . '"');
5929 local $/ = undef;
5930 binmode STDOUT, ':raw';
5931 print <$fd>;
5932 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5933 close $fd;
5936 sub git_blob {
5937 my $expires;
5939 if (!defined $hash) {
5940 if (defined $file_name) {
5941 my $base = $hash_base || git_get_head_hash($project);
5942 $hash = git_get_hash_by_path($base, $file_name, "blob")
5943 or die_error(404, "Cannot find file");
5944 } else {
5945 die_error(400, "No file name defined");
5947 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5948 # blobs defined by non-textual hash id's can be cached
5949 $expires = "+1d";
5952 my $have_blame = gitweb_check_feature('blame');
5953 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5954 or die_error(500, "Couldn't cat $file_name, $hash");
5955 my $mimetype = blob_mimetype($fd, $file_name);
5956 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5957 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5958 close $fd;
5959 return git_blob_plain($mimetype);
5961 # we can have blame only for text/* mimetype
5962 $have_blame &&= ($mimetype =~ m!^text/!);
5964 my $highlight = gitweb_check_feature('highlight');
5965 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5966 $fd = run_highlighter($fd, $highlight, $syntax)
5967 if $syntax;
5969 git_header_html(undef, $expires);
5970 my $formats_nav = '';
5971 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5972 if (defined $file_name) {
5973 if ($have_blame) {
5974 $formats_nav .=
5975 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5976 "blame") .
5977 " | ";
5979 $formats_nav .=
5980 $cgi->a({-href => href(action=>"history", -replay=>1)},
5981 "history") .
5982 " | " .
5983 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5984 "raw") .
5985 " | " .
5986 $cgi->a({-href => href(action=>"blob",
5987 hash_base=>"HEAD", file_name=>$file_name)},
5988 "HEAD");
5989 } else {
5990 $formats_nav .=
5991 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5992 "raw");
5994 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5995 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5996 } else {
5997 print "<div class=\"page_nav\">\n" .
5998 "<br/><br/></div>\n" .
5999 "<div class=\"title\">$hash</div>\n";
6001 git_print_page_path($file_name, "blob", $hash_base);
6002 print "<div class=\"page_body\">\n";
6003 if ($mimetype =~ m!^image/!) {
6004 print qq!<img type="$mimetype"!;
6005 if ($file_name) {
6006 print qq! alt="$file_name" title="$file_name"!;
6008 print qq! src="! .
6009 href(action=>"blob_plain", hash=>$hash,
6010 hash_base=>$hash_base, file_name=>$file_name) .
6011 qq!" />\n!;
6012 } else {
6013 my $nr;
6014 while (my $line = <$fd>) {
6015 chomp $line;
6016 $nr++;
6017 $line = untabify($line);
6018 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
6019 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
6022 close $fd
6023 or print "Reading blob failed.\n";
6024 print "</div>";
6025 git_footer_html();
6028 sub git_tree {
6029 if (!defined $hash_base) {
6030 $hash_base = "HEAD";
6032 if (!defined $hash) {
6033 if (defined $file_name) {
6034 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
6035 } else {
6036 $hash = $hash_base;
6039 die_error(404, "No such tree") unless defined($hash);
6041 my $show_sizes = gitweb_check_feature('show-sizes');
6042 my $have_blame = gitweb_check_feature('blame');
6044 my @entries = ();
6046 local $/ = "\0";
6047 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
6048 ($show_sizes ? '-l' : ()), @extra_options, $hash
6049 or die_error(500, "Open git-ls-tree failed");
6050 @entries = map { chomp; $_ } <$fd>;
6051 close $fd
6052 or die_error(404, "Reading tree failed");
6055 my $refs = git_get_references();
6056 my $ref = format_ref_marker($refs, $hash_base);
6057 git_header_html();
6058 my $basedir = '';
6059 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6060 my @views_nav = ();
6061 if (defined $file_name) {
6062 push @views_nav,
6063 $cgi->a({-href => href(action=>"history", -replay=>1)},
6064 "history"),
6065 $cgi->a({-href => href(action=>"tree",
6066 hash_base=>"HEAD", file_name=>$file_name)},
6067 "HEAD"),
6069 my $snapshot_links = format_snapshot_links($hash);
6070 if (defined $snapshot_links) {
6071 # FIXME: Should be available when we have no hash base as well.
6072 push @views_nav, $snapshot_links;
6074 git_print_page_nav('tree','', $hash_base, undef, undef,
6075 join(' | ', @views_nav));
6076 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
6077 } else {
6078 undef $hash_base;
6079 print "<div class=\"page_nav\">\n";
6080 print "<br/><br/></div>\n";
6081 print "<div class=\"title\">$hash</div>\n";
6083 if (defined $file_name) {
6084 $basedir = $file_name;
6085 if ($basedir ne '' && substr($basedir, -1) ne '/') {
6086 $basedir .= '/';
6088 git_print_page_path($file_name, 'tree', $hash_base);
6090 print "<div class=\"page_body\">\n";
6091 print "<table class=\"tree\">\n";
6092 my $alternate = 1;
6093 # '..' (top directory) link if possible
6094 if (defined $hash_base &&
6095 defined $file_name && $file_name =~ m![^/]+$!) {
6096 if ($alternate) {
6097 print "<tr class=\"dark\">\n";
6098 } else {
6099 print "<tr class=\"light\">\n";
6101 $alternate ^= 1;
6103 my $up = $file_name;
6104 $up =~ s!/?[^/]+$!!;
6105 undef $up unless $up;
6106 # based on git_print_tree_entry
6107 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6108 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
6109 print '<td class="list">';
6110 print $cgi->a({-href => href(action=>"tree",
6111 hash_base=>$hash_base,
6112 file_name=>$up)},
6113 "..");
6114 print "</td>\n";
6115 print "<td class=\"link\"></td>\n";
6117 print "</tr>\n";
6119 foreach my $line (@entries) {
6120 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6122 if ($alternate) {
6123 print "<tr class=\"dark\">\n";
6124 } else {
6125 print "<tr class=\"light\">\n";
6127 $alternate ^= 1;
6129 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6131 print "</tr>\n";
6133 print "</table>\n" .
6134 "</div>";
6135 git_footer_html();
6138 sub snapshot_name {
6139 my ($project, $hash) = @_;
6141 # path/to/project.git -> project
6142 # path/to/project/.git -> project
6143 my $name = to_utf8($project);
6144 $name =~ s,([^/])/*\.git$,$1,;
6145 $name = basename($name);
6146 # sanitize name
6147 $name =~ s/[[:cntrl:]]/?/g;
6149 my $ver = $hash;
6150 if ($hash =~ /^[0-9a-fA-F]+$/) {
6151 # shorten SHA-1 hash
6152 my $full_hash = git_get_full_hash($project, $hash);
6153 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6154 $ver = git_get_short_hash($project, $hash);
6156 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6157 # tags don't need shortened SHA-1 hash
6158 $ver = $1;
6159 } else {
6160 # branches and other need shortened SHA-1 hash
6161 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6162 $ver = $1;
6164 $ver .= '-' . git_get_short_hash($project, $hash);
6166 # in case of hierarchical branch names
6167 $ver =~ s!/!.!g;
6169 # name = project-version_string
6170 $name = "$name-$ver";
6172 return wantarray ? ($name, $name) : $name;
6175 sub git_snapshot {
6176 my $format = $input_params{'snapshot_format'};
6177 if (!@snapshot_fmts) {
6178 die_error(403, "Snapshots not allowed");
6180 # default to first supported snapshot format
6181 $format ||= $snapshot_fmts[0];
6182 if ($format !~ m/^[a-z0-9]+$/) {
6183 die_error(400, "Invalid snapshot format parameter");
6184 } elsif (!exists($known_snapshot_formats{$format})) {
6185 die_error(400, "Unknown snapshot format");
6186 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6187 die_error(403, "Snapshot format not allowed");
6188 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6189 die_error(403, "Unsupported snapshot format");
6192 my $type = git_get_type("$hash^{}");
6193 if (!$type) {
6194 die_error(404, 'Object does not exist');
6195 } elsif ($type eq 'blob') {
6196 die_error(400, 'Object is not a tree-ish');
6199 my ($name, $prefix) = snapshot_name($project, $hash);
6200 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6201 my $cmd = quote_command(
6202 git_cmd(), 'archive',
6203 "--format=$known_snapshot_formats{$format}{'format'}",
6204 "--prefix=$prefix/", $hash);
6205 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6206 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6209 $filename =~ s/(["\\])/\\$1/g;
6210 print $cgi->header(
6211 -type => $known_snapshot_formats{$format}{'type'},
6212 -content_disposition => 'inline; filename="' . $filename . '"',
6213 -status => '200 OK');
6215 open my $fd, "-|", $cmd
6216 or die_error(500, "Execute git-archive failed");
6217 binmode STDOUT, ':raw';
6218 print <$fd>;
6219 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6220 close $fd;
6223 sub git_log_generic {
6224 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6226 my $head = git_get_head_hash($project);
6227 if (!defined $base) {
6228 $base = $head;
6230 if (!defined $page) {
6231 $page = 0;
6233 my $refs = git_get_references();
6235 my $commit_hash = $base;
6236 if (defined $parent) {
6237 $commit_hash = "$parent..$base";
6239 my @commitlist =
6240 parse_commits($commit_hash, 101, (100 * $page),
6241 defined $file_name ? ($file_name, "--full-history") : ());
6243 my $ftype;
6244 if (!defined $file_hash && defined $file_name) {
6245 # some commits could have deleted file in question,
6246 # and not have it in tree, but one of them has to have it
6247 for (my $i = 0; $i < @commitlist; $i++) {
6248 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6249 last if defined $file_hash;
6252 if (defined $file_hash) {
6253 $ftype = git_get_type($file_hash);
6255 if (defined $file_name && !defined $ftype) {
6256 die_error(500, "Unknown type of object");
6258 my %co;
6259 if (defined $file_name) {
6260 %co = parse_commit($base)
6261 or die_error(404, "Unknown commit object");
6265 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6266 my $next_link = '';
6267 if ($#commitlist >= 100) {
6268 $next_link =
6269 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6270 -accesskey => "n", -title => "Alt-n"}, "next");
6272 my $patch_max = gitweb_get_feature('patches');
6273 if ($patch_max && !defined $file_name) {
6274 if ($patch_max < 0 || @commitlist <= $patch_max) {
6275 $paging_nav .= " &sdot; " .
6276 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6277 "patches");
6281 git_header_html();
6282 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6283 if (defined $file_name) {
6284 git_print_header_div('commit', esc_html($co{'title'}), $base);
6285 } else {
6286 git_print_header_div('summary', $project)
6288 git_print_page_path($file_name, $ftype, $hash_base)
6289 if (defined $file_name);
6291 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6292 $file_name, $file_hash, $ftype);
6294 git_footer_html();
6297 sub git_log {
6298 git_log_generic('log', \&git_log_body,
6299 $hash, $hash_parent);
6302 sub git_commit {
6303 $hash ||= $hash_base || "HEAD";
6304 my %co = parse_commit($hash)
6305 or die_error(404, "Unknown commit object");
6307 my $parent = $co{'parent'};
6308 my $parents = $co{'parents'}; # listref
6310 # we need to prepare $formats_nav before any parameter munging
6311 my $formats_nav;
6312 if (!defined $parent) {
6313 # --root commitdiff
6314 $formats_nav .= '(initial)';
6315 } elsif (@$parents == 1) {
6316 # single parent commit
6317 $formats_nav .=
6318 '(parent: ' .
6319 $cgi->a({-href => href(action=>"commit",
6320 hash=>$parent)},
6321 esc_html(substr($parent, 0, 7))) .
6322 ')';
6323 } else {
6324 # merge commit
6325 $formats_nav .=
6326 '(merge: ' .
6327 join(' ', map {
6328 $cgi->a({-href => href(action=>"commit",
6329 hash=>$_)},
6330 esc_html(substr($_, 0, 7)));
6331 } @$parents ) .
6332 ')';
6334 if (gitweb_check_feature('patches') && @$parents <= 1) {
6335 $formats_nav .= " | " .
6336 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6337 "patch");
6340 if (!defined $parent) {
6341 $parent = "--root";
6343 my @difftree;
6344 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6345 @diff_opts,
6346 (@$parents <= 1 ? $parent : '-c'),
6347 $hash, "--"
6348 or die_error(500, "Open git-diff-tree failed");
6349 @difftree = map { chomp; $_ } <$fd>;
6350 close $fd or die_error(404, "Reading git-diff-tree failed");
6352 # non-textual hash id's can be cached
6353 my $expires;
6354 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6355 $expires = "+1d";
6357 my $refs = git_get_references();
6358 my $ref = format_ref_marker($refs, $co{'id'});
6360 git_header_html(undef, $expires);
6361 git_print_page_nav('commit', '',
6362 $hash, $co{'tree'}, $hash,
6363 $formats_nav);
6365 if (defined $co{'parent'}) {
6366 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6367 } else {
6368 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6370 print "<div class=\"title_text\">\n" .
6371 "<table class=\"object_header\">\n";
6372 git_print_authorship_rows(\%co);
6373 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6374 print "<tr>" .
6375 "<td>tree</td>" .
6376 "<td class=\"sha1\">" .
6377 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6378 class => "list"}, $co{'tree'}) .
6379 "</td>" .
6380 "<td class=\"link\">" .
6381 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6382 "tree");
6383 my $snapshot_links = format_snapshot_links($hash);
6384 if (defined $snapshot_links) {
6385 print " | " . $snapshot_links;
6387 print "</td>" .
6388 "</tr>\n";
6390 foreach my $par (@$parents) {
6391 print "<tr>" .
6392 "<td>parent</td>" .
6393 "<td class=\"sha1\">" .
6394 $cgi->a({-href => href(action=>"commit", hash=>$par),
6395 class => "list"}, $par) .
6396 "</td>" .
6397 "<td class=\"link\">" .
6398 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6399 " | " .
6400 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6401 "</td>" .
6402 "</tr>\n";
6404 print "</table>".
6405 "</div>\n";
6407 print "<div class=\"page_body\">\n";
6408 git_print_log($co{'comment'});
6409 print "</div>\n";
6411 git_difftree_body(\@difftree, $hash, @$parents);
6413 git_footer_html();
6416 sub git_object {
6417 # object is defined by:
6418 # - hash or hash_base alone
6419 # - hash_base and file_name
6420 my $type;
6422 # - hash or hash_base alone
6423 if ($hash || ($hash_base && !defined $file_name)) {
6424 my $object_id = $hash || $hash_base;
6426 open my $fd, "-|", quote_command(
6427 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6428 or die_error(404, "Object does not exist");
6429 $type = <$fd>;
6430 chomp $type;
6431 close $fd
6432 or die_error(404, "Object does not exist");
6434 # - hash_base and file_name
6435 } elsif ($hash_base && defined $file_name) {
6436 $file_name =~ s,/+$,,;
6438 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6439 or die_error(404, "Base object does not exist");
6441 # here errors should not hapen
6442 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6443 or die_error(500, "Open git-ls-tree failed");
6444 my $line = <$fd>;
6445 close $fd;
6447 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6448 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6449 die_error(404, "File or directory for given base does not exist");
6451 $type = $2;
6452 $hash = $3;
6453 } else {
6454 die_error(400, "Not enough information to find object");
6457 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6458 hash=>$hash, hash_base=>$hash_base,
6459 file_name=>$file_name),
6460 -status => '302 Found');
6463 sub git_blobdiff {
6464 my $format = shift || 'html';
6466 my $fd;
6467 my @difftree;
6468 my %diffinfo;
6469 my $expires;
6471 # preparing $fd and %diffinfo for git_patchset_body
6472 # new style URI
6473 if (defined $hash_base && defined $hash_parent_base) {
6474 if (defined $file_name) {
6475 # read raw output
6476 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6477 $hash_parent_base, $hash_base,
6478 "--", (defined $file_parent ? $file_parent : ()), $file_name
6479 or die_error(500, "Open git-diff-tree failed");
6480 @difftree = map { chomp; $_ } <$fd>;
6481 close $fd
6482 or die_error(404, "Reading git-diff-tree failed");
6483 @difftree
6484 or die_error(404, "Blob diff not found");
6486 } elsif (defined $hash &&
6487 $hash =~ /[0-9a-fA-F]{40}/) {
6488 # try to find filename from $hash
6490 # read filtered raw output
6491 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6492 $hash_parent_base, $hash_base, "--"
6493 or die_error(500, "Open git-diff-tree failed");
6494 @difftree =
6495 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6496 # $hash == to_id
6497 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6498 map { chomp; $_ } <$fd>;
6499 close $fd
6500 or die_error(404, "Reading git-diff-tree failed");
6501 @difftree
6502 or die_error(404, "Blob diff not found");
6504 } else {
6505 die_error(400, "Missing one of the blob diff parameters");
6508 if (@difftree > 1) {
6509 die_error(400, "Ambiguous blob diff specification");
6512 %diffinfo = parse_difftree_raw_line($difftree[0]);
6513 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6514 $file_name ||= $diffinfo{'to_file'};
6516 $hash_parent ||= $diffinfo{'from_id'};
6517 $hash ||= $diffinfo{'to_id'};
6519 # non-textual hash id's can be cached
6520 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6521 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6522 $expires = '+1d';
6525 # open patch output
6526 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6527 '-p', ($format eq 'html' ? "--full-index" : ()),
6528 $hash_parent_base, $hash_base,
6529 "--", (defined $file_parent ? $file_parent : ()), $file_name
6530 or die_error(500, "Open git-diff-tree failed");
6533 # old/legacy style URI -- not generated anymore since 1.4.3.
6534 if (!%diffinfo) {
6535 die_error('404 Not Found', "Missing one of the blob diff parameters")
6538 # header
6539 if ($format eq 'html') {
6540 my $formats_nav =
6541 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6542 "raw");
6543 git_header_html(undef, $expires);
6544 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6545 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6546 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6547 } else {
6548 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6549 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6551 if (defined $file_name) {
6552 git_print_page_path($file_name, "blob", $hash_base);
6553 } else {
6554 print "<div class=\"page_path\"></div>\n";
6557 } elsif ($format eq 'plain') {
6558 print $cgi->header(
6559 -type => 'text/plain',
6560 -charset => 'utf-8',
6561 -expires => $expires,
6562 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6564 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6566 } else {
6567 die_error(400, "Unknown blobdiff format");
6570 # patch
6571 if ($format eq 'html') {
6572 print "<div class=\"page_body\">\n";
6574 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6575 close $fd;
6577 print "</div>\n"; # class="page_body"
6578 git_footer_html();
6580 } else {
6581 while (my $line = <$fd>) {
6582 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6583 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6585 print $line;
6587 last if $line =~ m!^\+\+\+!;
6589 local $/ = undef;
6590 print <$fd>;
6591 close $fd;
6595 sub git_blobdiff_plain {
6596 git_blobdiff('plain');
6599 sub git_commitdiff {
6600 my %params = @_;
6601 my $format = $params{-format} || 'html';
6603 my ($patch_max) = gitweb_get_feature('patches');
6604 if ($format eq 'patch') {
6605 die_error(403, "Patch view not allowed") unless $patch_max;
6608 $hash ||= $hash_base || "HEAD";
6609 my %co = parse_commit($hash)
6610 or die_error(404, "Unknown commit object");
6612 # choose format for commitdiff for merge
6613 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6614 $hash_parent = '--cc';
6616 # we need to prepare $formats_nav before almost any parameter munging
6617 my $formats_nav;
6618 if ($format eq 'html') {
6619 $formats_nav =
6620 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6621 "raw");
6622 if ($patch_max && @{$co{'parents'}} <= 1) {
6623 $formats_nav .= " | " .
6624 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6625 "patch");
6628 if (defined $hash_parent &&
6629 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6630 # commitdiff with two commits given
6631 my $hash_parent_short = $hash_parent;
6632 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6633 $hash_parent_short = substr($hash_parent, 0, 7);
6635 $formats_nav .=
6636 ' (from';
6637 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6638 if ($co{'parents'}[$i] eq $hash_parent) {
6639 $formats_nav .= ' parent ' . ($i+1);
6640 last;
6643 $formats_nav .= ': ' .
6644 $cgi->a({-href => href(action=>"commitdiff",
6645 hash=>$hash_parent)},
6646 esc_html($hash_parent_short)) .
6647 ')';
6648 } elsif (!$co{'parent'}) {
6649 # --root commitdiff
6650 $formats_nav .= ' (initial)';
6651 } elsif (scalar @{$co{'parents'}} == 1) {
6652 # single parent commit
6653 $formats_nav .=
6654 ' (parent: ' .
6655 $cgi->a({-href => href(action=>"commitdiff",
6656 hash=>$co{'parent'})},
6657 esc_html(substr($co{'parent'}, 0, 7))) .
6658 ')';
6659 } else {
6660 # merge commit
6661 if ($hash_parent eq '--cc') {
6662 $formats_nav .= ' | ' .
6663 $cgi->a({-href => href(action=>"commitdiff",
6664 hash=>$hash, hash_parent=>'-c')},
6665 'combined');
6666 } else { # $hash_parent eq '-c'
6667 $formats_nav .= ' | ' .
6668 $cgi->a({-href => href(action=>"commitdiff",
6669 hash=>$hash, hash_parent=>'--cc')},
6670 'compact');
6672 $formats_nav .=
6673 ' (merge: ' .
6674 join(' ', map {
6675 $cgi->a({-href => href(action=>"commitdiff",
6676 hash=>$_)},
6677 esc_html(substr($_, 0, 7)));
6678 } @{$co{'parents'}} ) .
6679 ')';
6683 my $hash_parent_param = $hash_parent;
6684 if (!defined $hash_parent_param) {
6685 # --cc for multiple parents, --root for parentless
6686 $hash_parent_param =
6687 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6690 # read commitdiff
6691 my $fd;
6692 my @difftree;
6693 if ($format eq 'html') {
6694 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6695 "--no-commit-id", "--patch-with-raw", "--full-index",
6696 $hash_parent_param, $hash, "--"
6697 or die_error(500, "Open git-diff-tree failed");
6699 while (my $line = <$fd>) {
6700 chomp $line;
6701 # empty line ends raw part of diff-tree output
6702 last unless $line;
6703 push @difftree, scalar parse_difftree_raw_line($line);
6706 } elsif ($format eq 'plain') {
6707 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6708 '-p', $hash_parent_param, $hash, "--"
6709 or die_error(500, "Open git-diff-tree failed");
6710 } elsif ($format eq 'patch') {
6711 # For commit ranges, we limit the output to the number of
6712 # patches specified in the 'patches' feature.
6713 # For single commits, we limit the output to a single patch,
6714 # diverging from the git-format-patch default.
6715 my @commit_spec = ();
6716 if ($hash_parent) {
6717 if ($patch_max > 0) {
6718 push @commit_spec, "-$patch_max";
6720 push @commit_spec, '-n', "$hash_parent..$hash";
6721 } else {
6722 if ($params{-single}) {
6723 push @commit_spec, '-1';
6724 } else {
6725 if ($patch_max > 0) {
6726 push @commit_spec, "-$patch_max";
6728 push @commit_spec, "-n";
6730 push @commit_spec, '--root', $hash;
6732 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6733 '--encoding=utf8', '--stdout', @commit_spec
6734 or die_error(500, "Open git-format-patch failed");
6735 } else {
6736 die_error(400, "Unknown commitdiff format");
6739 # non-textual hash id's can be cached
6740 my $expires;
6741 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6742 $expires = "+1d";
6745 # write commit message
6746 if ($format eq 'html') {
6747 my $refs = git_get_references();
6748 my $ref = format_ref_marker($refs, $co{'id'});
6750 git_header_html(undef, $expires);
6751 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6752 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6753 print "<div class=\"title_text\">\n" .
6754 "<table class=\"object_header\">\n";
6755 git_print_authorship_rows(\%co);
6756 print "</table>".
6757 "</div>\n";
6758 print "<div class=\"page_body\">\n";
6759 if (@{$co{'comment'}} > 1) {
6760 print "<div class=\"log\">\n";
6761 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6762 print "</div>\n"; # class="log"
6765 } elsif ($format eq 'plain') {
6766 my $refs = git_get_references("tags");
6767 my $tagname = git_get_rev_name_tags($hash);
6768 my $filename = basename($project) . "-$hash.patch";
6770 print $cgi->header(
6771 -type => 'text/plain',
6772 -charset => 'utf-8',
6773 -expires => $expires,
6774 -content_disposition => 'inline; filename="' . "$filename" . '"');
6775 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6776 print "From: " . to_utf8($co{'author'}) . "\n";
6777 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6778 print "Subject: " . to_utf8($co{'title'}) . "\n";
6780 print "X-Git-Tag: $tagname\n" if $tagname;
6781 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6783 foreach my $line (@{$co{'comment'}}) {
6784 print to_utf8($line) . "\n";
6786 print "---\n\n";
6787 } elsif ($format eq 'patch') {
6788 my $filename = basename($project) . "-$hash.patch";
6790 print $cgi->header(
6791 -type => 'text/plain',
6792 -charset => 'utf-8',
6793 -expires => $expires,
6794 -content_disposition => 'inline; filename="' . "$filename" . '"');
6797 # write patch
6798 if ($format eq 'html') {
6799 my $use_parents = !defined $hash_parent ||
6800 $hash_parent eq '-c' || $hash_parent eq '--cc';
6801 git_difftree_body(\@difftree, $hash,
6802 $use_parents ? @{$co{'parents'}} : $hash_parent);
6803 print "<br/>\n";
6805 git_patchset_body($fd, \@difftree, $hash,
6806 $use_parents ? @{$co{'parents'}} : $hash_parent);
6807 close $fd;
6808 print "</div>\n"; # class="page_body"
6809 git_footer_html();
6811 } elsif ($format eq 'plain') {
6812 local $/ = undef;
6813 print <$fd>;
6814 close $fd
6815 or print "Reading git-diff-tree failed\n";
6816 } elsif ($format eq 'patch') {
6817 local $/ = undef;
6818 print <$fd>;
6819 close $fd
6820 or print "Reading git-format-patch failed\n";
6824 sub git_commitdiff_plain {
6825 git_commitdiff(-format => 'plain');
6828 # format-patch-style patches
6829 sub git_patch {
6830 git_commitdiff(-format => 'patch', -single => 1);
6833 sub git_patches {
6834 git_commitdiff(-format => 'patch');
6837 sub git_history {
6838 git_log_generic('history', \&git_history_body,
6839 $hash_base, $hash_parent_base,
6840 $file_name, $hash);
6843 sub git_search {
6844 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6845 if (!defined $searchtext) {
6846 die_error(400, "Text field is empty");
6848 if (!defined $hash) {
6849 $hash = git_get_head_hash($project);
6851 my %co = parse_commit($hash);
6852 if (!%co) {
6853 die_error(404, "Unknown commit object");
6855 if (!defined $page) {
6856 $page = 0;
6859 $searchtype ||= 'commit';
6860 if ($searchtype eq 'pickaxe') {
6861 # pickaxe may take all resources of your box and run for several minutes
6862 # with every query - so decide by yourself how public you make this feature
6863 gitweb_check_feature('pickaxe')
6864 or die_error(403, "Pickaxe is disabled");
6866 if ($searchtype eq 'grep') {
6867 gitweb_check_feature('grep')
6868 or die_error(403, "Grep is disabled");
6871 git_header_html();
6873 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6874 my $greptype;
6875 if ($searchtype eq 'commit') {
6876 $greptype = "--grep=";
6877 } elsif ($searchtype eq 'author') {
6878 $greptype = "--author=";
6879 } elsif ($searchtype eq 'committer') {
6880 $greptype = "--committer=";
6882 $greptype .= $searchtext;
6883 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6884 $greptype, '--regexp-ignore-case',
6885 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6887 my $paging_nav = '';
6888 if ($page > 0) {
6889 $paging_nav .=
6890 $cgi->a({-href => href(action=>"search", hash=>$hash,
6891 searchtext=>$searchtext,
6892 searchtype=>$searchtype)},
6893 "first");
6894 $paging_nav .= " &sdot; " .
6895 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6896 -accesskey => "p", -title => "Alt-p"}, "prev");
6897 } else {
6898 $paging_nav .= "first";
6899 $paging_nav .= " &sdot; prev";
6901 my $next_link = '';
6902 if ($#commitlist >= 100) {
6903 $next_link =
6904 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6905 -accesskey => "n", -title => "Alt-n"}, "next");
6906 $paging_nav .= " &sdot; $next_link";
6907 } else {
6908 $paging_nav .= " &sdot; next";
6911 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6912 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6913 if ($page == 0 && !@commitlist) {
6914 print "<p>No match.</p>\n";
6915 } else {
6916 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6920 if ($searchtype eq 'pickaxe') {
6921 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6922 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6924 print "<table class=\"pickaxe search\">\n";
6925 my $alternate = 1;
6926 local $/ = "\n";
6927 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6928 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6929 ($search_use_regexp ? '--pickaxe-regex' : ());
6930 undef %co;
6931 my @files;
6932 while (my $line = <$fd>) {
6933 chomp $line;
6934 next unless $line;
6936 my %set = parse_difftree_raw_line($line);
6937 if (defined $set{'commit'}) {
6938 # finish previous commit
6939 if (%co) {
6940 print "</td>\n" .
6941 "<td class=\"link\">" .
6942 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6943 " | " .
6944 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6945 print "</td>\n" .
6946 "</tr>\n";
6949 if ($alternate) {
6950 print "<tr class=\"dark\">\n";
6951 } else {
6952 print "<tr class=\"light\">\n";
6954 $alternate ^= 1;
6955 %co = parse_commit($set{'commit'});
6956 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6957 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6958 "<td><i>$author</i></td>\n" .
6959 "<td>" .
6960 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6961 -class => "list subject"},
6962 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6963 } elsif (defined $set{'to_id'}) {
6964 next if ($set{'to_id'} =~ m/^0{40}$/);
6966 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6967 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6968 -class => "list"},
6969 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6970 "<br/>\n";
6973 close $fd;
6975 # finish last commit (warning: repetition!)
6976 if (%co) {
6977 print "</td>\n" .
6978 "<td class=\"link\">" .
6979 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6980 " | " .
6981 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6982 print "</td>\n" .
6983 "</tr>\n";
6986 print "</table>\n";
6989 if ($searchtype eq 'grep') {
6990 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6991 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6993 print "<table class=\"grep_search\">\n";
6994 my $alternate = 1;
6995 my $matches = 0;
6996 local $/ = "\n";
6997 open my $fd, "-|", git_cmd(), 'grep', '-n',
6998 $search_use_regexp ? ('-E', '-i') : '-F',
6999 $searchtext, $co{'tree'};
7000 my $lastfile = '';
7001 while (my $line = <$fd>) {
7002 chomp $line;
7003 my ($file, $lno, $ltext, $binary);
7004 last if ($matches++ > 1000);
7005 if ($line =~ /^Binary file (.+) matches$/) {
7006 $file = $1;
7007 $binary = 1;
7008 } else {
7009 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
7011 if ($file ne $lastfile) {
7012 $lastfile and print "</td></tr>\n";
7013 if ($alternate++) {
7014 print "<tr class=\"dark\">\n";
7015 } else {
7016 print "<tr class=\"light\">\n";
7018 print "<td class=\"list\">".
7019 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
7020 file_name=>"$file"),
7021 -class => "list"}, esc_path($file));
7022 print "</td><td>\n";
7023 $lastfile = $file;
7025 if ($binary) {
7026 print "<div class=\"binary\">Binary file</div>\n";
7027 } else {
7028 $ltext = untabify($ltext);
7029 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
7030 $ltext = esc_html($1, -nbsp=>1);
7031 $ltext .= '<span class="match">';
7032 $ltext .= esc_html($2, -nbsp=>1);
7033 $ltext .= '</span>';
7034 $ltext .= esc_html($3, -nbsp=>1);
7035 } else {
7036 $ltext = esc_html($ltext, -nbsp=>1);
7038 print "<div class=\"pre\">" .
7039 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
7040 file_name=>"$file").'#l'.$lno,
7041 -class => "linenr"}, sprintf('%4i', $lno))
7042 . ' ' . $ltext . "</div>\n";
7045 if ($lastfile) {
7046 print "</td></tr>\n";
7047 if ($matches > 1000) {
7048 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
7050 } else {
7051 print "<div class=\"diff nodifferences\">No matches found</div>\n";
7053 close $fd;
7055 print "</table>\n";
7057 git_footer_html();
7060 sub git_search_help {
7061 git_header_html();
7062 git_print_page_nav('','', $hash,$hash,$hash);
7063 print <<EOT;
7064 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7065 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7066 the pattern entered is recognized as the POSIX extended
7067 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7068 insensitive).</p>
7069 <dl>
7070 <dt><b>commit</b></dt>
7071 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7073 my $have_grep = gitweb_check_feature('grep');
7074 if ($have_grep) {
7075 print <<EOT;
7076 <dt><b>grep</b></dt>
7077 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7078 a different one) are searched for the given pattern. On large trees, this search can take
7079 a while and put some strain on the server, so please use it with some consideration. Note that
7080 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7081 case-sensitive.</dd>
7084 print <<EOT;
7085 <dt><b>author</b></dt>
7086 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7087 <dt><b>committer</b></dt>
7088 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7090 my $have_pickaxe = gitweb_check_feature('pickaxe');
7091 if ($have_pickaxe) {
7092 print <<EOT;
7093 <dt><b>pickaxe</b></dt>
7094 <dd>All commits that caused the string to appear or disappear from any file (changes that
7095 added, removed or "modified" the string) will be listed. This search can take a while and
7096 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7097 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7100 print "</dl>\n";
7101 git_footer_html();
7104 sub git_shortlog {
7105 git_log_generic('shortlog', \&git_shortlog_body,
7106 $hash, $hash_parent);
7109 ## ......................................................................
7110 ## feeds (RSS, Atom; OPML)
7112 sub git_feed {
7113 my $format = shift || 'atom';
7114 my $have_blame = gitweb_check_feature('blame');
7116 # Atom: http://www.atomenabled.org/developers/syndication/
7117 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7118 if ($format ne 'rss' && $format ne 'atom') {
7119 die_error(400, "Unknown web feed format");
7122 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7123 my $head = $hash || 'HEAD';
7124 my @commitlist = parse_commits($head, 150, 0, $file_name);
7126 my %latest_commit;
7127 my %latest_date;
7128 my $content_type = "application/$format+xml";
7129 if (defined $cgi->http('HTTP_ACCEPT') &&
7130 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7131 # browser (feed reader) prefers text/xml
7132 $content_type = 'text/xml';
7134 if (defined($commitlist[0])) {
7135 %latest_commit = %{$commitlist[0]};
7136 my $latest_epoch = $latest_commit{'committer_epoch'};
7137 %latest_date = parse_date($latest_epoch);
7138 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7139 if (defined $if_modified) {
7140 my $since;
7141 if (eval { require HTTP::Date; 1; }) {
7142 $since = HTTP::Date::str2time($if_modified);
7143 } elsif (eval { require Time::ParseDate; 1; }) {
7144 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7146 if (defined $since && $latest_epoch <= $since) {
7147 print $cgi->header(
7148 -type => $content_type,
7149 -charset => 'utf-8',
7150 -last_modified => $latest_date{'rfc2822'},
7151 -status => '304 Not Modified');
7152 return;
7155 print $cgi->header(
7156 -type => $content_type,
7157 -charset => 'utf-8',
7158 -last_modified => $latest_date{'rfc2822'});
7159 } else {
7160 print $cgi->header(
7161 -type => $content_type,
7162 -charset => 'utf-8');
7165 # Optimization: skip generating the body if client asks only
7166 # for Last-Modified date.
7167 return if ($cgi->request_method() eq 'HEAD');
7169 # header variables
7170 my $title = "$site_name - $project/$action";
7171 my $feed_type = 'log';
7172 if (defined $hash) {
7173 $title .= " - '$hash'";
7174 $feed_type = 'branch log';
7175 if (defined $file_name) {
7176 $title .= " :: $file_name";
7177 $feed_type = 'history';
7179 } elsif (defined $file_name) {
7180 $title .= " - $file_name";
7181 $feed_type = 'history';
7183 $title .= " $feed_type";
7184 my $descr = git_get_project_description($project);
7185 if (defined $descr) {
7186 $descr = esc_html($descr);
7187 } else {
7188 $descr = "$project " .
7189 ($format eq 'rss' ? 'RSS' : 'Atom') .
7190 " feed";
7192 my $owner = git_get_project_owner($project);
7193 $owner = esc_html($owner);
7195 #header
7196 my $alt_url;
7197 if (defined $file_name) {
7198 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7199 } elsif (defined $hash) {
7200 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7201 } else {
7202 $alt_url = href(-full=>1, action=>"summary");
7204 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7205 if ($format eq 'rss') {
7206 print <<XML;
7207 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7208 <channel>
7210 print "<title>$title</title>\n" .
7211 "<link>$alt_url</link>\n" .
7212 "<description>$descr</description>\n" .
7213 "<language>en</language>\n" .
7214 # project owner is responsible for 'editorial' content
7215 "<managingEditor>$owner</managingEditor>\n";
7216 if (defined $logo || defined $favicon) {
7217 # prefer the logo to the favicon, since RSS
7218 # doesn't allow both
7219 my $img = esc_url($logo || $favicon);
7220 print "<image>\n" .
7221 "<url>$img</url>\n" .
7222 "<title>$title</title>\n" .
7223 "<link>$alt_url</link>\n" .
7224 "</image>\n";
7226 if (%latest_date) {
7227 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7228 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7230 print "<generator>gitweb v.$version/$git_version</generator>\n";
7231 } elsif ($format eq 'atom') {
7232 print <<XML;
7233 <feed xmlns="http://www.w3.org/2005/Atom">
7235 print "<title>$title</title>\n" .
7236 "<subtitle>$descr</subtitle>\n" .
7237 '<link rel="alternate" type="text/html" href="' .
7238 $alt_url . '" />' . "\n" .
7239 '<link rel="self" type="' . $content_type . '" href="' .
7240 $cgi->self_url() . '" />' . "\n" .
7241 "<id>" . href(-full=>1) . "</id>\n" .
7242 # use project owner for feed author
7243 "<author><name>$owner</name></author>\n";
7244 if (defined $favicon) {
7245 print "<icon>" . esc_url($favicon) . "</icon>\n";
7247 if (defined $logo_url) {
7248 # not twice as wide as tall: 72 x 27 pixels
7249 print "<logo>" . esc_url($logo) . "</logo>\n";
7251 if (! %latest_date) {
7252 # dummy date to keep the feed valid until commits trickle in:
7253 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7254 } else {
7255 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7257 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7260 # contents
7261 for (my $i = 0; $i <= $#commitlist; $i++) {
7262 my %co = %{$commitlist[$i]};
7263 my $commit = $co{'id'};
7264 # we read 150, we always show 30 and the ones more recent than 48 hours
7265 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7266 last;
7268 my %cd = parse_date($co{'author_epoch'});
7270 # get list of changed files
7271 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7272 $co{'parent'} || "--root",
7273 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7274 or next;
7275 my @difftree = map { chomp; $_ } <$fd>;
7276 close $fd
7277 or next;
7279 # print element (entry, item)
7280 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7281 if ($format eq 'rss') {
7282 print "<item>\n" .
7283 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7284 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7285 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7286 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7287 "<link>$co_url</link>\n" .
7288 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7289 "<content:encoded>" .
7290 "<![CDATA[\n";
7291 } elsif ($format eq 'atom') {
7292 print "<entry>\n" .
7293 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7294 "<updated>$cd{'iso-8601'}</updated>\n" .
7295 "<author>\n" .
7296 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7297 if ($co{'author_email'}) {
7298 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7300 print "</author>\n" .
7301 # use committer for contributor
7302 "<contributor>\n" .
7303 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7304 if ($co{'committer_email'}) {
7305 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7307 print "</contributor>\n" .
7308 "<published>$cd{'iso-8601'}</published>\n" .
7309 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7310 "<id>$co_url</id>\n" .
7311 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7312 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7314 my $comment = $co{'comment'};
7315 print "<pre>\n";
7316 foreach my $line (@$comment) {
7317 $line = esc_html($line);
7318 print "$line\n";
7320 print "</pre><ul>\n";
7321 foreach my $difftree_line (@difftree) {
7322 my %difftree = parse_difftree_raw_line($difftree_line);
7323 next if !$difftree{'from_id'};
7325 my $file = $difftree{'file'} || $difftree{'to_file'};
7327 print "<li>" .
7328 "[" .
7329 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7330 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7331 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7332 file_name=>$file, file_parent=>$difftree{'from_file'}),
7333 -title => "diff"}, 'D');
7334 if ($have_blame) {
7335 print $cgi->a({-href => href(-full=>1, action=>"blame",
7336 file_name=>$file, hash_base=>$commit),
7337 -title => "blame"}, 'B');
7339 # if this is not a feed of a file history
7340 if (!defined $file_name || $file_name ne $file) {
7341 print $cgi->a({-href => href(-full=>1, action=>"history",
7342 file_name=>$file, hash=>$commit),
7343 -title => "history"}, 'H');
7345 $file = esc_path($file);
7346 print "] ".
7347 "$file</li>\n";
7349 if ($format eq 'rss') {
7350 print "</ul>]]>\n" .
7351 "</content:encoded>\n" .
7352 "</item>\n";
7353 } elsif ($format eq 'atom') {
7354 print "</ul>\n</div>\n" .
7355 "</content>\n" .
7356 "</entry>\n";
7360 # end of feed
7361 if ($format eq 'rss') {
7362 print "</channel>\n</rss>\n";
7363 } elsif ($format eq 'atom') {
7364 print "</feed>\n";
7368 sub git_rss {
7369 git_feed('rss');
7372 sub git_atom {
7373 git_feed('atom');
7376 sub git_opml {
7377 my @list = git_get_projects_list();
7379 print $cgi->header(
7380 -type => 'text/xml',
7381 -charset => 'utf-8',
7382 -content_disposition => 'inline; filename="opml.xml"');
7384 print <<XML;
7385 <?xml version="1.0" encoding="utf-8"?>
7386 <opml version="1.0">
7387 <head>
7388 <title>$site_name OPML Export</title>
7389 </head>
7390 <body>
7391 <outline text="git RSS feeds">
7394 foreach my $pr (@list) {
7395 my %proj = %$pr;
7396 my $head = git_get_head_hash($proj{'path'});
7397 if (!defined $head) {
7398 next;
7400 $git_dir = "$projectroot/$proj{'path'}";
7401 my %co = parse_commit($head);
7402 if (!%co) {
7403 next;
7406 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7407 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7408 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7409 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7411 print <<XML;
7412 </outline>
7413 </body>
7414 </opml>