gitweb: Wrap die_error to use as error handler for caching engine
[git/jnareb-git.git] / gitweb / gitweb.perl
blob89a394320a2d4df1fe40fc53489d2de059adbddb
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;
287 # You define site-wide cache options defaults here; override them with
288 # $GITWEB_CONFIG as necessary.
289 our %cache_options = (
290 # The location in the filesystem that will hold the root of the cache.
291 # This directory will be created as needed (if possible) on the first
292 # cache set. Note that either this directory must exists and web server
293 # has to have write permissions to it, or web server must be able to
294 # create this directory.
295 # Possible values:
296 # * 'cache' (relative to gitweb),
297 # * File::Spec->catdir(File::Spec->tmpdir(), 'gitweb-cache'),
298 # * '/var/cache/gitweb' (FHS compliant, requires being set up),
299 'cache_root' => 'cache',
301 # The number of subdirectories deep to cache object item. This should be
302 # large enough that no cache directory has more than a few hundred
303 # objects. Each non-leaf directory contains up to 256 subdirectories
304 # (00-ff). Must be larger than 0.
305 'cache_depth' => 1,
307 # The (global) minimum expiration time for objects placed in the cache,
308 # in seconds. If the dynamic adaptive cache exporation time is lower
309 # than this number, we set cache timeout to this minimum.
310 'expires_min' => 20, # 20 seconds
312 # The (global) maximum expiration time for dynamic (adaptive) caching
313 # algorithm, in seconds. If the adaptive cache lifetime exceeds this
314 # number, we set cache timeout to this maximum.
315 # (If 'expires_min' >= 'expires_max', there is no adaptive cache timeout,
316 # and 'expires_min' is used as expiration time for objects in cache.)
317 'expires_max' => 1200, # 20 minutes
319 # Cache lifetime will be increased by applying this factor to the result
320 # from 'check_load' callback (see below).
321 'expires_factor' => 60, # expire time in seconds for 1.0 (100% CPU) load
323 # User supplied callback for deciding the cache policy, usually system
324 # load. Multiplied by 'expires_factor' gives adaptive expiration time,
325 # in seconds, subject to the limits imposed by 'expires_min' and
326 # 'expires_max' bounds. Set to undef (or delete) to turn off dynamic
327 # lifetime control.
328 # (Compatibile with Cache::Adaptive.)
329 'check_load' => \&get_loadavg,
331 # Maximum cache file life, in seconds. If cache entry lifetime exceeds
332 # this value, it wouldn't be served as being too stale when waiting for
333 # cache to be regenerated/refreshed, instead of trying to display
334 # existing cache date.
335 # Set it to -1 to always serve existing data if it exists,
336 # set it to 0 to turn off serving stale data - always wait.
337 'max_lifetime' => 5*60*60, # 5 hours
339 # This enables/disables background caching. If it is set to true value,
340 # caching engine would return stale data (if it is not older than
341 # 'max_lifetime' seconds) if it exists, and launch process if regenerating
342 # (refreshing) cache into the background. If it is set to false value,
343 # the process that fills cache must always wait for data to be generated.
344 # In theory this will make gitweb seem more responsive at the price of
345 # serving possibly stale data.
346 'background_cache' => 1,
348 # Subroutine which would be called when gitweb has to wait for data to
349 # be generated (it can't serve stale data because there isn't any,
350 # or if it exists it is older than 'max_lifetime'). The default
351 # is to use git_generating_data_html(), which creates "Generating..."
352 # page, which would then redirect or redraw/rewrite the page when
353 # data is ready.
354 # Set it to `undef' to disable this feature.
356 # Such subroutine (if invoked from GitwebCache::SimpleFileCache)
357 # is passed the following parameters: $cache instance, human-readable
358 # $key to current page, and filehandle $lock_fh to lockfile.
359 'generating_info' => \&git_generating_data_html,
361 # This enables/disables using 'generating_info' subroutine by process
362 # generating data, when not too stale data is not available (data is then
363 # generated in background). Because git_generating_data_html() includes
364 # initial delay (of 1 second by default), and we can assume that die_error
365 # finishes within this time, then generating error pages should be safe
366 # from infinite "Generating page..." loop.
367 'generating_info_is_safe' => 1,
369 # How to handle runtime errors occurring during cache gets and cache
370 # sets. Options are:
371 # * "die" (the default) - call die() with an appropriate message
372 # * "warn" - call warn() with an appropriate message
373 # * "ignore" - do nothing
374 # * <coderef> - call this code reference with an appropriate message
375 # Note that gitweb catches 'die <message>' via custom handle_errors_html
376 # handler, set via set_message() from CGI::Carp. 'warn <message>' are
377 # written to web server logs.
379 # The default is to use cache_error_handler, which wraps die_error.
380 # Only first argument passed to cache_error_handler is used (c.f. CHI)
381 'on_error' => \&cache_error_handler,
383 # You define site-wide options for "Generating..." page (if enabled) here
384 # (which means that $cache_options{'generating_info'} is set to coderef);
385 # override them with $GITWEB_CONFIG as necessary.
386 our %generating_options = (
387 # The delay before displaying "Generating..." page, in seconds. It is
388 # intended for "Generating..." page to be shown only when really needed.
389 'startup_delay' => 1,
390 # The time between generating new piece of output to prevent from
391 # redirection before data is ready, i.e. time between printing each
392 # dot in activity indicator / progress info, in seconds.
393 'print_interval' => 2,
394 # Maximum time "Generating..." page would be present, waiting for data,
395 # before unconditional redirect, in seconds.
396 'timeout' => $cache_options{'expires_min'},
398 # Set to _initialized_ instance of GitwebCache::Capture compatibile capturing
399 # engine, i.e. one implementing ->new() constructor, and ->capture($code)
400 # method. If unset (default), the GitwebCache::Capture::Simple would be used.
401 our $capture;
403 # You define site-wide feature defaults here; override them with
404 # $GITWEB_CONFIG as necessary.
405 our %feature = (
406 # feature => {
407 # 'sub' => feature-sub (subroutine),
408 # 'override' => allow-override (boolean),
409 # 'default' => [ default options...] (array reference)}
411 # if feature is overridable (it means that allow-override has true value),
412 # then feature-sub will be called with default options as parameters;
413 # return value of feature-sub indicates if to enable specified feature
415 # if there is no 'sub' key (no feature-sub), then feature cannot be
416 # overridden
418 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
419 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
420 # is enabled
422 # Enable the 'blame' blob view, showing the last commit that modified
423 # each line in the file. This can be very CPU-intensive.
425 # To enable system wide have in $GITWEB_CONFIG
426 # $feature{'blame'}{'default'} = [1];
427 # To have project specific config enable override in $GITWEB_CONFIG
428 # $feature{'blame'}{'override'} = 1;
429 # and in project config gitweb.blame = 0|1;
430 'blame' => {
431 'sub' => sub { feature_bool('blame', @_) },
432 'override' => 0,
433 'default' => [0]},
435 # Enable the 'snapshot' link, providing a compressed archive of any
436 # tree. This can potentially generate high traffic if you have large
437 # project.
439 # Value is a list of formats defined in %known_snapshot_formats that
440 # you wish to offer.
441 # To disable system wide have in $GITWEB_CONFIG
442 # $feature{'snapshot'}{'default'} = [];
443 # To have project specific config enable override in $GITWEB_CONFIG
444 # $feature{'snapshot'}{'override'} = 1;
445 # and in project config, a comma-separated list of formats or "none"
446 # to disable. Example: gitweb.snapshot = tbz2,zip;
447 'snapshot' => {
448 'sub' => \&feature_snapshot,
449 'override' => 0,
450 'default' => ['tgz']},
452 # Enable text search, which will list the commits which match author,
453 # committer or commit text to a given string. Enabled by default.
454 # Project specific override is not supported.
455 'search' => {
456 'override' => 0,
457 'default' => [1]},
459 # Enable grep search, which will list the files in currently selected
460 # tree containing the given string. Enabled by default. This can be
461 # potentially CPU-intensive, of course.
463 # To enable system wide have in $GITWEB_CONFIG
464 # $feature{'grep'}{'default'} = [1];
465 # To have project specific config enable override in $GITWEB_CONFIG
466 # $feature{'grep'}{'override'} = 1;
467 # and in project config gitweb.grep = 0|1;
468 'grep' => {
469 'sub' => sub { feature_bool('grep', @_) },
470 'override' => 0,
471 'default' => [1]},
473 # Enable the pickaxe search, which will list the commits that modified
474 # a given string in a file. This can be practical and quite faster
475 # alternative to 'blame', but still potentially CPU-intensive.
477 # To enable system wide have in $GITWEB_CONFIG
478 # $feature{'pickaxe'}{'default'} = [1];
479 # To have project specific config enable override in $GITWEB_CONFIG
480 # $feature{'pickaxe'}{'override'} = 1;
481 # and in project config gitweb.pickaxe = 0|1;
482 'pickaxe' => {
483 'sub' => sub { feature_bool('pickaxe', @_) },
484 'override' => 0,
485 'default' => [1]},
487 # Enable showing size of blobs in a 'tree' view, in a separate
488 # column, similar to what 'ls -l' does. This cost a bit of IO.
490 # To disable system wide have in $GITWEB_CONFIG
491 # $feature{'show-sizes'}{'default'} = [0];
492 # To have project specific config enable override in $GITWEB_CONFIG
493 # $feature{'show-sizes'}{'override'} = 1;
494 # and in project config gitweb.showsizes = 0|1;
495 'show-sizes' => {
496 'sub' => sub { feature_bool('showsizes', @_) },
497 'override' => 0,
498 'default' => [1]},
500 # Make gitweb use an alternative format of the URLs which can be
501 # more readable and natural-looking: project name is embedded
502 # directly in the path and the query string contains other
503 # auxiliary information. All gitweb installations recognize
504 # URL in either format; this configures in which formats gitweb
505 # generates links.
507 # To enable system wide have in $GITWEB_CONFIG
508 # $feature{'pathinfo'}{'default'} = [1];
509 # Project specific override is not supported.
511 # Note that you will need to change the default location of CSS,
512 # favicon, logo and possibly other files to an absolute URL. Also,
513 # if gitweb.cgi serves as your indexfile, you will need to force
514 # $my_uri to contain the script name in your $GITWEB_CONFIG.
515 'pathinfo' => {
516 'override' => 0,
517 'default' => [0]},
519 # Make gitweb consider projects in project root subdirectories
520 # to be forks of existing projects. Given project $projname.git,
521 # projects matching $projname/*.git will not be shown in the main
522 # projects list, instead a '+' mark will be added to $projname
523 # there and a 'forks' view will be enabled for the project, listing
524 # all the forks. If project list is taken from a file, forks have
525 # to be listed after the main project.
527 # To enable system wide have in $GITWEB_CONFIG
528 # $feature{'forks'}{'default'} = [1];
529 # Project specific override is not supported.
530 'forks' => {
531 'override' => 0,
532 'default' => [0]},
534 # Insert custom links to the action bar of all project pages.
535 # This enables you mainly to link to third-party scripts integrating
536 # into gitweb; e.g. git-browser for graphical history representation
537 # or custom web-based repository administration interface.
539 # The 'default' value consists of a list of triplets in the form
540 # (label, link, position) where position is the label after which
541 # to insert the link and link is a format string where %n expands
542 # to the project name, %f to the project path within the filesystem,
543 # %h to the current hash (h gitweb parameter) and %b to the current
544 # hash base (hb gitweb parameter); %% expands to %.
546 # To enable system wide have in $GITWEB_CONFIG e.g.
547 # $feature{'actions'}{'default'} = [('graphiclog',
548 # '/git-browser/by-commit.html?r=%n', 'summary')];
549 # Project specific override is not supported.
550 'actions' => {
551 'override' => 0,
552 'default' => []},
554 # Allow gitweb scan project content tags described in ctags/
555 # of project repository, and display the popular Web 2.0-ish
556 # "tag cloud" near the project list. Note that this is something
557 # COMPLETELY different from the normal Git tags.
559 # gitweb by itself can show existing tags, but it does not handle
560 # tagging itself; you need an external application for that.
561 # For an example script, check Girocco's cgi/tagproj.cgi.
562 # You may want to install the HTML::TagCloud Perl module to get
563 # a pretty tag cloud instead of just a list of tags.
565 # To enable system wide have in $GITWEB_CONFIG
566 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
567 # Project specific override is not supported.
568 'ctags' => {
569 'override' => 0,
570 'default' => [0]},
572 # The maximum number of patches in a patchset generated in patch
573 # view. Set this to 0 or undef to disable patch view, or to a
574 # negative number to remove any limit.
576 # To disable system wide have in $GITWEB_CONFIG
577 # $feature{'patches'}{'default'} = [0];
578 # To have project specific config enable override in $GITWEB_CONFIG
579 # $feature{'patches'}{'override'} = 1;
580 # and in project config gitweb.patches = 0|n;
581 # where n is the maximum number of patches allowed in a patchset.
582 'patches' => {
583 'sub' => \&feature_patches,
584 'override' => 0,
585 'default' => [16]},
587 # Avatar support. When this feature is enabled, views such as
588 # shortlog or commit will display an avatar associated with
589 # the email of the committer(s) and/or author(s).
591 # Currently available providers are gravatar and picon.
592 # If an unknown provider is specified, the feature is disabled.
594 # Gravatar depends on Digest::MD5.
595 # Picon currently relies on the indiana.edu database.
597 # To enable system wide have in $GITWEB_CONFIG
598 # $feature{'avatar'}{'default'} = ['<provider>'];
599 # where <provider> is either gravatar or picon.
600 # To have project specific config enable override in $GITWEB_CONFIG
601 # $feature{'avatar'}{'override'} = 1;
602 # and in project config gitweb.avatar = <provider>;
603 'avatar' => {
604 'sub' => \&feature_avatar,
605 'override' => 0,
606 'default' => ['']},
608 # Enable displaying how much time and how many git commands
609 # it took to generate and display page. Disabled by default.
610 # Project specific override is not supported.
611 'timed' => {
612 'override' => 0,
613 'default' => [0]},
615 # Enable turning some links into links to actions which require
616 # JavaScript to run (like 'blame_incremental'). Not enabled by
617 # default. Project specific override is currently not supported.
618 'javascript-actions' => {
619 'override' => 0,
620 'default' => [0]},
622 # Syntax highlighting support. This is based on Daniel Svensson's
623 # and Sham Chukoury's work in gitweb-xmms2.git.
624 # It requires the 'highlight' program present in $PATH,
625 # and therefore is disabled by default.
627 # To enable system wide have in $GITWEB_CONFIG
628 # $feature{'highlight'}{'default'} = [1];
630 'highlight' => {
631 'sub' => sub { feature_bool('highlight', @_) },
632 'override' => 0,
633 'default' => [0]},
636 sub gitweb_get_feature {
637 my ($name) = @_;
638 return unless exists $feature{$name};
639 my ($sub, $override, @defaults) = (
640 $feature{$name}{'sub'},
641 $feature{$name}{'override'},
642 @{$feature{$name}{'default'}});
643 # project specific override is possible only if we have project
644 our $git_dir; # global variable, declared later
645 if (!$override || !defined $git_dir) {
646 return @defaults;
648 if (!defined $sub) {
649 warn "feature $name is not overridable";
650 return @defaults;
652 return $sub->(@defaults);
655 # A wrapper to check if a given feature is enabled.
656 # With this, you can say
658 # my $bool_feat = gitweb_check_feature('bool_feat');
659 # gitweb_check_feature('bool_feat') or somecode;
661 # instead of
663 # my ($bool_feat) = gitweb_get_feature('bool_feat');
664 # (gitweb_get_feature('bool_feat'))[0] or somecode;
666 sub gitweb_check_feature {
667 return (gitweb_get_feature(@_))[0];
671 sub feature_bool {
672 my $key = shift;
673 my ($val) = git_get_project_config($key, '--bool');
675 if (!defined $val) {
676 return ($_[0]);
677 } elsif ($val eq 'true') {
678 return (1);
679 } elsif ($val eq 'false') {
680 return (0);
684 sub feature_snapshot {
685 my (@fmts) = @_;
687 my ($val) = git_get_project_config('snapshot');
689 if ($val) {
690 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
693 return @fmts;
696 sub feature_patches {
697 my @val = (git_get_project_config('patches', '--int'));
699 if (@val) {
700 return @val;
703 return ($_[0]);
706 sub feature_avatar {
707 my @val = (git_get_project_config('avatar'));
709 return @val ? @val : @_;
712 # checking HEAD file with -e is fragile if the repository was
713 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
714 # and then pruned.
715 sub check_head_link {
716 my ($dir) = @_;
717 my $headfile = "$dir/HEAD";
718 return ((-e $headfile) ||
719 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
722 sub check_export_ok {
723 my ($dir) = @_;
724 return (check_head_link($dir) &&
725 (!$export_ok || -e "$dir/$export_ok") &&
726 (!$export_auth_hook || $export_auth_hook->($dir)));
729 # process alternate names for backward compatibility
730 # filter out unsupported (unknown) snapshot formats
731 sub filter_snapshot_fmts {
732 my @fmts = @_;
734 @fmts = map {
735 exists $known_snapshot_format_aliases{$_} ?
736 $known_snapshot_format_aliases{$_} : $_} @fmts;
737 @fmts = grep {
738 exists $known_snapshot_formats{$_} &&
739 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
742 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
743 sub evaluate_gitweb_config {
744 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
745 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
746 # die if there are errors parsing config file
747 if (-e $GITWEB_CONFIG) {
748 do $GITWEB_CONFIG;
749 die $@ if $@;
750 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
751 do $GITWEB_CONFIG_SYSTEM;
752 die $@ if $@;
756 # Get loadavg of system, to compare against $maxload.
757 # Currently it requires '/proc/loadavg' present to get loadavg;
758 # if it is not present it returns 0, which means no load checking.
759 sub get_loadavg {
760 if( -e '/proc/loadavg' ){
761 open my $fd, '<', '/proc/loadavg'
762 or return 0;
763 my @load = split(/\s+/, scalar <$fd>);
764 close $fd;
766 # The first three columns measure CPU and IO utilization of the last one,
767 # five, and 10 minute periods. The fourth column shows the number of
768 # currently running processes and the total number of processes in the m/n
769 # format. The last column displays the last process ID used.
770 return $load[0] || 0;
772 # additional checks for load average should go here for things that don't export
773 # /proc/loadavg
775 return 0;
778 # version of the core git binary
779 our $git_version;
780 sub evaluate_git_version {
781 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
782 $number_of_git_cmds++;
785 sub check_loadavg {
786 if (defined $maxload && get_loadavg() > $maxload) {
787 die_error(503, "The load average on the server is too high");
791 # ======================================================================
792 # input validation and dispatch
794 # input parameters can be collected from a variety of sources (presently, CGI
795 # and PATH_INFO), so we define an %input_params hash that collects them all
796 # together during validation: this allows subsequent uses (e.g. href()) to be
797 # agnostic of the parameter origin
799 our %input_params = ();
801 # input parameters are stored with the long parameter name as key. This will
802 # also be used in the href subroutine to convert parameters to their CGI
803 # equivalent, and since the href() usage is the most frequent one, we store
804 # the name -> CGI key mapping here, instead of the reverse.
806 # XXX: Warning: If you touch this, check the search form for updating,
807 # too.
809 our @cgi_param_mapping = (
810 project => "p",
811 action => "a",
812 file_name => "f",
813 file_parent => "fp",
814 hash => "h",
815 hash_parent => "hp",
816 hash_base => "hb",
817 hash_parent_base => "hpb",
818 page => "pg",
819 order => "o",
820 searchtext => "s",
821 searchtype => "st",
822 snapshot_format => "sf",
823 extra_options => "opt",
824 search_use_regexp => "sr",
825 # this must be last entry (for manipulation from JavaScript)
826 javascript => "js"
828 our %cgi_param_mapping = @cgi_param_mapping;
830 # we will also need to know the possible actions, for validation
831 our %actions = (
832 "blame" => \&git_blame,
833 "blame_incremental" => \&git_blame_incremental,
834 "blame_data" => \&git_blame_data,
835 "blobdiff" => \&git_blobdiff,
836 "blobdiff_plain" => \&git_blobdiff_plain,
837 "blob" => \&git_blob,
838 "blob_plain" => \&git_blob_plain,
839 "commitdiff" => \&git_commitdiff,
840 "commitdiff_plain" => \&git_commitdiff_plain,
841 "commit" => \&git_commit,
842 "forks" => \&git_forks,
843 "heads" => \&git_heads,
844 "history" => \&git_history,
845 "log" => \&git_log,
846 "patch" => \&git_patch,
847 "patches" => \&git_patches,
848 "rss" => \&git_rss,
849 "atom" => \&git_atom,
850 "search" => \&git_search,
851 "search_help" => \&git_search_help,
852 "shortlog" => \&git_shortlog,
853 "summary" => \&git_summary,
854 "tag" => \&git_tag,
855 "tags" => \&git_tags,
856 "tree" => \&git_tree,
857 "snapshot" => \&git_snapshot,
858 "object" => \&git_object,
859 # those below don't need $project
860 "opml" => \&git_opml,
861 "project_list" => \&git_project_list,
862 "project_index" => \&git_project_index,
865 # finally, we have the hash of allowed extra_options for the commands that
866 # allow them
867 our %allowed_options = (
868 "--no-merges" => [ qw(rss atom log shortlog history) ],
871 our %actions_info = ();
872 sub evaluate_actions_info {
873 our %actions_info;
874 our (%actions);
876 # unless explicitely stated otherwise, default output format is html
877 foreach my $action (keys %actions) {
878 $actions_info{$action}{'output_format'} = 'html';
880 # list all exceptions; undef means variable (no definite format)
881 map { $actions_info{$_}{'output_format'} = 'text' }
882 qw(commitdiff_plain patch patches project_index blame_data);
883 map { $actions_info{$_}{'output_format'} = 'xml' }
884 qw(rss atom opml); # there are different types (document formats) of XML
885 map { $actions_info{$_}{'output_format'} = undef }
886 qw(blob_plain object);
887 $actions_info{'snapshot'}{'output_format'} = 'binary';
890 sub action_outputs_html {
891 my $action = shift;
892 return $actions_info{$action}{'output_format'} eq 'html';
895 sub browser_is_robot {
896 return 1 if !exists $ENV{'HTTP_USER_AGENT'}; # gitweb run as script
897 if (eval { require HTTP::BrowserDetect; }) {
898 my $browser = HTTP::BrowserDetect->new();
899 return $browser->robot();
901 # fallback on detecting known web browsers
902 return 0 if ($ENV{'HTTP_USER_AGENT'} =~ /\b(?:Mozilla|Opera|Safari|IE)\b/);
903 # be conservative; if not sure, assume non-interactive
904 return 1;
907 # fill %input_params with the CGI parameters. All values except for 'opt'
908 # should be single values, but opt can be an array. We should probably
909 # build an array of parameters that can be multi-valued, but since for the time
910 # being it's only this one, we just single it out
911 sub evaluate_query_params {
912 our $cgi;
914 while (my ($name, $symbol) = each %cgi_param_mapping) {
915 if ($symbol eq 'opt') {
916 $input_params{$name} = [ $cgi->param($symbol) ];
917 } else {
918 $input_params{$name} = $cgi->param($symbol);
923 # now read PATH_INFO and update the parameter list for missing parameters
924 sub evaluate_path_info {
925 return if defined $input_params{'project'};
926 return if !$path_info;
927 $path_info =~ s,^/+,,;
928 return if !$path_info;
930 # find which part of PATH_INFO is project
931 my $project = $path_info;
932 $project =~ s,/+$,,;
933 while ($project && !check_head_link("$projectroot/$project")) {
934 $project =~ s,/*[^/]*$,,;
936 return unless $project;
937 $input_params{'project'} = $project;
939 # do not change any parameters if an action is given using the query string
940 return if $input_params{'action'};
941 $path_info =~ s,^\Q$project\E/*,,;
943 # next, check if we have an action
944 my $action = $path_info;
945 $action =~ s,/.*$,,;
946 if (exists $actions{$action}) {
947 $path_info =~ s,^$action/*,,;
948 $input_params{'action'} = $action;
951 # list of actions that want hash_base instead of hash, but can have no
952 # pathname (f) parameter
953 my @wants_base = (
954 'tree',
955 'history',
958 # we want to catch, among others
959 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
960 my ($parentrefname, $parentpathname, $refname, $pathname) =
961 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
963 # first, analyze the 'current' part
964 if (defined $pathname) {
965 # we got "branch:filename" or "branch:dir/"
966 # we could use git_get_type(branch:pathname), but:
967 # - it needs $git_dir
968 # - it does a git() call
969 # - the convention of terminating directories with a slash
970 # makes it superfluous
971 # - embedding the action in the PATH_INFO would make it even
972 # more superfluous
973 $pathname =~ s,^/+,,;
974 if (!$pathname || substr($pathname, -1) eq "/") {
975 $input_params{'action'} ||= "tree";
976 $pathname =~ s,/$,,;
977 } else {
978 # the default action depends on whether we had parent info
979 # or not
980 if ($parentrefname) {
981 $input_params{'action'} ||= "blobdiff_plain";
982 } else {
983 $input_params{'action'} ||= "blob_plain";
986 $input_params{'hash_base'} ||= $refname;
987 $input_params{'file_name'} ||= $pathname;
988 } elsif (defined $refname) {
989 # we got "branch". In this case we have to choose if we have to
990 # set hash or hash_base.
992 # Most of the actions without a pathname only want hash to be
993 # set, except for the ones specified in @wants_base that want
994 # hash_base instead. It should also be noted that hand-crafted
995 # links having 'history' as an action and no pathname or hash
996 # set will fail, but that happens regardless of PATH_INFO.
997 if (defined $parentrefname) {
998 # if there is parent let the default be 'shortlog' action
999 # (for http://git.example.com/repo.git/A..B links); if there
1000 # is no parent, dispatch will detect type of object and set
1001 # action appropriately if required (if action is not set)
1002 $input_params{'action'} ||= "shortlog";
1004 if ($input_params{'action'} &&
1005 grep { $_ eq $input_params{'action'} } @wants_base) {
1006 $input_params{'hash_base'} ||= $refname;
1007 } else {
1008 $input_params{'hash'} ||= $refname;
1012 # next, handle the 'parent' part, if present
1013 if (defined $parentrefname) {
1014 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1015 # someproject/blobdiff/oldrev..newrev:/filename
1016 if ($parentpathname) {
1017 $parentpathname =~ s,^/+,,;
1018 $parentpathname =~ s,/$,,;
1019 $input_params{'file_parent'} ||= $parentpathname;
1020 } else {
1021 $input_params{'file_parent'} ||= $input_params{'file_name'};
1023 # we assume that hash_parent_base is wanted if a path was specified,
1024 # or if the action wants hash_base instead of hash
1025 if (defined $input_params{'file_parent'} ||
1026 grep { $_ eq $input_params{'action'} } @wants_base) {
1027 $input_params{'hash_parent_base'} ||= $parentrefname;
1028 } else {
1029 $input_params{'hash_parent'} ||= $parentrefname;
1033 # for the snapshot action, we allow URLs in the form
1034 # $project/snapshot/$hash.ext
1035 # where .ext determines the snapshot and gets removed from the
1036 # passed $refname to provide the $hash.
1038 # To be able to tell that $refname includes the format extension, we
1039 # require the following two conditions to be satisfied:
1040 # - the hash input parameter MUST have been set from the $refname part
1041 # of the URL (i.e. they must be equal)
1042 # - the snapshot format MUST NOT have been defined already (e.g. from
1043 # CGI parameter sf)
1044 # It's also useless to try any matching unless $refname has a dot,
1045 # so we check for that too
1046 if (defined $input_params{'action'} &&
1047 $input_params{'action'} eq 'snapshot' &&
1048 defined $refname && index($refname, '.') != -1 &&
1049 $refname eq $input_params{'hash'} &&
1050 !defined $input_params{'snapshot_format'}) {
1051 # We loop over the known snapshot formats, checking for
1052 # extensions. Allowed extensions are both the defined suffix
1053 # (which includes the initial dot already) and the snapshot
1054 # format key itself, with a prepended dot
1055 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1056 my $hash = $refname;
1057 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1058 next;
1060 my $sfx = $1;
1061 # a valid suffix was found, so set the snapshot format
1062 # and reset the hash parameter
1063 $input_params{'snapshot_format'} = $fmt;
1064 $input_params{'hash'} = $hash;
1065 # we also set the format suffix to the one requested
1066 # in the URL: this way a request for e.g. .tgz returns
1067 # a .tgz instead of a .tar.gz
1068 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1069 last;
1074 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1075 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1076 $searchtext, $search_regexp);
1077 sub evaluate_and_validate_params {
1078 our $action = $input_params{'action'};
1079 if (defined $action) {
1080 if (!validate_action($action)) {
1081 die_error(400, "Invalid action parameter");
1085 # parameters which are pathnames
1086 our $project = $input_params{'project'};
1087 if (defined $project) {
1088 if (!validate_project($project)) {
1089 undef $project;
1090 die_error(404, "No such project");
1094 our $file_name = $input_params{'file_name'};
1095 if (defined $file_name) {
1096 if (!validate_pathname($file_name)) {
1097 die_error(400, "Invalid file parameter");
1101 our $file_parent = $input_params{'file_parent'};
1102 if (defined $file_parent) {
1103 if (!validate_pathname($file_parent)) {
1104 die_error(400, "Invalid file parent parameter");
1108 # parameters which are refnames
1109 our $hash = $input_params{'hash'};
1110 if (defined $hash) {
1111 if (!validate_refname($hash)) {
1112 die_error(400, "Invalid hash parameter");
1116 our $hash_parent = $input_params{'hash_parent'};
1117 if (defined $hash_parent) {
1118 if (!validate_refname($hash_parent)) {
1119 die_error(400, "Invalid hash parent parameter");
1123 our $hash_base = $input_params{'hash_base'};
1124 if (defined $hash_base) {
1125 if (!validate_refname($hash_base)) {
1126 die_error(400, "Invalid hash base parameter");
1130 our @extra_options = @{$input_params{'extra_options'}};
1131 # @extra_options is always defined, since it can only be (currently) set from
1132 # CGI, and $cgi->param() returns the empty array in array context if the param
1133 # is not set
1134 foreach my $opt (@extra_options) {
1135 if (not exists $allowed_options{$opt}) {
1136 die_error(400, "Invalid option parameter");
1138 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1139 die_error(400, "Invalid option parameter for this action");
1143 our $hash_parent_base = $input_params{'hash_parent_base'};
1144 if (defined $hash_parent_base) {
1145 if (!validate_refname($hash_parent_base)) {
1146 die_error(400, "Invalid hash parent base parameter");
1150 # other parameters
1151 our $page = $input_params{'page'};
1152 if (defined $page) {
1153 if ($page =~ m/[^0-9]/) {
1154 die_error(400, "Invalid page parameter");
1158 our $searchtype = $input_params{'searchtype'};
1159 if (defined $searchtype) {
1160 if ($searchtype =~ m/[^a-z]/) {
1161 die_error(400, "Invalid searchtype parameter");
1165 our $search_use_regexp = $input_params{'search_use_regexp'};
1167 our $searchtext = $input_params{'searchtext'};
1168 our $search_regexp;
1169 if (defined $searchtext) {
1170 if (length($searchtext) < 2) {
1171 die_error(403, "At least two characters are required for search parameter");
1173 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1177 # path to the current git repository
1178 our $git_dir;
1179 sub evaluate_git_dir {
1180 our $git_dir = "$projectroot/$project" if $project;
1183 our (@snapshot_fmts, $git_avatar);
1184 sub configure_gitweb_features {
1185 # list of supported snapshot formats
1186 our @snapshot_fmts = gitweb_get_feature('snapshot');
1187 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1189 # check that the avatar feature is set to a known provider name,
1190 # and for each provider check if the dependencies are satisfied.
1191 # if the provider name is invalid or the dependencies are not met,
1192 # reset $git_avatar to the empty string.
1193 our ($git_avatar) = gitweb_get_feature('avatar');
1194 if ($git_avatar eq 'gravatar') {
1195 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1196 } elsif ($git_avatar eq 'picon') {
1197 # no dependencies
1198 } else {
1199 $git_avatar = '';
1203 # custom error handler for caching engine (Internal Server Error)
1204 sub cache_error_handler {
1205 my $error = shift;
1207 $error = to_utf8($error);
1208 $error =
1209 "Error in caching layer: <i>".ref($cache)."</i><br>\n".
1210 CGI::escapeHTML($error);
1211 # die_error() would exit
1212 die_error(undef, undef, $error);
1214 # custom error handler: 'die <message>' is Internal Server Error
1215 sub handle_errors_html {
1216 my $msg = shift; # it is already HTML escaped
1218 # to avoid infinite loop where error occurs in die_error,
1219 # change handler to default handler, disabling handle_errors_html
1220 set_message("Error occured when inside die_error:\n$msg");
1222 # you cannot jump out of die_error when called as error handler;
1223 # the subroutine set via CGI::Carp::set_message is called _after_
1224 # HTTP headers are already written, so it cannot write them itself
1225 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1227 set_message(\&handle_errors_html);
1229 # dispatch
1230 sub dispatch {
1231 if (!defined $action) {
1232 if (defined $hash) {
1233 $action = git_get_type($hash);
1234 } elsif (defined $hash_base && defined $file_name) {
1235 $action = git_get_type("$hash_base:$file_name");
1236 } elsif (defined $project) {
1237 $action = 'summary';
1238 } else {
1239 $action = 'project_list';
1242 if (!defined($actions{$action})) {
1243 die_error(400, "Unknown action");
1245 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1246 !$project) {
1247 die_error(400, "Project needed");
1250 if ($caching_enabled) {
1251 # human readable key identifying gitweb output
1252 my $output_key = href(-replay => 1, -full => 1, -path_info => 0);
1254 cache_output($cache, $capture, $output_key, $actions{$action});
1255 } else {
1256 $actions{$action}->();
1260 sub reset_timer {
1261 our $t0 = [Time::HiRes::gettimeofday()]
1262 if defined $t0;
1263 our $number_of_git_cmds = 0;
1266 sub run_request {
1267 reset_timer();
1269 evaluate_uri();
1270 evaluate_gitweb_config();
1271 evaluate_git_version();
1272 check_loadavg();
1273 configure_caching()
1274 if ($caching_enabled);
1276 # $projectroot and $projects_list might be set in gitweb config file
1277 $projects_list ||= $projectroot;
1279 evaluate_query_params();
1280 evaluate_path_info();
1281 evaluate_and_validate_params();
1282 evaluate_git_dir();
1284 configure_gitweb_features();
1286 dispatch();
1289 our $is_last_request = sub { 1 };
1290 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1291 our $CGI = 'CGI';
1292 our $cgi;
1293 sub configure_as_fcgi {
1294 require CGI::Fast;
1295 our $CGI = 'CGI::Fast';
1297 my $request_number = 0;
1298 # let each child service 100 requests
1299 our $is_last_request = sub { ++$request_number > 100 };
1301 sub evaluate_argv {
1302 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1303 configure_as_fcgi()
1304 if $script_name =~ /\.fcgi$/;
1306 return unless (@ARGV);
1308 require Getopt::Long;
1309 Getopt::Long::GetOptions(
1310 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1311 'nproc|n=i' => sub {
1312 my ($arg, $val) = @_;
1313 return unless eval { require FCGI::ProcManager; 1; };
1314 my $proc_manager = FCGI::ProcManager->new({
1315 n_processes => $val,
1317 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1318 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1319 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1324 sub run {
1325 evaluate_argv();
1326 evaluate_actions_info();
1328 $pre_listen_hook->()
1329 if $pre_listen_hook;
1331 REQUEST:
1332 while ($cgi = $CGI->new()) {
1333 $pre_dispatch_hook->()
1334 if $pre_dispatch_hook;
1336 run_request();
1338 $post_dispatch_hook->()
1339 if $post_dispatch_hook;
1341 last REQUEST if ($is_last_request->());
1344 DONE_GITWEB:
1348 sub configure_caching {
1349 if (!eval { require GitwebCache::CacheOutput; 1; }) {
1350 # cache is configured _before_ handling request, so $cgi is not defined,
1351 # so we can't just "die" with sending error message to web browser
1352 #die_error(500, "Caching enabled and GitwebCache::CacheOutput not found");
1354 # turn off caching and warn instead
1355 $caching_enabled = 0;
1356 warn "Caching enabled and GitwebCache::CacheOutput not found";
1358 GitwebCache::CacheOutput->import();
1360 # $cache might be initialized (instantiated) cache, i.e. cache object,
1361 # or it might be name of class, or it might be undefined
1362 unless (defined $cache && ref($cache)) {
1363 $cache ||= 'GitwebCache::FileCacheWithLocking';
1364 eval "require $cache";
1365 die $@ if $@;
1366 $cache = $cache->new({
1367 %cache_options,
1368 #'cache_root' => '/tmp/cache',
1369 #'cache_depth' => 2,
1370 #'expires_in' => 20, # in seconds (CHI compatibile)
1371 # (Cache::Cache compatibile initialization)
1372 'default_expires_in' => $cache_options{'expires_in'},
1373 # (CHI compatibile initialization)
1374 'root_dir' => $cache_options{'cache_root'},
1375 'depth' => $cache_options{'cache_depth'},
1376 'on_get_error' => $cache_options{'on_error'},
1377 'on_set_error' => $cache_options{'on_error'},
1380 unless (defined $capture && ref($capture)) {
1381 require GitwebCache::Capture::Simple;
1382 $capture = GitwebCache::Capture::Simple->new();
1386 run();
1388 if (defined caller) {
1389 # wrapped in a subroutine processing requests,
1390 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1391 return;
1392 } else {
1393 # pure CGI script, serving single request
1394 exit;
1397 ## ======================================================================
1398 ## action links
1400 # possible values of extra options
1401 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1402 # -replay => 1 - start from a current view (replay with modifications)
1403 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1404 sub href {
1405 my %params = @_;
1406 # default is to use -absolute url() i.e. $my_uri
1407 my $href = $params{-full} ? $my_url : $my_uri;
1409 $params{'project'} = $project unless exists $params{'project'};
1411 if ($params{-replay}) {
1412 while (my ($name, $symbol) = each %cgi_param_mapping) {
1413 if (!exists $params{$name}) {
1414 $params{$name} = $input_params{$name};
1419 my $use_pathinfo = gitweb_check_feature('pathinfo');
1420 if (defined $params{'project'} &&
1421 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1422 # try to put as many parameters as possible in PATH_INFO:
1423 # - project name
1424 # - action
1425 # - hash_parent or hash_parent_base:/file_parent
1426 # - hash or hash_base:/filename
1427 # - the snapshot_format as an appropriate suffix
1429 # When the script is the root DirectoryIndex for the domain,
1430 # $href here would be something like http://gitweb.example.com/
1431 # Thus, we strip any trailing / from $href, to spare us double
1432 # slashes in the final URL
1433 $href =~ s,/$,,;
1435 # Then add the project name, if present
1436 $href .= "/".esc_url($params{'project'});
1437 delete $params{'project'};
1439 # since we destructively absorb parameters, we keep this
1440 # boolean that remembers if we're handling a snapshot
1441 my $is_snapshot = $params{'action'} eq 'snapshot';
1443 # Summary just uses the project path URL, any other action is
1444 # added to the URL
1445 if (defined $params{'action'}) {
1446 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1447 delete $params{'action'};
1450 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1451 # stripping nonexistent or useless pieces
1452 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1453 || $params{'hash_parent'} || $params{'hash'});
1454 if (defined $params{'hash_base'}) {
1455 if (defined $params{'hash_parent_base'}) {
1456 $href .= esc_url($params{'hash_parent_base'});
1457 # skip the file_parent if it's the same as the file_name
1458 if (defined $params{'file_parent'}) {
1459 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1460 delete $params{'file_parent'};
1461 } elsif ($params{'file_parent'} !~ /\.\./) {
1462 $href .= ":/".esc_url($params{'file_parent'});
1463 delete $params{'file_parent'};
1466 $href .= "..";
1467 delete $params{'hash_parent'};
1468 delete $params{'hash_parent_base'};
1469 } elsif (defined $params{'hash_parent'}) {
1470 $href .= esc_url($params{'hash_parent'}). "..";
1471 delete $params{'hash_parent'};
1474 $href .= esc_url($params{'hash_base'});
1475 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1476 $href .= ":/".esc_url($params{'file_name'});
1477 delete $params{'file_name'};
1479 delete $params{'hash'};
1480 delete $params{'hash_base'};
1481 } elsif (defined $params{'hash'}) {
1482 $href .= esc_url($params{'hash'});
1483 delete $params{'hash'};
1486 # If the action was a snapshot, we can absorb the
1487 # snapshot_format parameter too
1488 if ($is_snapshot) {
1489 my $fmt = $params{'snapshot_format'};
1490 # snapshot_format should always be defined when href()
1491 # is called, but just in case some code forgets, we
1492 # fall back to the default
1493 $fmt ||= $snapshot_fmts[0];
1494 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1495 delete $params{'snapshot_format'};
1499 # now encode the parameters explicitly
1500 my @result = ();
1501 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1502 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1503 if (defined $params{$name}) {
1504 if (ref($params{$name}) eq "ARRAY") {
1505 foreach my $par (@{$params{$name}}) {
1506 push @result, $symbol . "=" . esc_param($par);
1508 } else {
1509 push @result, $symbol . "=" . esc_param($params{$name});
1513 $href .= "?" . join(';', @result) if scalar @result;
1515 return $href;
1519 ## ======================================================================
1520 ## validation, quoting/unquoting and escaping
1522 sub validate_action {
1523 my $input = shift || return undef;
1524 return undef unless exists $actions{$input};
1525 return $input;
1528 sub validate_project {
1529 my $input = shift || return undef;
1530 if (!validate_pathname($input) ||
1531 !(-d "$projectroot/$input") ||
1532 !check_export_ok("$projectroot/$input") ||
1533 ($strict_export && !project_in_list($input))) {
1534 return undef;
1535 } else {
1536 return $input;
1540 sub validate_pathname {
1541 my $input = shift || return undef;
1543 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1544 # at the beginning, at the end, and between slashes.
1545 # also this catches doubled slashes
1546 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1547 return undef;
1549 # no null characters
1550 if ($input =~ m!\0!) {
1551 return undef;
1553 return $input;
1556 sub validate_refname {
1557 my $input = shift || return undef;
1559 # textual hashes are O.K.
1560 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1561 return $input;
1563 # it must be correct pathname
1564 $input = validate_pathname($input)
1565 or return undef;
1566 # restrictions on ref name according to git-check-ref-format
1567 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1568 return undef;
1570 return $input;
1573 # decode sequences of octets in utf8 into Perl's internal form,
1574 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1575 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1576 sub to_utf8 {
1577 my $str = shift;
1578 return undef unless defined $str;
1579 if (utf8::valid($str)) {
1580 utf8::decode($str);
1581 return $str;
1582 } else {
1583 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1587 # quote unsafe chars, but keep the slash, even when it's not
1588 # correct, but quoted slashes look too horrible in bookmarks
1589 sub esc_param {
1590 my $str = shift;
1591 return undef unless defined $str;
1592 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1593 $str =~ s/ /\+/g;
1594 return $str;
1597 # quote unsafe chars in whole URL, so some characters cannot be quoted
1598 sub esc_url {
1599 my $str = shift;
1600 return undef unless defined $str;
1601 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1602 $str =~ s/ /\+/g;
1603 return $str;
1606 # replace invalid utf8 character with SUBSTITUTION sequence
1607 sub esc_html {
1608 my $str = shift;
1609 my %opts = @_;
1611 return undef unless defined $str;
1613 $str = to_utf8($str);
1614 $str = $cgi->escapeHTML($str);
1615 if ($opts{'-nbsp'}) {
1616 $str =~ s/ /&nbsp;/g;
1618 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1619 return $str;
1622 # quote control characters and escape filename to HTML
1623 sub esc_path {
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:]])|quot_cec($1)|eg;
1635 return $str;
1638 # Make control characters "printable", using character escape codes (CEC)
1639 sub quot_cec {
1640 my $cntrl = shift;
1641 my %opts = @_;
1642 my %es = ( # character escape codes, aka escape sequences
1643 "\t" => '\t', # tab (HT)
1644 "\n" => '\n', # line feed (LF)
1645 "\r" => '\r', # carrige return (CR)
1646 "\f" => '\f', # form feed (FF)
1647 "\b" => '\b', # backspace (BS)
1648 "\a" => '\a', # alarm (bell) (BEL)
1649 "\e" => '\e', # escape (ESC)
1650 "\013" => '\v', # vertical tab (VT)
1651 "\000" => '\0', # nul character (NUL)
1653 my $chr = ( (exists $es{$cntrl})
1654 ? $es{$cntrl}
1655 : sprintf('\%2x', ord($cntrl)) );
1656 if ($opts{-nohtml}) {
1657 return $chr;
1658 } else {
1659 return "<span class=\"cntrl\">$chr</span>";
1663 # Alternatively use unicode control pictures codepoints,
1664 # Unicode "printable representation" (PR)
1665 sub quot_upr {
1666 my $cntrl = shift;
1667 my %opts = @_;
1669 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1670 if ($opts{-nohtml}) {
1671 return $chr;
1672 } else {
1673 return "<span class=\"cntrl\">$chr</span>";
1677 # git may return quoted and escaped filenames
1678 sub unquote {
1679 my $str = shift;
1681 sub unq {
1682 my $seq = shift;
1683 my %es = ( # character escape codes, aka escape sequences
1684 't' => "\t", # tab (HT, TAB)
1685 'n' => "\n", # newline (NL)
1686 'r' => "\r", # return (CR)
1687 'f' => "\f", # form feed (FF)
1688 'b' => "\b", # backspace (BS)
1689 'a' => "\a", # alarm (bell) (BEL)
1690 'e' => "\e", # escape (ESC)
1691 'v' => "\013", # vertical tab (VT)
1694 if ($seq =~ m/^[0-7]{1,3}$/) {
1695 # octal char sequence
1696 return chr(oct($seq));
1697 } elsif (exists $es{$seq}) {
1698 # C escape sequence, aka character escape code
1699 return $es{$seq};
1701 # quoted ordinary character
1702 return $seq;
1705 if ($str =~ m/^"(.*)"$/) {
1706 # needs unquoting
1707 $str = $1;
1708 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1710 return $str;
1713 # escape tabs (convert tabs to spaces)
1714 sub untabify {
1715 my $line = shift;
1717 while ((my $pos = index($line, "\t")) != -1) {
1718 if (my $count = (8 - ($pos % 8))) {
1719 my $spaces = ' ' x $count;
1720 $line =~ s/\t/$spaces/;
1724 return $line;
1727 sub project_in_list {
1728 my $project = shift;
1729 my @list = git_get_projects_list();
1730 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1733 ## ----------------------------------------------------------------------
1734 ## HTML aware string manipulation
1736 # Try to chop given string on a word boundary between position
1737 # $len and $len+$add_len. If there is no word boundary there,
1738 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1739 # (marking chopped part) would be longer than given string.
1740 sub chop_str {
1741 my $str = shift;
1742 my $len = shift;
1743 my $add_len = shift || 10;
1744 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1746 # Make sure perl knows it is utf8 encoded so we don't
1747 # cut in the middle of a utf8 multibyte char.
1748 $str = to_utf8($str);
1750 # allow only $len chars, but don't cut a word if it would fit in $add_len
1751 # if it doesn't fit, cut it if it's still longer than the dots we would add
1752 # remove chopped character entities entirely
1754 # when chopping in the middle, distribute $len into left and right part
1755 # return early if chopping wouldn't make string shorter
1756 if ($where eq 'center') {
1757 return $str if ($len + 5 >= length($str)); # filler is length 5
1758 $len = int($len/2);
1759 } else {
1760 return $str if ($len + 4 >= length($str)); # filler is length 4
1763 # regexps: ending and beginning with word part up to $add_len
1764 my $endre = qr/.{$len}\w{0,$add_len}/;
1765 my $begre = qr/\w{0,$add_len}.{$len}/;
1767 if ($where eq 'left') {
1768 $str =~ m/^(.*?)($begre)$/;
1769 my ($lead, $body) = ($1, $2);
1770 if (length($lead) > 4) {
1771 $lead = " ...";
1773 return "$lead$body";
1775 } elsif ($where eq 'center') {
1776 $str =~ m/^($endre)(.*)$/;
1777 my ($left, $str) = ($1, $2);
1778 $str =~ m/^(.*?)($begre)$/;
1779 my ($mid, $right) = ($1, $2);
1780 if (length($mid) > 5) {
1781 $mid = " ... ";
1783 return "$left$mid$right";
1785 } else {
1786 $str =~ m/^($endre)(.*)$/;
1787 my $body = $1;
1788 my $tail = $2;
1789 if (length($tail) > 4) {
1790 $tail = "... ";
1792 return "$body$tail";
1796 # takes the same arguments as chop_str, but also wraps a <span> around the
1797 # result with a title attribute if it does get chopped. Additionally, the
1798 # string is HTML-escaped.
1799 sub chop_and_escape_str {
1800 my ($str) = @_;
1802 my $chopped = chop_str(@_);
1803 if ($chopped eq $str) {
1804 return esc_html($chopped);
1805 } else {
1806 $str =~ s/[[:cntrl:]]/?/g;
1807 return $cgi->span({-title=>$str}, esc_html($chopped));
1811 ## ----------------------------------------------------------------------
1812 ## functions returning short strings
1814 # CSS class for given age value (in seconds)
1815 sub age_class {
1816 my $age = shift;
1818 if (!defined $age) {
1819 return "noage";
1820 } elsif ($age < 60*60*2) {
1821 return "age0";
1822 } elsif ($age < 60*60*24*2) {
1823 return "age1";
1824 } else {
1825 return "age2";
1829 # convert age in seconds to "nn units ago" string
1830 sub age_string {
1831 my $age = shift;
1832 my $age_str;
1834 if ($age > 60*60*24*365*2) {
1835 $age_str = (int $age/60/60/24/365);
1836 $age_str .= " years ago";
1837 } elsif ($age > 60*60*24*(365/12)*2) {
1838 $age_str = int $age/60/60/24/(365/12);
1839 $age_str .= " months ago";
1840 } elsif ($age > 60*60*24*7*2) {
1841 $age_str = int $age/60/60/24/7;
1842 $age_str .= " weeks ago";
1843 } elsif ($age > 60*60*24*2) {
1844 $age_str = int $age/60/60/24;
1845 $age_str .= " days ago";
1846 } elsif ($age > 60*60*2) {
1847 $age_str = int $age/60/60;
1848 $age_str .= " hours ago";
1849 } elsif ($age > 60*2) {
1850 $age_str = int $age/60;
1851 $age_str .= " min ago";
1852 } elsif ($age > 2) {
1853 $age_str = int $age;
1854 $age_str .= " sec ago";
1855 } else {
1856 $age_str .= " right now";
1858 return $age_str;
1861 use constant {
1862 S_IFINVALID => 0030000,
1863 S_IFGITLINK => 0160000,
1866 # submodule/subproject, a commit object reference
1867 sub S_ISGITLINK {
1868 my $mode = shift;
1870 return (($mode & S_IFMT) == S_IFGITLINK)
1873 # convert file mode in octal to symbolic file mode string
1874 sub mode_str {
1875 my $mode = oct shift;
1877 if (S_ISGITLINK($mode)) {
1878 return 'm---------';
1879 } elsif (S_ISDIR($mode & S_IFMT)) {
1880 return 'drwxr-xr-x';
1881 } elsif (S_ISLNK($mode)) {
1882 return 'lrwxrwxrwx';
1883 } elsif (S_ISREG($mode)) {
1884 # git cares only about the executable bit
1885 if ($mode & S_IXUSR) {
1886 return '-rwxr-xr-x';
1887 } else {
1888 return '-rw-r--r--';
1890 } else {
1891 return '----------';
1895 # convert file mode in octal to file type string
1896 sub file_type {
1897 my $mode = shift;
1899 if ($mode !~ m/^[0-7]+$/) {
1900 return $mode;
1901 } else {
1902 $mode = oct $mode;
1905 if (S_ISGITLINK($mode)) {
1906 return "submodule";
1907 } elsif (S_ISDIR($mode & S_IFMT)) {
1908 return "directory";
1909 } elsif (S_ISLNK($mode)) {
1910 return "symlink";
1911 } elsif (S_ISREG($mode)) {
1912 return "file";
1913 } else {
1914 return "unknown";
1918 # convert file mode in octal to file type description string
1919 sub file_type_long {
1920 my $mode = shift;
1922 if ($mode !~ m/^[0-7]+$/) {
1923 return $mode;
1924 } else {
1925 $mode = oct $mode;
1928 if (S_ISGITLINK($mode)) {
1929 return "submodule";
1930 } elsif (S_ISDIR($mode & S_IFMT)) {
1931 return "directory";
1932 } elsif (S_ISLNK($mode)) {
1933 return "symlink";
1934 } elsif (S_ISREG($mode)) {
1935 if ($mode & S_IXUSR) {
1936 return "executable";
1937 } else {
1938 return "file";
1940 } else {
1941 return "unknown";
1946 ## ----------------------------------------------------------------------
1947 ## functions returning short HTML fragments, or transforming HTML fragments
1948 ## which don't belong to other sections
1950 # format line of commit message.
1951 sub format_log_line_html {
1952 my $line = shift;
1954 $line = esc_html($line, -nbsp=>1);
1955 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1956 $cgi->a({-href => href(action=>"object", hash=>$1),
1957 -class => "text"}, $1);
1958 }eg;
1960 return $line;
1963 # format marker of refs pointing to given object
1965 # the destination action is chosen based on object type and current context:
1966 # - for annotated tags, we choose the tag view unless it's the current view
1967 # already, in which case we go to shortlog view
1968 # - for other refs, we keep the current view if we're in history, shortlog or
1969 # log view, and select shortlog otherwise
1970 sub format_ref_marker {
1971 my ($refs, $id) = @_;
1972 my $markers = '';
1974 if (defined $refs->{$id}) {
1975 foreach my $ref (@{$refs->{$id}}) {
1976 # this code exploits the fact that non-lightweight tags are the
1977 # only indirect objects, and that they are the only objects for which
1978 # we want to use tag instead of shortlog as action
1979 my ($type, $name) = qw();
1980 my $indirect = ($ref =~ s/\^\{\}$//);
1981 # e.g. tags/v2.6.11 or heads/next
1982 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1983 $type = $1;
1984 $name = $2;
1985 } else {
1986 $type = "ref";
1987 $name = $ref;
1990 my $class = $type;
1991 $class .= " indirect" if $indirect;
1993 my $dest_action = "shortlog";
1995 if ($indirect) {
1996 $dest_action = "tag" unless $action eq "tag";
1997 } elsif ($action =~ /^(history|(short)?log)$/) {
1998 $dest_action = $action;
2001 my $dest = "";
2002 $dest .= "refs/" unless $ref =~ m!^refs/!;
2003 $dest .= $ref;
2005 my $link = $cgi->a({
2006 -href => href(
2007 action=>$dest_action,
2008 hash=>$dest
2009 )}, $name);
2011 $markers .= " <span class=\"$class\" title=\"$ref\">" .
2012 $link . "</span>";
2016 if ($markers) {
2017 return ' <span class="refs">'. $markers . '</span>';
2018 } else {
2019 return "";
2023 # format, perhaps shortened and with markers, title line
2024 sub format_subject_html {
2025 my ($long, $short, $href, $extra) = @_;
2026 $extra = '' unless defined($extra);
2028 if (length($short) < length($long)) {
2029 $long =~ s/[[:cntrl:]]/?/g;
2030 return $cgi->a({-href => $href, -class => "list subject",
2031 -title => to_utf8($long)},
2032 esc_html($short)) . $extra;
2033 } else {
2034 return $cgi->a({-href => $href, -class => "list subject"},
2035 esc_html($long)) . $extra;
2039 # Rather than recomputing the url for an email multiple times, we cache it
2040 # after the first hit. This gives a visible benefit in views where the avatar
2041 # for the same email is used repeatedly (e.g. shortlog).
2042 # The cache is shared by all avatar engines (currently gravatar only), which
2043 # are free to use it as preferred. Since only one avatar engine is used for any
2044 # given page, there's no risk for cache conflicts.
2045 our %avatar_cache = ();
2047 # Compute the picon url for a given email, by using the picon search service over at
2048 # http://www.cs.indiana.edu/picons/search.html
2049 sub picon_url {
2050 my $email = lc shift;
2051 if (!$avatar_cache{$email}) {
2052 my ($user, $domain) = split('@', $email);
2053 $avatar_cache{$email} =
2054 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2055 "$domain/$user/" .
2056 "users+domains+unknown/up/single";
2058 return $avatar_cache{$email};
2061 # Compute the gravatar url for a given email, if it's not in the cache already.
2062 # Gravatar stores only the part of the URL before the size, since that's the
2063 # one computationally more expensive. This also allows reuse of the cache for
2064 # different sizes (for this particular engine).
2065 sub gravatar_url {
2066 my $email = lc shift;
2067 my $size = shift;
2068 $avatar_cache{$email} ||=
2069 "http://www.gravatar.com/avatar/" .
2070 Digest::MD5::md5_hex($email) . "?s=";
2071 return $avatar_cache{$email} . $size;
2074 # Insert an avatar for the given $email at the given $size if the feature
2075 # is enabled.
2076 sub git_get_avatar {
2077 my ($email, %opts) = @_;
2078 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2079 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2080 $opts{-size} ||= 'default';
2081 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2082 my $url = "";
2083 if ($git_avatar eq 'gravatar') {
2084 $url = gravatar_url($email, $size);
2085 } elsif ($git_avatar eq 'picon') {
2086 $url = picon_url($email);
2088 # Other providers can be added by extending the if chain, defining $url
2089 # as needed. If no variant puts something in $url, we assume avatars
2090 # are completely disabled/unavailable.
2091 if ($url) {
2092 return $pre_white .
2093 "<img width=\"$size\" " .
2094 "class=\"avatar\" " .
2095 "src=\"$url\" " .
2096 "alt=\"\" " .
2097 "/>" . $post_white;
2098 } else {
2099 return "";
2103 sub format_search_author {
2104 my ($author, $searchtype, $displaytext) = @_;
2105 my $have_search = gitweb_check_feature('search');
2107 if ($have_search) {
2108 my $performed = "";
2109 if ($searchtype eq 'author') {
2110 $performed = "authored";
2111 } elsif ($searchtype eq 'committer') {
2112 $performed = "committed";
2115 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2116 searchtext=>$author,
2117 searchtype=>$searchtype), class=>"list",
2118 title=>"Search for commits $performed by $author"},
2119 $displaytext);
2121 } else {
2122 return $displaytext;
2126 # format the author name of the given commit with the given tag
2127 # the author name is chopped and escaped according to the other
2128 # optional parameters (see chop_str).
2129 sub format_author_html {
2130 my $tag = shift;
2131 my $co = shift;
2132 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2133 return "<$tag class=\"author\">" .
2134 format_search_author($co->{'author_name'}, "author",
2135 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2136 $author) .
2137 "</$tag>";
2140 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2141 sub format_git_diff_header_line {
2142 my $line = shift;
2143 my $diffinfo = shift;
2144 my ($from, $to) = @_;
2146 if ($diffinfo->{'nparents'}) {
2147 # combined diff
2148 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2149 if ($to->{'href'}) {
2150 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2151 esc_path($to->{'file'}));
2152 } else { # file was deleted (no href)
2153 $line .= esc_path($to->{'file'});
2155 } else {
2156 # "ordinary" diff
2157 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2158 if ($from->{'href'}) {
2159 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2160 'a/' . esc_path($from->{'file'}));
2161 } else { # file was added (no href)
2162 $line .= 'a/' . esc_path($from->{'file'});
2164 $line .= ' ';
2165 if ($to->{'href'}) {
2166 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2167 'b/' . esc_path($to->{'file'}));
2168 } else { # file was deleted
2169 $line .= 'b/' . esc_path($to->{'file'});
2173 return "<div class=\"diff header\">$line</div>\n";
2176 # format extended diff header line, before patch itself
2177 sub format_extended_diff_header_line {
2178 my $line = shift;
2179 my $diffinfo = shift;
2180 my ($from, $to) = @_;
2182 # match <path>
2183 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2184 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2185 esc_path($from->{'file'}));
2187 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2188 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2189 esc_path($to->{'file'}));
2191 # match single <mode>
2192 if ($line =~ m/\s(\d{6})$/) {
2193 $line .= '<span class="info"> (' .
2194 file_type_long($1) .
2195 ')</span>';
2197 # match <hash>
2198 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2199 # can match only for combined diff
2200 $line = 'index ';
2201 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2202 if ($from->{'href'}[$i]) {
2203 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2204 -class=>"hash"},
2205 substr($diffinfo->{'from_id'}[$i],0,7));
2206 } else {
2207 $line .= '0' x 7;
2209 # separator
2210 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2212 $line .= '..';
2213 if ($to->{'href'}) {
2214 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2215 substr($diffinfo->{'to_id'},0,7));
2216 } else {
2217 $line .= '0' x 7;
2220 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2221 # can match only for ordinary diff
2222 my ($from_link, $to_link);
2223 if ($from->{'href'}) {
2224 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2225 substr($diffinfo->{'from_id'},0,7));
2226 } else {
2227 $from_link = '0' x 7;
2229 if ($to->{'href'}) {
2230 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2231 substr($diffinfo->{'to_id'},0,7));
2232 } else {
2233 $to_link = '0' x 7;
2235 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2236 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2239 return $line . "<br/>\n";
2242 # format from-file/to-file diff header
2243 sub format_diff_from_to_header {
2244 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2245 my $line;
2246 my $result = '';
2248 $line = $from_line;
2249 #assert($line =~ m/^---/) if DEBUG;
2250 # no extra formatting for "^--- /dev/null"
2251 if (! $diffinfo->{'nparents'}) {
2252 # ordinary (single parent) diff
2253 if ($line =~ m!^--- "?a/!) {
2254 if ($from->{'href'}) {
2255 $line = '--- a/' .
2256 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2257 esc_path($from->{'file'}));
2258 } else {
2259 $line = '--- a/' .
2260 esc_path($from->{'file'});
2263 $result .= qq!<div class="diff from_file">$line</div>\n!;
2265 } else {
2266 # combined diff (merge commit)
2267 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2268 if ($from->{'href'}[$i]) {
2269 $line = '--- ' .
2270 $cgi->a({-href=>href(action=>"blobdiff",
2271 hash_parent=>$diffinfo->{'from_id'}[$i],
2272 hash_parent_base=>$parents[$i],
2273 file_parent=>$from->{'file'}[$i],
2274 hash=>$diffinfo->{'to_id'},
2275 hash_base=>$hash,
2276 file_name=>$to->{'file'}),
2277 -class=>"path",
2278 -title=>"diff" . ($i+1)},
2279 $i+1) .
2280 '/' .
2281 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2282 esc_path($from->{'file'}[$i]));
2283 } else {
2284 $line = '--- /dev/null';
2286 $result .= qq!<div class="diff from_file">$line</div>\n!;
2290 $line = $to_line;
2291 #assert($line =~ m/^\+\+\+/) if DEBUG;
2292 # no extra formatting for "^+++ /dev/null"
2293 if ($line =~ m!^\+\+\+ "?b/!) {
2294 if ($to->{'href'}) {
2295 $line = '+++ b/' .
2296 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2297 esc_path($to->{'file'}));
2298 } else {
2299 $line = '+++ b/' .
2300 esc_path($to->{'file'});
2303 $result .= qq!<div class="diff to_file">$line</div>\n!;
2305 return $result;
2308 # create note for patch simplified by combined diff
2309 sub format_diff_cc_simplified {
2310 my ($diffinfo, @parents) = @_;
2311 my $result = '';
2313 $result .= "<div class=\"diff header\">" .
2314 "diff --cc ";
2315 if (!is_deleted($diffinfo)) {
2316 $result .= $cgi->a({-href => href(action=>"blob",
2317 hash_base=>$hash,
2318 hash=>$diffinfo->{'to_id'},
2319 file_name=>$diffinfo->{'to_file'}),
2320 -class => "path"},
2321 esc_path($diffinfo->{'to_file'}));
2322 } else {
2323 $result .= esc_path($diffinfo->{'to_file'});
2325 $result .= "</div>\n" . # class="diff header"
2326 "<div class=\"diff nodifferences\">" .
2327 "Simple merge" .
2328 "</div>\n"; # class="diff nodifferences"
2330 return $result;
2333 # format patch (diff) line (not to be used for diff headers)
2334 sub format_diff_line {
2335 my $line = shift;
2336 my ($from, $to) = @_;
2337 my $diff_class = "";
2339 chomp $line;
2341 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2342 # combined diff
2343 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2344 if ($line =~ m/^\@{3}/) {
2345 $diff_class = " chunk_header";
2346 } elsif ($line =~ m/^\\/) {
2347 $diff_class = " incomplete";
2348 } elsif ($prefix =~ tr/+/+/) {
2349 $diff_class = " add";
2350 } elsif ($prefix =~ tr/-/-/) {
2351 $diff_class = " rem";
2353 } else {
2354 # assume ordinary diff
2355 my $char = substr($line, 0, 1);
2356 if ($char eq '+') {
2357 $diff_class = " add";
2358 } elsif ($char eq '-') {
2359 $diff_class = " rem";
2360 } elsif ($char eq '@') {
2361 $diff_class = " chunk_header";
2362 } elsif ($char eq "\\") {
2363 $diff_class = " incomplete";
2366 $line = untabify($line);
2367 if ($from && $to && $line =~ m/^\@{2} /) {
2368 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2369 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2371 $from_lines = 0 unless defined $from_lines;
2372 $to_lines = 0 unless defined $to_lines;
2374 if ($from->{'href'}) {
2375 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2376 -class=>"list"}, $from_text);
2378 if ($to->{'href'}) {
2379 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2380 -class=>"list"}, $to_text);
2382 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2383 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2384 return "<div class=\"diff$diff_class\">$line</div>\n";
2385 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2386 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2387 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2389 @from_text = split(' ', $ranges);
2390 for (my $i = 0; $i < @from_text; ++$i) {
2391 ($from_start[$i], $from_nlines[$i]) =
2392 (split(',', substr($from_text[$i], 1)), 0);
2395 $to_text = pop @from_text;
2396 $to_start = pop @from_start;
2397 $to_nlines = pop @from_nlines;
2399 $line = "<span class=\"chunk_info\">$prefix ";
2400 for (my $i = 0; $i < @from_text; ++$i) {
2401 if ($from->{'href'}[$i]) {
2402 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2403 -class=>"list"}, $from_text[$i]);
2404 } else {
2405 $line .= $from_text[$i];
2407 $line .= " ";
2409 if ($to->{'href'}) {
2410 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2411 -class=>"list"}, $to_text);
2412 } else {
2413 $line .= $to_text;
2415 $line .= " $prefix</span>" .
2416 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2417 return "<div class=\"diff$diff_class\">$line</div>\n";
2419 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2422 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2423 # linked. Pass the hash of the tree/commit to snapshot.
2424 sub format_snapshot_links {
2425 my ($hash) = @_;
2426 my $num_fmts = @snapshot_fmts;
2427 if ($num_fmts > 1) {
2428 # A parenthesized list of links bearing format names.
2429 # e.g. "snapshot (_tar.gz_ _zip_)"
2430 return "snapshot (" . join(' ', map
2431 $cgi->a({
2432 -href => href(
2433 action=>"snapshot",
2434 hash=>$hash,
2435 snapshot_format=>$_
2437 }, $known_snapshot_formats{$_}{'display'})
2438 , @snapshot_fmts) . ")";
2439 } elsif ($num_fmts == 1) {
2440 # A single "snapshot" link whose tooltip bears the format name.
2441 # i.e. "_snapshot_"
2442 my ($fmt) = @snapshot_fmts;
2443 return
2444 $cgi->a({
2445 -href => href(
2446 action=>"snapshot",
2447 hash=>$hash,
2448 snapshot_format=>$fmt
2450 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2451 }, "snapshot");
2452 } else { # $num_fmts == 0
2453 return undef;
2457 ## ......................................................................
2458 ## functions returning values to be passed, perhaps after some
2459 ## transformation, to other functions; e.g. returning arguments to href()
2461 # returns hash to be passed to href to generate gitweb URL
2462 # in -title key it returns description of link
2463 sub get_feed_info {
2464 my $format = shift || 'Atom';
2465 my %res = (action => lc($format));
2467 # feed links are possible only for project views
2468 return unless (defined $project);
2469 # some views should link to OPML, or to generic project feed,
2470 # or don't have specific feed yet (so they should use generic)
2471 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2473 my $branch;
2474 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2475 # from tag links; this also makes possible to detect branch links
2476 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2477 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2478 $branch = $1;
2480 # find log type for feed description (title)
2481 my $type = 'log';
2482 if (defined $file_name) {
2483 $type = "history of $file_name";
2484 $type .= "/" if ($action eq 'tree');
2485 $type .= " on '$branch'" if (defined $branch);
2486 } else {
2487 $type = "log of $branch" if (defined $branch);
2490 $res{-title} = $type;
2491 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2492 $res{'file_name'} = $file_name;
2494 return %res;
2497 ## ----------------------------------------------------------------------
2498 ## git utility subroutines, invoking git commands
2500 # returns path to the core git executable and the --git-dir parameter as list
2501 sub git_cmd {
2502 $number_of_git_cmds++;
2503 return $GIT, '--git-dir='.$git_dir;
2506 # quote the given arguments for passing them to the shell
2507 # quote_command("command", "arg 1", "arg with ' and ! characters")
2508 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2509 # Try to avoid using this function wherever possible.
2510 sub quote_command {
2511 return join(' ',
2512 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2515 # get HEAD ref of given project as hash
2516 sub git_get_head_hash {
2517 return git_get_full_hash(shift, 'HEAD');
2520 sub git_get_full_hash {
2521 return git_get_hash(@_);
2524 sub git_get_short_hash {
2525 return git_get_hash(@_, '--short=7');
2528 sub git_get_hash {
2529 my ($project, $hash, @options) = @_;
2530 my $o_git_dir = $git_dir;
2531 my $retval = undef;
2532 $git_dir = "$projectroot/$project";
2533 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2534 '--verify', '-q', @options, $hash) {
2535 $retval = <$fd>;
2536 chomp $retval if defined $retval;
2537 close $fd;
2539 if (defined $o_git_dir) {
2540 $git_dir = $o_git_dir;
2542 return $retval;
2545 # get type of given object
2546 sub git_get_type {
2547 my $hash = shift;
2549 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2550 my $type = <$fd>;
2551 close $fd or return;
2552 chomp $type;
2553 return $type;
2556 # repository configuration
2557 our $config_file = '';
2558 our %config;
2560 # store multiple values for single key as anonymous array reference
2561 # single values stored directly in the hash, not as [ <value> ]
2562 sub hash_set_multi {
2563 my ($hash, $key, $value) = @_;
2565 if (!exists $hash->{$key}) {
2566 $hash->{$key} = $value;
2567 } elsif (!ref $hash->{$key}) {
2568 $hash->{$key} = [ $hash->{$key}, $value ];
2569 } else {
2570 push @{$hash->{$key}}, $value;
2574 # return hash of git project configuration
2575 # optionally limited to some section, e.g. 'gitweb'
2576 sub git_parse_project_config {
2577 my $section_regexp = shift;
2578 my %config;
2580 local $/ = "\0";
2582 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2583 or return;
2585 while (my $keyval = <$fh>) {
2586 chomp $keyval;
2587 my ($key, $value) = split(/\n/, $keyval, 2);
2589 hash_set_multi(\%config, $key, $value)
2590 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2592 close $fh;
2594 return %config;
2597 # convert config value to boolean: 'true' or 'false'
2598 # no value, number > 0, 'true' and 'yes' values are true
2599 # rest of values are treated as false (never as error)
2600 sub config_to_bool {
2601 my $val = shift;
2603 return 1 if !defined $val; # section.key
2605 # strip leading and trailing whitespace
2606 $val =~ s/^\s+//;
2607 $val =~ s/\s+$//;
2609 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2610 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2613 # convert config value to simple decimal number
2614 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2615 # to be multiplied by 1024, 1048576, or 1073741824
2616 sub config_to_int {
2617 my $val = shift;
2619 # strip leading and trailing whitespace
2620 $val =~ s/^\s+//;
2621 $val =~ s/\s+$//;
2623 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2624 $unit = lc($unit);
2625 # unknown unit is treated as 1
2626 return $num * ($unit eq 'g' ? 1073741824 :
2627 $unit eq 'm' ? 1048576 :
2628 $unit eq 'k' ? 1024 : 1);
2630 return $val;
2633 # convert config value to array reference, if needed
2634 sub config_to_multi {
2635 my $val = shift;
2637 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2640 sub git_get_project_config {
2641 my ($key, $type) = @_;
2643 return unless defined $git_dir;
2645 # key sanity check
2646 return unless ($key);
2647 $key =~ s/^gitweb\.//;
2648 return if ($key =~ m/\W/);
2650 # type sanity check
2651 if (defined $type) {
2652 $type =~ s/^--//;
2653 $type = undef
2654 unless ($type eq 'bool' || $type eq 'int');
2657 # get config
2658 if (!defined $config_file ||
2659 $config_file ne "$git_dir/config") {
2660 %config = git_parse_project_config('gitweb');
2661 $config_file = "$git_dir/config";
2664 # check if config variable (key) exists
2665 return unless exists $config{"gitweb.$key"};
2667 # ensure given type
2668 if (!defined $type) {
2669 return $config{"gitweb.$key"};
2670 } elsif ($type eq 'bool') {
2671 # backward compatibility: 'git config --bool' returns true/false
2672 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2673 } elsif ($type eq 'int') {
2674 return config_to_int($config{"gitweb.$key"});
2676 return $config{"gitweb.$key"};
2679 # get hash of given path at given ref
2680 sub git_get_hash_by_path {
2681 my $base = shift;
2682 my $path = shift || return undef;
2683 my $type = shift;
2685 $path =~ s,/+$,,;
2687 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2688 or die_error(500, "Open git-ls-tree failed");
2689 my $line = <$fd>;
2690 close $fd or return undef;
2692 if (!defined $line) {
2693 # there is no tree or hash given by $path at $base
2694 return undef;
2697 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2698 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2699 if (defined $type && $type ne $2) {
2700 # type doesn't match
2701 return undef;
2703 return $3;
2706 # get path of entry with given hash at given tree-ish (ref)
2707 # used to get 'from' filename for combined diff (merge commit) for renames
2708 sub git_get_path_by_hash {
2709 my $base = shift || return;
2710 my $hash = shift || return;
2712 local $/ = "\0";
2714 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2715 or return undef;
2716 while (my $line = <$fd>) {
2717 chomp $line;
2719 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2720 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2721 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2722 close $fd;
2723 return $1;
2726 close $fd;
2727 return undef;
2730 ## ......................................................................
2731 ## git utility functions, directly accessing git repository
2733 sub git_get_project_description {
2734 my $path = shift;
2736 $git_dir = "$projectroot/$path";
2737 open my $fd, '<', "$git_dir/description"
2738 or return git_get_project_config('description');
2739 my $descr = <$fd>;
2740 close $fd;
2741 if (defined $descr) {
2742 chomp $descr;
2744 return $descr;
2747 sub git_get_project_ctags {
2748 my $path = shift;
2749 my $ctags = {};
2751 $git_dir = "$projectroot/$path";
2752 opendir my $dh, "$git_dir/ctags"
2753 or return $ctags;
2754 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2755 open my $ct, '<', $_ or next;
2756 my $val = <$ct>;
2757 chomp $val;
2758 close $ct;
2759 my $ctag = $_; $ctag =~ s#.*/##;
2760 $ctags->{$ctag} = $val;
2762 closedir $dh;
2763 $ctags;
2766 sub git_populate_project_tagcloud {
2767 my $ctags = shift;
2769 # First, merge different-cased tags; tags vote on casing
2770 my %ctags_lc;
2771 foreach (keys %$ctags) {
2772 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2773 if (not $ctags_lc{lc $_}->{topcount}
2774 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2775 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2776 $ctags_lc{lc $_}->{topname} = $_;
2780 my $cloud;
2781 if (eval { require HTML::TagCloud; 1; }) {
2782 $cloud = HTML::TagCloud->new;
2783 foreach (sort keys %ctags_lc) {
2784 # Pad the title with spaces so that the cloud looks
2785 # less crammed.
2786 my $title = $ctags_lc{$_}->{topname};
2787 $title =~ s/ /&nbsp;/g;
2788 $title =~ s/^/&nbsp;/g;
2789 $title =~ s/$/&nbsp;/g;
2790 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2792 } else {
2793 $cloud = \%ctags_lc;
2795 $cloud;
2798 sub git_show_project_tagcloud {
2799 my ($cloud, $count) = @_;
2800 print STDERR ref($cloud)."..\n";
2801 if (ref $cloud eq 'HTML::TagCloud') {
2802 return $cloud->html_and_css($count);
2803 } else {
2804 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2805 return '<p align="center">' . join (', ', map {
2806 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2807 } splice(@tags, 0, $count)) . '</p>';
2811 sub git_get_project_url_list {
2812 my $path = shift;
2814 $git_dir = "$projectroot/$path";
2815 open my $fd, '<', "$git_dir/cloneurl"
2816 or return wantarray ?
2817 @{ config_to_multi(git_get_project_config('url')) } :
2818 config_to_multi(git_get_project_config('url'));
2819 my @git_project_url_list = map { chomp; $_ } <$fd>;
2820 close $fd;
2822 return wantarray ? @git_project_url_list : \@git_project_url_list;
2825 sub git_get_projects_list {
2826 my ($filter) = @_;
2827 my @list;
2829 $filter ||= '';
2830 $filter =~ s/\.git$//;
2832 my $check_forks = gitweb_check_feature('forks');
2834 if (-d $projects_list) {
2835 # search in directory
2836 my $dir = $projects_list . ($filter ? "/$filter" : '');
2837 # remove the trailing "/"
2838 $dir =~ s!/+$!!;
2839 my $pfxlen = length("$dir");
2840 my $pfxdepth = ($dir =~ tr!/!!);
2842 File::Find::find({
2843 follow_fast => 1, # follow symbolic links
2844 follow_skip => 2, # ignore duplicates
2845 dangling_symlinks => 0, # ignore dangling symlinks, silently
2846 wanted => sub {
2847 # global variables
2848 our $project_maxdepth;
2849 our $projectroot;
2850 # skip project-list toplevel, if we get it.
2851 return if (m!^[/.]$!);
2852 # only directories can be git repositories
2853 return unless (-d $_);
2854 # don't traverse too deep (Find is super slow on os x)
2855 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2856 $File::Find::prune = 1;
2857 return;
2860 my $subdir = substr($File::Find::name, $pfxlen + 1);
2861 # we check related file in $projectroot
2862 my $path = ($filter ? "$filter/" : '') . $subdir;
2863 if (check_export_ok("$projectroot/$path")) {
2864 push @list, { path => $path };
2865 $File::Find::prune = 1;
2868 }, "$dir");
2870 } elsif (-f $projects_list) {
2871 # read from file(url-encoded):
2872 # 'git%2Fgit.git Linus+Torvalds'
2873 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2874 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2875 my %paths;
2876 open my $fd, '<', $projects_list or return;
2877 PROJECT:
2878 while (my $line = <$fd>) {
2879 chomp $line;
2880 my ($path, $owner) = split ' ', $line;
2881 $path = unescape($path);
2882 $owner = unescape($owner);
2883 if (!defined $path) {
2884 next;
2886 if ($filter ne '') {
2887 # looking for forks;
2888 my $pfx = substr($path, 0, length($filter));
2889 if ($pfx ne $filter) {
2890 next PROJECT;
2892 my $sfx = substr($path, length($filter));
2893 if ($sfx !~ /^\/.*\.git$/) {
2894 next PROJECT;
2896 } elsif ($check_forks) {
2897 PATH:
2898 foreach my $filter (keys %paths) {
2899 # looking for forks;
2900 my $pfx = substr($path, 0, length($filter));
2901 if ($pfx ne $filter) {
2902 next PATH;
2904 my $sfx = substr($path, length($filter));
2905 if ($sfx !~ /^\/.*\.git$/) {
2906 next PATH;
2908 # is a fork, don't include it in
2909 # the list
2910 next PROJECT;
2913 if (check_export_ok("$projectroot/$path")) {
2914 my $pr = {
2915 path => $path,
2916 owner => to_utf8($owner),
2918 push @list, $pr;
2919 (my $forks_path = $path) =~ s/\.git$//;
2920 $paths{$forks_path}++;
2923 close $fd;
2925 return @list;
2928 our $gitweb_project_owner = undef;
2929 sub git_get_project_list_from_file {
2931 return if (defined $gitweb_project_owner);
2933 $gitweb_project_owner = {};
2934 # read from file (url-encoded):
2935 # 'git%2Fgit.git Linus+Torvalds'
2936 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2937 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2938 if (-f $projects_list) {
2939 open(my $fd, '<', $projects_list);
2940 while (my $line = <$fd>) {
2941 chomp $line;
2942 my ($pr, $ow) = split ' ', $line;
2943 $pr = unescape($pr);
2944 $ow = unescape($ow);
2945 $gitweb_project_owner->{$pr} = to_utf8($ow);
2947 close $fd;
2951 sub git_get_project_owner {
2952 my $project = shift;
2953 my $owner;
2955 return undef unless $project;
2956 $git_dir = "$projectroot/$project";
2958 if (!defined $gitweb_project_owner) {
2959 git_get_project_list_from_file();
2962 if (exists $gitweb_project_owner->{$project}) {
2963 $owner = $gitweb_project_owner->{$project};
2965 if (!defined $owner){
2966 $owner = git_get_project_config('owner');
2968 if (!defined $owner) {
2969 $owner = get_file_owner("$git_dir");
2972 return $owner;
2975 sub git_get_last_activity {
2976 my ($path) = @_;
2977 my $fd;
2979 $git_dir = "$projectroot/$path";
2980 open($fd, "-|", git_cmd(), 'for-each-ref',
2981 '--format=%(committer)',
2982 '--sort=-committerdate',
2983 '--count=1',
2984 'refs/heads') or return;
2985 my $most_recent = <$fd>;
2986 close $fd or return;
2987 if (defined $most_recent &&
2988 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2989 my $timestamp = $1;
2990 my $age = time - $timestamp;
2991 return ($age, age_string($age));
2993 return (undef, undef);
2996 sub git_get_references {
2997 my $type = shift || "";
2998 my %refs;
2999 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3000 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3001 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3002 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3003 or return;
3005 while (my $line = <$fd>) {
3006 chomp $line;
3007 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3008 if (defined $refs{$1}) {
3009 push @{$refs{$1}}, $2;
3010 } else {
3011 $refs{$1} = [ $2 ];
3015 close $fd or return;
3016 return \%refs;
3019 sub git_get_rev_name_tags {
3020 my $hash = shift || return undef;
3022 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3023 or return;
3024 my $name_rev = <$fd>;
3025 close $fd;
3027 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3028 return $1;
3029 } else {
3030 # catches also '$hash undefined' output
3031 return undef;
3035 ## ----------------------------------------------------------------------
3036 ## parse to hash functions
3038 sub parse_date {
3039 my $epoch = shift;
3040 my $tz = shift || "-0000";
3042 my %date;
3043 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3044 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3045 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3046 $date{'hour'} = $hour;
3047 $date{'minute'} = $min;
3048 $date{'mday'} = $mday;
3049 $date{'day'} = $days[$wday];
3050 $date{'month'} = $months[$mon];
3051 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3052 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3053 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3054 $mday, $months[$mon], $hour ,$min;
3055 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3056 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3058 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
3059 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
3060 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3061 $date{'hour_local'} = $hour;
3062 $date{'minute_local'} = $min;
3063 $date{'tz_local'} = $tz;
3064 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3065 1900+$year, $mon+1, $mday,
3066 $hour, $min, $sec, $tz);
3067 return %date;
3070 sub parse_tag {
3071 my $tag_id = shift;
3072 my %tag;
3073 my @comment;
3075 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3076 $tag{'id'} = $tag_id;
3077 while (my $line = <$fd>) {
3078 chomp $line;
3079 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3080 $tag{'object'} = $1;
3081 } elsif ($line =~ m/^type (.+)$/) {
3082 $tag{'type'} = $1;
3083 } elsif ($line =~ m/^tag (.+)$/) {
3084 $tag{'name'} = $1;
3085 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3086 $tag{'author'} = $1;
3087 $tag{'author_epoch'} = $2;
3088 $tag{'author_tz'} = $3;
3089 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3090 $tag{'author_name'} = $1;
3091 $tag{'author_email'} = $2;
3092 } else {
3093 $tag{'author_name'} = $tag{'author'};
3095 } elsif ($line =~ m/--BEGIN/) {
3096 push @comment, $line;
3097 last;
3098 } elsif ($line eq "") {
3099 last;
3102 push @comment, <$fd>;
3103 $tag{'comment'} = \@comment;
3104 close $fd or return;
3105 if (!defined $tag{'name'}) {
3106 return
3108 return %tag
3111 sub parse_commit_text {
3112 my ($commit_text, $withparents) = @_;
3113 my @commit_lines = split '\n', $commit_text;
3114 my %co;
3116 pop @commit_lines; # Remove '\0'
3118 if (! @commit_lines) {
3119 return;
3122 my $header = shift @commit_lines;
3123 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3124 return;
3126 ($co{'id'}, my @parents) = split ' ', $header;
3127 while (my $line = shift @commit_lines) {
3128 last if $line eq "\n";
3129 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3130 $co{'tree'} = $1;
3131 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3132 push @parents, $1;
3133 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3134 $co{'author'} = to_utf8($1);
3135 $co{'author_epoch'} = $2;
3136 $co{'author_tz'} = $3;
3137 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3138 $co{'author_name'} = $1;
3139 $co{'author_email'} = $2;
3140 } else {
3141 $co{'author_name'} = $co{'author'};
3143 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3144 $co{'committer'} = to_utf8($1);
3145 $co{'committer_epoch'} = $2;
3146 $co{'committer_tz'} = $3;
3147 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3148 $co{'committer_name'} = $1;
3149 $co{'committer_email'} = $2;
3150 } else {
3151 $co{'committer_name'} = $co{'committer'};
3155 if (!defined $co{'tree'}) {
3156 return;
3158 $co{'parents'} = \@parents;
3159 $co{'parent'} = $parents[0];
3161 foreach my $title (@commit_lines) {
3162 $title =~ s/^ //;
3163 if ($title ne "") {
3164 $co{'title'} = chop_str($title, 80, 5);
3165 # remove leading stuff of merges to make the interesting part visible
3166 if (length($title) > 50) {
3167 $title =~ s/^Automatic //;
3168 $title =~ s/^merge (of|with) /Merge ... /i;
3169 if (length($title) > 50) {
3170 $title =~ s/(http|rsync):\/\///;
3172 if (length($title) > 50) {
3173 $title =~ s/(master|www|rsync)\.//;
3175 if (length($title) > 50) {
3176 $title =~ s/kernel.org:?//;
3178 if (length($title) > 50) {
3179 $title =~ s/\/pub\/scm//;
3182 $co{'title_short'} = chop_str($title, 50, 5);
3183 last;
3186 if (! defined $co{'title'} || $co{'title'} eq "") {
3187 $co{'title'} = $co{'title_short'} = '(no commit message)';
3189 # remove added spaces
3190 foreach my $line (@commit_lines) {
3191 $line =~ s/^ //;
3193 $co{'comment'} = \@commit_lines;
3195 my $age = time - $co{'committer_epoch'};
3196 $co{'age'} = $age;
3197 $co{'age_string'} = age_string($age);
3198 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3199 if ($age > 60*60*24*7*2) {
3200 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3201 $co{'age_string_age'} = $co{'age_string'};
3202 } else {
3203 $co{'age_string_date'} = $co{'age_string'};
3204 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3206 return %co;
3209 sub parse_commit {
3210 my ($commit_id) = @_;
3211 my %co;
3213 local $/ = "\0";
3215 open my $fd, "-|", git_cmd(), "rev-list",
3216 "--parents",
3217 "--header",
3218 "--max-count=1",
3219 $commit_id,
3220 "--",
3221 or die_error(500, "Open git-rev-list failed");
3222 %co = parse_commit_text(<$fd>, 1);
3223 close $fd;
3225 return %co;
3228 sub parse_commits {
3229 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3230 my @cos;
3232 $maxcount ||= 1;
3233 $skip ||= 0;
3235 local $/ = "\0";
3237 open my $fd, "-|", git_cmd(), "rev-list",
3238 "--header",
3239 @args,
3240 ("--max-count=" . $maxcount),
3241 ("--skip=" . $skip),
3242 @extra_options,
3243 $commit_id,
3244 "--",
3245 ($filename ? ($filename) : ())
3246 or die_error(500, "Open git-rev-list failed");
3247 while (my $line = <$fd>) {
3248 my %co = parse_commit_text($line);
3249 push @cos, \%co;
3251 close $fd;
3253 return wantarray ? @cos : \@cos;
3256 # parse line of git-diff-tree "raw" output
3257 sub parse_difftree_raw_line {
3258 my $line = shift;
3259 my %res;
3261 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3262 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3263 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3264 $res{'from_mode'} = $1;
3265 $res{'to_mode'} = $2;
3266 $res{'from_id'} = $3;
3267 $res{'to_id'} = $4;
3268 $res{'status'} = $5;
3269 $res{'similarity'} = $6;
3270 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3271 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3272 } else {
3273 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3276 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3277 # combined diff (for merge commit)
3278 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3279 $res{'nparents'} = length($1);
3280 $res{'from_mode'} = [ split(' ', $2) ];
3281 $res{'to_mode'} = pop @{$res{'from_mode'}};
3282 $res{'from_id'} = [ split(' ', $3) ];
3283 $res{'to_id'} = pop @{$res{'from_id'}};
3284 $res{'status'} = [ split('', $4) ];
3285 $res{'to_file'} = unquote($5);
3287 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3288 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3289 $res{'commit'} = $1;
3292 return wantarray ? %res : \%res;
3295 # wrapper: return parsed line of git-diff-tree "raw" output
3296 # (the argument might be raw line, or parsed info)
3297 sub parsed_difftree_line {
3298 my $line_or_ref = shift;
3300 if (ref($line_or_ref) eq "HASH") {
3301 # pre-parsed (or generated by hand)
3302 return $line_or_ref;
3303 } else {
3304 return parse_difftree_raw_line($line_or_ref);
3308 # parse line of git-ls-tree output
3309 sub parse_ls_tree_line {
3310 my $line = shift;
3311 my %opts = @_;
3312 my %res;
3314 if ($opts{'-l'}) {
3315 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3316 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3318 $res{'mode'} = $1;
3319 $res{'type'} = $2;
3320 $res{'hash'} = $3;
3321 $res{'size'} = $4;
3322 if ($opts{'-z'}) {
3323 $res{'name'} = $5;
3324 } else {
3325 $res{'name'} = unquote($5);
3327 } else {
3328 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3329 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3331 $res{'mode'} = $1;
3332 $res{'type'} = $2;
3333 $res{'hash'} = $3;
3334 if ($opts{'-z'}) {
3335 $res{'name'} = $4;
3336 } else {
3337 $res{'name'} = unquote($4);
3341 return wantarray ? %res : \%res;
3344 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3345 sub parse_from_to_diffinfo {
3346 my ($diffinfo, $from, $to, @parents) = @_;
3348 if ($diffinfo->{'nparents'}) {
3349 # combined diff
3350 $from->{'file'} = [];
3351 $from->{'href'} = [];
3352 fill_from_file_info($diffinfo, @parents)
3353 unless exists $diffinfo->{'from_file'};
3354 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3355 $from->{'file'}[$i] =
3356 defined $diffinfo->{'from_file'}[$i] ?
3357 $diffinfo->{'from_file'}[$i] :
3358 $diffinfo->{'to_file'};
3359 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3360 $from->{'href'}[$i] = href(action=>"blob",
3361 hash_base=>$parents[$i],
3362 hash=>$diffinfo->{'from_id'}[$i],
3363 file_name=>$from->{'file'}[$i]);
3364 } else {
3365 $from->{'href'}[$i] = undef;
3368 } else {
3369 # ordinary (not combined) diff
3370 $from->{'file'} = $diffinfo->{'from_file'};
3371 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3372 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3373 hash=>$diffinfo->{'from_id'},
3374 file_name=>$from->{'file'});
3375 } else {
3376 delete $from->{'href'};
3380 $to->{'file'} = $diffinfo->{'to_file'};
3381 if (!is_deleted($diffinfo)) { # file exists in result
3382 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3383 hash=>$diffinfo->{'to_id'},
3384 file_name=>$to->{'file'});
3385 } else {
3386 delete $to->{'href'};
3390 ## ......................................................................
3391 ## parse to array of hashes functions
3393 sub git_get_heads_list {
3394 my $limit = shift;
3395 my @headslist;
3397 open my $fd, '-|', git_cmd(), 'for-each-ref',
3398 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3399 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3400 'refs/heads'
3401 or return;
3402 while (my $line = <$fd>) {
3403 my %ref_item;
3405 chomp $line;
3406 my ($refinfo, $committerinfo) = split(/\0/, $line);
3407 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3408 my ($committer, $epoch, $tz) =
3409 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3410 $ref_item{'fullname'} = $name;
3411 $name =~ s!^refs/heads/!!;
3413 $ref_item{'name'} = $name;
3414 $ref_item{'id'} = $hash;
3415 $ref_item{'title'} = $title || '(no commit message)';
3416 $ref_item{'epoch'} = $epoch;
3417 if ($epoch) {
3418 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3419 } else {
3420 $ref_item{'age'} = "unknown";
3423 push @headslist, \%ref_item;
3425 close $fd;
3427 return wantarray ? @headslist : \@headslist;
3430 sub git_get_tags_list {
3431 my $limit = shift;
3432 my @tagslist;
3434 open my $fd, '-|', git_cmd(), 'for-each-ref',
3435 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3436 '--format=%(objectname) %(objecttype) %(refname) '.
3437 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3438 'refs/tags'
3439 or return;
3440 while (my $line = <$fd>) {
3441 my %ref_item;
3443 chomp $line;
3444 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3445 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3446 my ($creator, $epoch, $tz) =
3447 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3448 $ref_item{'fullname'} = $name;
3449 $name =~ s!^refs/tags/!!;
3451 $ref_item{'type'} = $type;
3452 $ref_item{'id'} = $id;
3453 $ref_item{'name'} = $name;
3454 if ($type eq "tag") {
3455 $ref_item{'subject'} = $title;
3456 $ref_item{'reftype'} = $reftype;
3457 $ref_item{'refid'} = $refid;
3458 } else {
3459 $ref_item{'reftype'} = $type;
3460 $ref_item{'refid'} = $id;
3463 if ($type eq "tag" || $type eq "commit") {
3464 $ref_item{'epoch'} = $epoch;
3465 if ($epoch) {
3466 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3467 } else {
3468 $ref_item{'age'} = "unknown";
3472 push @tagslist, \%ref_item;
3474 close $fd;
3476 return wantarray ? @tagslist : \@tagslist;
3479 ## ----------------------------------------------------------------------
3480 ## filesystem-related functions
3482 sub get_file_owner {
3483 my $path = shift;
3485 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3486 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3487 if (!defined $gcos) {
3488 return undef;
3490 my $owner = $gcos;
3491 $owner =~ s/[,;].*$//;
3492 return to_utf8($owner);
3495 # assume that file exists
3496 sub insert_file {
3497 my $filename = shift;
3499 open my $fd, '<', $filename;
3500 print map { to_utf8($_) } <$fd>;
3501 close $fd;
3504 ## ......................................................................
3505 ## mimetype related functions
3507 sub mimetype_guess_file {
3508 my $filename = shift;
3509 my $mimemap = shift;
3510 -r $mimemap or return undef;
3512 my %mimemap;
3513 open(my $mh, '<', $mimemap) or return undef;
3514 while (<$mh>) {
3515 next if m/^#/; # skip comments
3516 my ($mimetype, $exts) = split(/\t+/);
3517 if (defined $exts) {
3518 my @exts = split(/\s+/, $exts);
3519 foreach my $ext (@exts) {
3520 $mimemap{$ext} = $mimetype;
3524 close($mh);
3526 $filename =~ /\.([^.]*)$/;
3527 return $mimemap{$1};
3530 sub mimetype_guess {
3531 my $filename = shift;
3532 my $mime;
3533 $filename =~ /\./ or return undef;
3535 if ($mimetypes_file) {
3536 my $file = $mimetypes_file;
3537 if ($file !~ m!^/!) { # if it is relative path
3538 # it is relative to project
3539 $file = "$projectroot/$project/$file";
3541 $mime = mimetype_guess_file($filename, $file);
3543 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3544 return $mime;
3547 sub blob_mimetype {
3548 my $fd = shift;
3549 my $filename = shift;
3551 if ($filename) {
3552 my $mime = mimetype_guess($filename);
3553 $mime and return $mime;
3556 # just in case
3557 return $default_blob_plain_mimetype unless $fd;
3559 if (-T $fd) {
3560 return 'text/plain';
3561 } elsif (! $filename) {
3562 return 'application/octet-stream';
3563 } elsif ($filename =~ m/\.png$/i) {
3564 return 'image/png';
3565 } elsif ($filename =~ m/\.gif$/i) {
3566 return 'image/gif';
3567 } elsif ($filename =~ m/\.jpe?g$/i) {
3568 return 'image/jpeg';
3569 } else {
3570 return 'application/octet-stream';
3574 sub blob_contenttype {
3575 my ($fd, $file_name, $type) = @_;
3577 $type ||= blob_mimetype($fd, $file_name);
3578 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3579 $type .= "; charset=$default_text_plain_charset";
3582 return $type;
3585 # guess file syntax for syntax highlighting; return undef if no highlighting
3586 # the name of syntax can (in the future) depend on syntax highlighter used
3587 sub guess_file_syntax {
3588 my ($highlight, $mimetype, $file_name) = @_;
3589 return undef unless ($highlight && defined $file_name);
3590 my $basename = basename($file_name, '.in');
3591 return $highlight_basename{$basename}
3592 if exists $highlight_basename{$basename};
3594 $basename =~ /\.([^.]*)$/;
3595 my $ext = $1 or return undef;
3596 return $highlight_ext{$ext}
3597 if exists $highlight_ext{$ext};
3599 return undef;
3602 # run highlighter and return FD of its output,
3603 # or return original FD if no highlighting
3604 sub run_highlighter {
3605 my ($fd, $highlight, $syntax) = @_;
3606 return $fd unless ($highlight && defined $syntax);
3608 close $fd
3609 or die_error(404, "Reading blob failed");
3610 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3611 quote_command($highlight_bin).
3612 " --xhtml --fragment --syntax $syntax |"
3613 or die_error(500, "Couldn't open file or run syntax highlighter");
3614 return $fd;
3617 ## ======================================================================
3618 ## functions printing HTML: header, footer, error page
3620 sub get_page_title {
3621 my $title = to_utf8($site_name);
3623 return $title unless (defined $project);
3624 $title .= " - " . to_utf8($project);
3626 return $title unless (defined $action);
3627 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3629 return $title unless (defined $file_name);
3630 $title .= " - " . esc_path($file_name);
3631 if ($action eq "tree" && $file_name !~ m|/$|) {
3632 $title .= "/";
3635 return $title;
3638 # creates "Generating..." page when caching enabled and not in cache
3639 sub git_generating_data_html {
3640 my ($cache, $key, $lock_fh) = @_;
3642 # whitelist of actions that should get "Generating..." page
3643 if (!action_outputs_html($action) ||
3644 browser_is_robot()) {
3645 return;
3648 # Initial delay
3649 if ($generating_options{'startup_delay'} > 0) {
3650 eval {
3651 local $SIG{ALRM} = sub { die "alarm clock restart\n" }; # NB: \n required
3652 alarm $generating_options{'startup_delay'};
3653 flock($lock_fh, LOCK_SH); # blocking readers lock
3654 alarm 0;
3656 if ($@) {
3657 # propagate unexpected errors
3658 die $@ if $@ !~ /alarm clock restart/;
3659 } else {
3660 # we got response within 'startup_delay' timeout
3661 return;
3665 my $title = "[Generating...] " . get_page_title();
3666 # TODO: the following line of code duplicates the one
3667 # in git_header_html, and it should probably be refactored.
3668 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3670 # Use the trick that 'refresh' HTTP header equivalent (set via http-equiv)
3671 # with timeout of 0 seconds would redirect as soon as page is finished.
3672 # It assumes that browser would display partially received page.
3673 # This "Generating..." redirect page should not be cached (externally).
3674 my %no_cache = (
3675 # HTTP/1.0
3676 -Pragma => 'no-cache',
3677 # HTTP/1.1
3678 -Cache_Control => join(', ', qw(private no-cache no-store must-revalidate
3679 max-age=0 pre-check=0 post-check=0)),
3681 print STDOUT $cgi->header(-type => 'text/html', -charset => 'utf-8',
3682 -status=> '200 OK', -expires => 'now',
3683 %no_cache);
3684 print STDOUT <<"EOF";
3685 <?xml version="1.0" encoding="utf-8"?>
3686 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3687 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3688 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3689 <!-- git web interface version $version -->
3690 <!-- git core binaries version $git_version -->
3691 <head>
3692 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
3693 <meta http-equiv="refresh" content="0" />
3694 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version" />
3695 <meta name="robots" content="noindex, nofollow" />
3696 <title>$title</title>
3697 </head>
3698 <body>
3701 local $| = 1; # autoflush
3702 print STDOUT 'Generating...';
3704 my $total_time = 0;
3705 my $interval = $generating_options{'print_interval'} || 1;
3706 my $timeout = $generating_options{'timeout'};
3707 my $alarm_handler = sub {
3708 local $! = 1;
3709 print STDOUT '.';
3710 $total_time += $interval;
3711 if ($total_time > $timeout) {
3712 die "timeout\n";
3715 eval {
3716 local $SIG{ALRM} = $alarm_handler;
3717 Time::HiRes::alarm($interval, $interval);
3718 my $lock_acquired;
3719 do {
3720 # loop is needed here because SIGALRM (from 'alarm')
3721 # can interrupt process of acquiring lock
3722 $lock_acquired = flock($lock_fh, LOCK_SH); # blocking readers lock
3723 } until ($lock_acquired);
3724 alarm 0;
3726 # It doesn't really matter if we got lock, or timed-out
3727 # but we should re-throw unknown (unexpected) errors
3728 die $@ if ($@ and $@ !~ /timeout/);
3730 print STDOUT <<"EOF";
3732 </body>
3733 </html>
3736 # after refresh web browser would reload page and send new request
3737 goto DONE_GITWEB;
3738 #exit 0;
3739 #return;
3742 sub git_header_html {
3743 my $status = shift || "200 OK";
3744 my $expires = shift;
3745 my %opts = @_;
3747 my $title = get_page_title();
3748 my $content_type;
3749 # require explicit support from the UA if we are to send the page as
3750 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3751 # we have to do this because MSIE sometimes globs '*/*', pretending to
3752 # support xhtml+xml but choking when it gets what it asked for.
3753 # Disable content-type negotiation when caching (use mimetype good for all).
3754 if (!$caching_enabled &&
3755 defined $cgi->http('HTTP_ACCEPT') &&
3756 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3757 $cgi->Accept('application/xhtml+xml') != 0) {
3758 $content_type = 'application/xhtml+xml';
3759 } else {
3760 $content_type = 'text/html';
3762 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3763 -status=> $status, -expires => $expires)
3764 unless ($opts{'-no_http_header'});
3765 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3766 print <<EOF;
3767 <?xml version="1.0" encoding="utf-8"?>
3768 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3769 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3770 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3771 <!-- git core binaries version $git_version -->
3772 <head>
3773 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3774 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3775 <meta name="robots" content="index, nofollow"/>
3776 <title>$title</title>
3778 # the stylesheet, favicon etc urls won't work correctly with path_info
3779 # unless we set the appropriate base URL
3780 # if caching is enabled we can get it from cache for path_info when it
3781 # is generated without path_info
3782 if ($ENV{'PATH_INFO'} || $caching_enabled) {
3783 print "<base href=\"".esc_url($base_url)."\" />\n";
3785 # print out each stylesheet that exist, providing backwards capability
3786 # for those people who defined $stylesheet in a config file
3787 if (defined $stylesheet) {
3788 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3789 } else {
3790 foreach my $stylesheet (@stylesheets) {
3791 next unless $stylesheet;
3792 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3795 if (defined $project) {
3796 my %href_params = get_feed_info();
3797 if (!exists $href_params{'-title'}) {
3798 $href_params{'-title'} = 'log';
3801 foreach my $format qw(RSS Atom) {
3802 my $type = lc($format);
3803 my %link_attr = (
3804 '-rel' => 'alternate',
3805 '-title' => "$project - $href_params{'-title'} - $format feed",
3806 '-type' => "application/$type+xml"
3809 $href_params{'action'} = $type;
3810 $link_attr{'-href'} = href(%href_params);
3811 print "<link ".
3812 "rel=\"$link_attr{'-rel'}\" ".
3813 "title=\"$link_attr{'-title'}\" ".
3814 "href=\"$link_attr{'-href'}\" ".
3815 "type=\"$link_attr{'-type'}\" ".
3816 "/>\n";
3818 $href_params{'extra_options'} = '--no-merges';
3819 $link_attr{'-href'} = href(%href_params);
3820 $link_attr{'-title'} .= ' (no merges)';
3821 print "<link ".
3822 "rel=\"$link_attr{'-rel'}\" ".
3823 "title=\"$link_attr{'-title'}\" ".
3824 "href=\"$link_attr{'-href'}\" ".
3825 "type=\"$link_attr{'-type'}\" ".
3826 "/>\n";
3829 } else {
3830 printf('<link rel="alternate" title="%s projects list" '.
3831 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3832 $site_name, href(project=>undef, action=>"project_index"));
3833 printf('<link rel="alternate" title="%s projects feeds" '.
3834 'href="%s" type="text/x-opml" />'."\n",
3835 $site_name, href(project=>undef, action=>"opml"));
3837 if (defined $favicon) {
3838 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3841 print "</head>\n" .
3842 "<body>\n";
3844 if (defined $site_header && -f $site_header) {
3845 insert_file($site_header);
3848 print "<div class=\"page_header\">\n" .
3849 $cgi->a({-href => esc_url($logo_url),
3850 -title => $logo_label},
3851 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3852 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3853 if (defined $project) {
3854 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3855 if (defined $action) {
3856 print " / $action";
3858 print "\n";
3860 print "</div>\n";
3862 my $have_search = gitweb_check_feature('search');
3863 if (defined $project && $have_search) {
3864 if (!defined $searchtext) {
3865 $searchtext = "";
3867 my $search_hash;
3868 if (defined $hash_base) {
3869 $search_hash = $hash_base;
3870 } elsif (defined $hash) {
3871 $search_hash = $hash;
3872 } else {
3873 $search_hash = "HEAD";
3875 my $action = $my_uri;
3876 my $use_pathinfo = gitweb_check_feature('pathinfo');
3877 if ($use_pathinfo) {
3878 $action .= "/".esc_url($project);
3880 print $cgi->startform(-method => "get", -action => $action) .
3881 "<div class=\"search\">\n" .
3882 (!$use_pathinfo &&
3883 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3884 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3885 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3886 $cgi->popup_menu(-name => 'st', -default => 'commit',
3887 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3888 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3889 " search:\n",
3890 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3891 "<span title=\"Extended regular expression\">" .
3892 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3893 -checked => $search_use_regexp) .
3894 "</span>" .
3895 "</div>" .
3896 $cgi->end_form() . "\n";
3900 sub git_footer_html {
3901 my $feed_class = 'rss_logo';
3903 print "<div class=\"page_footer\">\n";
3904 if (defined $project) {
3905 my $descr = git_get_project_description($project);
3906 if (defined $descr) {
3907 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3910 my %href_params = get_feed_info();
3911 if (!%href_params) {
3912 $feed_class .= ' generic';
3914 $href_params{'-title'} ||= 'log';
3916 foreach my $format qw(RSS Atom) {
3917 $href_params{'action'} = lc($format);
3918 print $cgi->a({-href => href(%href_params),
3919 -title => "$href_params{'-title'} $format feed",
3920 -class => $feed_class}, $format)."\n";
3923 } else {
3924 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3925 -class => $feed_class}, "OPML") . " ";
3926 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3927 -class => $feed_class}, "TXT") . "\n";
3929 print "</div>\n"; # class="page_footer"
3931 # timing info doesn't make much sense with output (response) caching,
3932 # so when caching is enabled gitweb prints the time of page generation
3933 if ((defined $t0 || $caching_enabled) &&
3934 gitweb_check_feature('timed')) {
3935 print "<div id=\"generating_info\">\n";
3936 if ($caching_enabled) {
3937 print 'This page was generated at '.
3938 gmtime( time() )." GMT\n";
3939 } else {
3940 print 'This page took '.
3941 '<span id="generating_time" class="time_span">'.
3942 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3943 ' seconds </span>'.
3944 ' and '.
3945 '<span id="generating_cmd">'.
3946 $number_of_git_cmds.
3947 '</span> git commands '.
3948 " to generate.\n";
3950 print "</div>\n"; # class="page_footer"
3953 if (defined $site_footer && -f $site_footer) {
3954 insert_file($site_footer);
3957 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3958 if (!$caching_enabled &&
3959 defined $action && $action eq 'blame_incremental') {
3960 print qq!<script type="text/javascript">\n!.
3961 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3962 qq! "!. href() .qq!");\n!.
3963 qq!</script>\n!;
3964 } elsif (gitweb_check_feature('javascript-actions')) {
3965 print qq!<script type="text/javascript">\n!.
3966 qq!window.onload = fixLinks;\n!.
3967 qq!</script>\n!;
3970 print "</body>\n" .
3971 "</html>";
3974 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3975 # Example: die_error(404, 'Hash not found')
3976 # By convention, use the following status codes (as defined in RFC 2616):
3977 # 400: Invalid or missing CGI parameters, or
3978 # requested object exists but has wrong type.
3979 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3980 # this server or project.
3981 # 404: Requested object/revision/project doesn't exist.
3982 # 500: The server isn't configured properly, or
3983 # an internal error occurred (e.g. failed assertions caused by bugs), or
3984 # an unknown error occurred (e.g. the git binary died unexpectedly).
3985 # 503: The server is currently unavailable (because it is overloaded,
3986 # or down for maintenance). Generally, this is a temporary state.
3987 sub die_error {
3988 my $status = shift || 500;
3989 my $error = esc_html(shift) || "Internal Server Error";
3990 my $extra = shift;
3991 my %opts = @_;
3993 my %http_responses = (
3994 400 => '400 Bad Request',
3995 403 => '403 Forbidden',
3996 404 => '404 Not Found',
3997 500 => '500 Internal Server Error',
3998 503 => '503 Service Unavailable',
4001 # Do not cache error pages
4002 capture_stop($cache, $capture) if ($capture && $caching_enabled);
4004 git_header_html($http_responses{$status}, undef, %opts);
4005 print <<EOF;
4006 <div class="page_body">
4007 <br /><br />
4008 $status - $error
4009 <br />
4011 if (defined $extra) {
4012 print "<hr />\n" .
4013 "$extra\n";
4015 print "</div>\n";
4017 git_footer_html();
4018 goto DONE_GITWEB
4019 unless ($opts{'-error_handler'});
4022 ## ----------------------------------------------------------------------
4023 ## functions printing or outputting HTML: navigation
4025 sub git_print_page_nav {
4026 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4027 $extra = '' if !defined $extra; # pager or formats
4029 my @navs = qw(summary shortlog log commit commitdiff tree);
4030 if ($suppress) {
4031 @navs = grep { $_ ne $suppress } @navs;
4034 my %arg = map { $_ => {action=>$_} } @navs;
4035 if (defined $head) {
4036 for (qw(commit commitdiff)) {
4037 $arg{$_}{'hash'} = $head;
4039 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4040 for (qw(shortlog log)) {
4041 $arg{$_}{'hash'} = $head;
4046 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4047 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4049 my @actions = gitweb_get_feature('actions');
4050 my %repl = (
4051 '%' => '%',
4052 'n' => $project, # project name
4053 'f' => $git_dir, # project path within filesystem
4054 'h' => $treehead || '', # current hash ('h' parameter)
4055 'b' => $treebase || '', # hash base ('hb' parameter)
4057 while (@actions) {
4058 my ($label, $link, $pos) = splice(@actions,0,3);
4059 # insert
4060 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4061 # munch munch
4062 $link =~ s/%([%nfhb])/$repl{$1}/g;
4063 $arg{$label}{'_href'} = $link;
4066 print "<div class=\"page_nav\">\n" .
4067 (join " | ",
4068 map { $_ eq $current ?
4069 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4070 } @navs);
4071 print "<br/>\n$extra<br/>\n" .
4072 "</div>\n";
4075 sub format_paging_nav {
4076 my ($action, $page, $has_next_link) = @_;
4077 my $paging_nav;
4080 if ($page > 0) {
4081 $paging_nav .=
4082 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4083 " &sdot; " .
4084 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4085 -accesskey => "p", -title => "Alt-p"}, "prev");
4086 } else {
4087 $paging_nav .= "first &sdot; prev";
4090 if ($has_next_link) {
4091 $paging_nav .= " &sdot; " .
4092 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4093 -accesskey => "n", -title => "Alt-n"}, "next");
4094 } else {
4095 $paging_nav .= " &sdot; next";
4098 return $paging_nav;
4101 ## ......................................................................
4102 ## functions printing or outputting HTML: div
4104 sub git_print_header_div {
4105 my ($action, $title, $hash, $hash_base) = @_;
4106 my %args = ();
4108 $args{'action'} = $action;
4109 $args{'hash'} = $hash if $hash;
4110 $args{'hash_base'} = $hash_base if $hash_base;
4112 print "<div class=\"header\">\n" .
4113 $cgi->a({-href => href(%args), -class => "title"},
4114 $title ? $title : $action) .
4115 "\n</div>\n";
4118 sub print_local_time {
4119 print format_local_time(@_);
4122 sub format_local_time {
4123 my $localtime = '';
4124 my %date = @_;
4125 if ($date{'hour_local'} < 6) {
4126 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4127 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4128 } else {
4129 $localtime .= sprintf(" (%02d:%02d %s)",
4130 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4133 return $localtime;
4136 # Outputs the author name and date in long form
4137 sub git_print_authorship {
4138 my $co = shift;
4139 my %opts = @_;
4140 my $tag = $opts{-tag} || 'div';
4141 my $author = $co->{'author_name'};
4143 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4144 print "<$tag class=\"author_date\">" .
4145 format_search_author($author, "author", esc_html($author)) .
4146 " [$ad{'rfc2822'}";
4147 print_local_time(%ad) if ($opts{-localtime});
4148 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
4149 . "</$tag>\n";
4152 # Outputs table rows containing the full author or committer information,
4153 # in the format expected for 'commit' view (& similar).
4154 # Parameters are a commit hash reference, followed by the list of people
4155 # to output information for. If the list is empty it defaults to both
4156 # author and committer.
4157 sub git_print_authorship_rows {
4158 my $co = shift;
4159 # too bad we can't use @people = @_ || ('author', 'committer')
4160 my @people = @_;
4161 @people = ('author', 'committer') unless @people;
4162 foreach my $who (@people) {
4163 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4164 print "<tr><td>$who</td><td>" .
4165 format_search_author($co->{"${who}_name"}, $who,
4166 esc_html($co->{"${who}_name"})) . " " .
4167 format_search_author($co->{"${who}_email"}, $who,
4168 esc_html("<" . $co->{"${who}_email"} . ">")) .
4169 "</td><td rowspan=\"2\">" .
4170 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4171 "</td></tr>\n" .
4172 "<tr>" .
4173 "<td></td><td> $wd{'rfc2822'}";
4174 print_local_time(%wd);
4175 print "</td>" .
4176 "</tr>\n";
4180 sub git_print_page_path {
4181 my $name = shift;
4182 my $type = shift;
4183 my $hb = shift;
4186 print "<div class=\"page_path\">";
4187 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4188 -title => 'tree root'}, to_utf8("[$project]"));
4189 print " / ";
4190 if (defined $name) {
4191 my @dirname = split '/', $name;
4192 my $basename = pop @dirname;
4193 my $fullname = '';
4195 foreach my $dir (@dirname) {
4196 $fullname .= ($fullname ? '/' : '') . $dir;
4197 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4198 hash_base=>$hb),
4199 -title => $fullname}, esc_path($dir));
4200 print " / ";
4202 if (defined $type && $type eq 'blob') {
4203 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4204 hash_base=>$hb),
4205 -title => $name}, esc_path($basename));
4206 } elsif (defined $type && $type eq 'tree') {
4207 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4208 hash_base=>$hb),
4209 -title => $name}, esc_path($basename));
4210 print " / ";
4211 } else {
4212 print esc_path($basename);
4215 print "<br/></div>\n";
4218 sub git_print_log {
4219 my $log = shift;
4220 my %opts = @_;
4222 if ($opts{'-remove_title'}) {
4223 # remove title, i.e. first line of log
4224 shift @$log;
4226 # remove leading empty lines
4227 while (defined $log->[0] && $log->[0] eq "") {
4228 shift @$log;
4231 # print log
4232 my $signoff = 0;
4233 my $empty = 0;
4234 foreach my $line (@$log) {
4235 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4236 $signoff = 1;
4237 $empty = 0;
4238 if (! $opts{'-remove_signoff'}) {
4239 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4240 next;
4241 } else {
4242 # remove signoff lines
4243 next;
4245 } else {
4246 $signoff = 0;
4249 # print only one empty line
4250 # do not print empty line after signoff
4251 if ($line eq "") {
4252 next if ($empty || $signoff);
4253 $empty = 1;
4254 } else {
4255 $empty = 0;
4258 print format_log_line_html($line) . "<br/>\n";
4261 if ($opts{'-final_empty_line'}) {
4262 # end with single empty line
4263 print "<br/>\n" unless $empty;
4267 # return link target (what link points to)
4268 sub git_get_link_target {
4269 my $hash = shift;
4270 my $link_target;
4272 # read link
4273 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4274 or return;
4276 local $/ = undef;
4277 $link_target = <$fd>;
4279 close $fd
4280 or return;
4282 return $link_target;
4285 # given link target, and the directory (basedir) the link is in,
4286 # return target of link relative to top directory (top tree);
4287 # return undef if it is not possible (including absolute links).
4288 sub normalize_link_target {
4289 my ($link_target, $basedir) = @_;
4291 # absolute symlinks (beginning with '/') cannot be normalized
4292 return if (substr($link_target, 0, 1) eq '/');
4294 # normalize link target to path from top (root) tree (dir)
4295 my $path;
4296 if ($basedir) {
4297 $path = $basedir . '/' . $link_target;
4298 } else {
4299 # we are in top (root) tree (dir)
4300 $path = $link_target;
4303 # remove //, /./, and /../
4304 my @path_parts;
4305 foreach my $part (split('/', $path)) {
4306 # discard '.' and ''
4307 next if (!$part || $part eq '.');
4308 # handle '..'
4309 if ($part eq '..') {
4310 if (@path_parts) {
4311 pop @path_parts;
4312 } else {
4313 # link leads outside repository (outside top dir)
4314 return;
4316 } else {
4317 push @path_parts, $part;
4320 $path = join('/', @path_parts);
4322 return $path;
4325 # print tree entry (row of git_tree), but without encompassing <tr> element
4326 sub git_print_tree_entry {
4327 my ($t, $basedir, $hash_base, $have_blame) = @_;
4329 my %base_key = ();
4330 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4332 # The format of a table row is: mode list link. Where mode is
4333 # the mode of the entry, list is the name of the entry, an href,
4334 # and link is the action links of the entry.
4336 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4337 if (exists $t->{'size'}) {
4338 print "<td class=\"size\">$t->{'size'}</td>\n";
4340 if ($t->{'type'} eq "blob") {
4341 print "<td class=\"list\">" .
4342 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4343 file_name=>"$basedir$t->{'name'}", %base_key),
4344 -class => "list"}, esc_path($t->{'name'}));
4345 if (S_ISLNK(oct $t->{'mode'})) {
4346 my $link_target = git_get_link_target($t->{'hash'});
4347 if ($link_target) {
4348 my $norm_target = normalize_link_target($link_target, $basedir);
4349 if (defined $norm_target) {
4350 print " -> " .
4351 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4352 file_name=>$norm_target),
4353 -title => $norm_target}, esc_path($link_target));
4354 } else {
4355 print " -> " . esc_path($link_target);
4359 print "</td>\n";
4360 print "<td class=\"link\">";
4361 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4362 file_name=>"$basedir$t->{'name'}", %base_key)},
4363 "blob");
4364 if ($have_blame) {
4365 print " | " .
4366 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4367 file_name=>"$basedir$t->{'name'}", %base_key)},
4368 "blame");
4370 if (defined $hash_base) {
4371 print " | " .
4372 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4373 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4374 "history");
4376 print " | " .
4377 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4378 file_name=>"$basedir$t->{'name'}")},
4379 "raw");
4380 print "</td>\n";
4382 } elsif ($t->{'type'} eq "tree") {
4383 print "<td class=\"list\">";
4384 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4385 file_name=>"$basedir$t->{'name'}",
4386 %base_key)},
4387 esc_path($t->{'name'}));
4388 print "</td>\n";
4389 print "<td class=\"link\">";
4390 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4391 file_name=>"$basedir$t->{'name'}",
4392 %base_key)},
4393 "tree");
4394 if (defined $hash_base) {
4395 print " | " .
4396 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4397 file_name=>"$basedir$t->{'name'}")},
4398 "history");
4400 print "</td>\n";
4401 } else {
4402 # unknown object: we can only present history for it
4403 # (this includes 'commit' object, i.e. submodule support)
4404 print "<td class=\"list\">" .
4405 esc_path($t->{'name'}) .
4406 "</td>\n";
4407 print "<td class=\"link\">";
4408 if (defined $hash_base) {
4409 print $cgi->a({-href => href(action=>"history",
4410 hash_base=>$hash_base,
4411 file_name=>"$basedir$t->{'name'}")},
4412 "history");
4414 print "</td>\n";
4418 ## ......................................................................
4419 ## functions printing large fragments of HTML
4421 # get pre-image filenames for merge (combined) diff
4422 sub fill_from_file_info {
4423 my ($diff, @parents) = @_;
4425 $diff->{'from_file'} = [ ];
4426 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4427 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4428 if ($diff->{'status'}[$i] eq 'R' ||
4429 $diff->{'status'}[$i] eq 'C') {
4430 $diff->{'from_file'}[$i] =
4431 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4435 return $diff;
4438 # is current raw difftree line of file deletion
4439 sub is_deleted {
4440 my $diffinfo = shift;
4442 return $diffinfo->{'to_id'} eq ('0' x 40);
4445 # does patch correspond to [previous] difftree raw line
4446 # $diffinfo - hashref of parsed raw diff format
4447 # $patchinfo - hashref of parsed patch diff format
4448 # (the same keys as in $diffinfo)
4449 sub is_patch_split {
4450 my ($diffinfo, $patchinfo) = @_;
4452 return defined $diffinfo && defined $patchinfo
4453 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4457 sub git_difftree_body {
4458 my ($difftree, $hash, @parents) = @_;
4459 my ($parent) = $parents[0];
4460 my $have_blame = gitweb_check_feature('blame');
4461 print "<div class=\"list_head\">\n";
4462 if ($#{$difftree} > 10) {
4463 print(($#{$difftree} + 1) . " files changed:\n");
4465 print "</div>\n";
4467 print "<table class=\"" .
4468 (@parents > 1 ? "combined " : "") .
4469 "diff_tree\">\n";
4471 # header only for combined diff in 'commitdiff' view
4472 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4473 if ($has_header) {
4474 # table header
4475 print "<thead><tr>\n" .
4476 "<th></th><th></th>\n"; # filename, patchN link
4477 for (my $i = 0; $i < @parents; $i++) {
4478 my $par = $parents[$i];
4479 print "<th>" .
4480 $cgi->a({-href => href(action=>"commitdiff",
4481 hash=>$hash, hash_parent=>$par),
4482 -title => 'commitdiff to parent number ' .
4483 ($i+1) . ': ' . substr($par,0,7)},
4484 $i+1) .
4485 "&nbsp;</th>\n";
4487 print "</tr></thead>\n<tbody>\n";
4490 my $alternate = 1;
4491 my $patchno = 0;
4492 foreach my $line (@{$difftree}) {
4493 my $diff = parsed_difftree_line($line);
4495 if ($alternate) {
4496 print "<tr class=\"dark\">\n";
4497 } else {
4498 print "<tr class=\"light\">\n";
4500 $alternate ^= 1;
4502 if (exists $diff->{'nparents'}) { # combined diff
4504 fill_from_file_info($diff, @parents)
4505 unless exists $diff->{'from_file'};
4507 if (!is_deleted($diff)) {
4508 # file exists in the result (child) commit
4509 print "<td>" .
4510 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4511 file_name=>$diff->{'to_file'},
4512 hash_base=>$hash),
4513 -class => "list"}, esc_path($diff->{'to_file'})) .
4514 "</td>\n";
4515 } else {
4516 print "<td>" .
4517 esc_path($diff->{'to_file'}) .
4518 "</td>\n";
4521 if ($action eq 'commitdiff') {
4522 # link to patch
4523 $patchno++;
4524 print "<td class=\"link\">" .
4525 $cgi->a({-href => "#patch$patchno"}, "patch") .
4526 " | " .
4527 "</td>\n";
4530 my $has_history = 0;
4531 my $not_deleted = 0;
4532 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4533 my $hash_parent = $parents[$i];
4534 my $from_hash = $diff->{'from_id'}[$i];
4535 my $from_path = $diff->{'from_file'}[$i];
4536 my $status = $diff->{'status'}[$i];
4538 $has_history ||= ($status ne 'A');
4539 $not_deleted ||= ($status ne 'D');
4541 if ($status eq 'A') {
4542 print "<td class=\"link\" align=\"right\"> | </td>\n";
4543 } elsif ($status eq 'D') {
4544 print "<td class=\"link\">" .
4545 $cgi->a({-href => href(action=>"blob",
4546 hash_base=>$hash,
4547 hash=>$from_hash,
4548 file_name=>$from_path)},
4549 "blob" . ($i+1)) .
4550 " | </td>\n";
4551 } else {
4552 if ($diff->{'to_id'} eq $from_hash) {
4553 print "<td class=\"link nochange\">";
4554 } else {
4555 print "<td class=\"link\">";
4557 print $cgi->a({-href => href(action=>"blobdiff",
4558 hash=>$diff->{'to_id'},
4559 hash_parent=>$from_hash,
4560 hash_base=>$hash,
4561 hash_parent_base=>$hash_parent,
4562 file_name=>$diff->{'to_file'},
4563 file_parent=>$from_path)},
4564 "diff" . ($i+1)) .
4565 " | </td>\n";
4569 print "<td class=\"link\">";
4570 if ($not_deleted) {
4571 print $cgi->a({-href => href(action=>"blob",
4572 hash=>$diff->{'to_id'},
4573 file_name=>$diff->{'to_file'},
4574 hash_base=>$hash)},
4575 "blob");
4576 print " | " if ($has_history);
4578 if ($has_history) {
4579 print $cgi->a({-href => href(action=>"history",
4580 file_name=>$diff->{'to_file'},
4581 hash_base=>$hash)},
4582 "history");
4584 print "</td>\n";
4586 print "</tr>\n";
4587 next; # instead of 'else' clause, to avoid extra indent
4589 # else ordinary diff
4591 my ($to_mode_oct, $to_mode_str, $to_file_type);
4592 my ($from_mode_oct, $from_mode_str, $from_file_type);
4593 if ($diff->{'to_mode'} ne ('0' x 6)) {
4594 $to_mode_oct = oct $diff->{'to_mode'};
4595 if (S_ISREG($to_mode_oct)) { # only for regular file
4596 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4598 $to_file_type = file_type($diff->{'to_mode'});
4600 if ($diff->{'from_mode'} ne ('0' x 6)) {
4601 $from_mode_oct = oct $diff->{'from_mode'};
4602 if (S_ISREG($to_mode_oct)) { # only for regular file
4603 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4605 $from_file_type = file_type($diff->{'from_mode'});
4608 if ($diff->{'status'} eq "A") { # created
4609 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4610 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4611 $mode_chng .= "]</span>";
4612 print "<td>";
4613 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4614 hash_base=>$hash, file_name=>$diff->{'file'}),
4615 -class => "list"}, esc_path($diff->{'file'}));
4616 print "</td>\n";
4617 print "<td>$mode_chng</td>\n";
4618 print "<td class=\"link\">";
4619 if ($action eq 'commitdiff') {
4620 # link to patch
4621 $patchno++;
4622 print $cgi->a({-href => "#patch$patchno"}, "patch");
4623 print " | ";
4625 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4626 hash_base=>$hash, file_name=>$diff->{'file'})},
4627 "blob");
4628 print "</td>\n";
4630 } elsif ($diff->{'status'} eq "D") { # deleted
4631 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4632 print "<td>";
4633 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4634 hash_base=>$parent, file_name=>$diff->{'file'}),
4635 -class => "list"}, esc_path($diff->{'file'}));
4636 print "</td>\n";
4637 print "<td>$mode_chng</td>\n";
4638 print "<td class=\"link\">";
4639 if ($action eq 'commitdiff') {
4640 # link to patch
4641 $patchno++;
4642 print $cgi->a({-href => "#patch$patchno"}, "patch");
4643 print " | ";
4645 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4646 hash_base=>$parent, file_name=>$diff->{'file'})},
4647 "blob") . " | ";
4648 if ($have_blame) {
4649 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4650 file_name=>$diff->{'file'})},
4651 "blame") . " | ";
4653 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4654 file_name=>$diff->{'file'})},
4655 "history");
4656 print "</td>\n";
4658 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4659 my $mode_chnge = "";
4660 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4661 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4662 if ($from_file_type ne $to_file_type) {
4663 $mode_chnge .= " from $from_file_type to $to_file_type";
4665 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4666 if ($from_mode_str && $to_mode_str) {
4667 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4668 } elsif ($to_mode_str) {
4669 $mode_chnge .= " mode: $to_mode_str";
4672 $mode_chnge .= "]</span>\n";
4674 print "<td>";
4675 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4676 hash_base=>$hash, file_name=>$diff->{'file'}),
4677 -class => "list"}, esc_path($diff->{'file'}));
4678 print "</td>\n";
4679 print "<td>$mode_chnge</td>\n";
4680 print "<td class=\"link\">";
4681 if ($action eq 'commitdiff') {
4682 # link to patch
4683 $patchno++;
4684 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4685 " | ";
4686 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4687 # "commit" view and modified file (not onlu mode changed)
4688 print $cgi->a({-href => href(action=>"blobdiff",
4689 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4690 hash_base=>$hash, hash_parent_base=>$parent,
4691 file_name=>$diff->{'file'})},
4692 "diff") .
4693 " | ";
4695 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4696 hash_base=>$hash, file_name=>$diff->{'file'})},
4697 "blob") . " | ";
4698 if ($have_blame) {
4699 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4700 file_name=>$diff->{'file'})},
4701 "blame") . " | ";
4703 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4704 file_name=>$diff->{'file'})},
4705 "history");
4706 print "</td>\n";
4708 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4709 my %status_name = ('R' => 'moved', 'C' => 'copied');
4710 my $nstatus = $status_name{$diff->{'status'}};
4711 my $mode_chng = "";
4712 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4713 # mode also for directories, so we cannot use $to_mode_str
4714 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4716 print "<td>" .
4717 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4718 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4719 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4720 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4721 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4722 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4723 -class => "list"}, esc_path($diff->{'from_file'})) .
4724 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4725 "<td class=\"link\">";
4726 if ($action eq 'commitdiff') {
4727 # link to patch
4728 $patchno++;
4729 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4730 " | ";
4731 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4732 # "commit" view and modified file (not only pure rename or copy)
4733 print $cgi->a({-href => href(action=>"blobdiff",
4734 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4735 hash_base=>$hash, hash_parent_base=>$parent,
4736 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4737 "diff") .
4738 " | ";
4740 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4741 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4742 "blob") . " | ";
4743 if ($have_blame) {
4744 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4745 file_name=>$diff->{'to_file'})},
4746 "blame") . " | ";
4748 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4749 file_name=>$diff->{'to_file'})},
4750 "history");
4751 print "</td>\n";
4753 } # we should not encounter Unmerged (U) or Unknown (X) status
4754 print "</tr>\n";
4756 print "</tbody>" if $has_header;
4757 print "</table>\n";
4760 sub git_patchset_body {
4761 my ($fd, $difftree, $hash, @hash_parents) = @_;
4762 my ($hash_parent) = $hash_parents[0];
4764 my $is_combined = (@hash_parents > 1);
4765 my $patch_idx = 0;
4766 my $patch_number = 0;
4767 my $patch_line;
4768 my $diffinfo;
4769 my $to_name;
4770 my (%from, %to);
4772 print "<div class=\"patchset\">\n";
4774 # skip to first patch
4775 while ($patch_line = <$fd>) {
4776 chomp $patch_line;
4778 last if ($patch_line =~ m/^diff /);
4781 PATCH:
4782 while ($patch_line) {
4784 # parse "git diff" header line
4785 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4786 # $1 is from_name, which we do not use
4787 $to_name = unquote($2);
4788 $to_name =~ s!^b/!!;
4789 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4790 # $1 is 'cc' or 'combined', which we do not use
4791 $to_name = unquote($2);
4792 } else {
4793 $to_name = undef;
4796 # check if current patch belong to current raw line
4797 # and parse raw git-diff line if needed
4798 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4799 # this is continuation of a split patch
4800 print "<div class=\"patch cont\">\n";
4801 } else {
4802 # advance raw git-diff output if needed
4803 $patch_idx++ if defined $diffinfo;
4805 # read and prepare patch information
4806 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4808 # compact combined diff output can have some patches skipped
4809 # find which patch (using pathname of result) we are at now;
4810 if ($is_combined) {
4811 while ($to_name ne $diffinfo->{'to_file'}) {
4812 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4813 format_diff_cc_simplified($diffinfo, @hash_parents) .
4814 "</div>\n"; # class="patch"
4816 $patch_idx++;
4817 $patch_number++;
4819 last if $patch_idx > $#$difftree;
4820 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4824 # modifies %from, %to hashes
4825 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4827 # this is first patch for raw difftree line with $patch_idx index
4828 # we index @$difftree array from 0, but number patches from 1
4829 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4832 # git diff header
4833 #assert($patch_line =~ m/^diff /) if DEBUG;
4834 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4835 $patch_number++;
4836 # print "git diff" header
4837 print format_git_diff_header_line($patch_line, $diffinfo,
4838 \%from, \%to);
4840 # print extended diff header
4841 print "<div class=\"diff extended_header\">\n";
4842 EXTENDED_HEADER:
4843 while ($patch_line = <$fd>) {
4844 chomp $patch_line;
4846 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4848 print format_extended_diff_header_line($patch_line, $diffinfo,
4849 \%from, \%to);
4851 print "</div>\n"; # class="diff extended_header"
4853 # from-file/to-file diff header
4854 if (! $patch_line) {
4855 print "</div>\n"; # class="patch"
4856 last PATCH;
4858 next PATCH if ($patch_line =~ m/^diff /);
4859 #assert($patch_line =~ m/^---/) if DEBUG;
4861 my $last_patch_line = $patch_line;
4862 $patch_line = <$fd>;
4863 chomp $patch_line;
4864 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4866 print format_diff_from_to_header($last_patch_line, $patch_line,
4867 $diffinfo, \%from, \%to,
4868 @hash_parents);
4870 # the patch itself
4871 LINE:
4872 while ($patch_line = <$fd>) {
4873 chomp $patch_line;
4875 next PATCH if ($patch_line =~ m/^diff /);
4877 print format_diff_line($patch_line, \%from, \%to);
4880 } continue {
4881 print "</div>\n"; # class="patch"
4884 # for compact combined (--cc) format, with chunk and patch simplification
4885 # the patchset might be empty, but there might be unprocessed raw lines
4886 for (++$patch_idx if $patch_number > 0;
4887 $patch_idx < @$difftree;
4888 ++$patch_idx) {
4889 # read and prepare patch information
4890 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4892 # generate anchor for "patch" links in difftree / whatchanged part
4893 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4894 format_diff_cc_simplified($diffinfo, @hash_parents) .
4895 "</div>\n"; # class="patch"
4897 $patch_number++;
4900 if ($patch_number == 0) {
4901 if (@hash_parents > 1) {
4902 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4903 } else {
4904 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4908 print "</div>\n"; # class="patchset"
4911 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4913 # fills project list info (age, description, owner, forks) for each
4914 # project in the list, removing invalid projects from returned list
4915 # NOTE: modifies $projlist, but does not remove entries from it
4916 sub fill_project_list_info {
4917 my ($projlist, $check_forks) = @_;
4918 my @projects;
4920 my $show_ctags = gitweb_check_feature('ctags');
4921 PROJECT:
4922 foreach my $pr (@$projlist) {
4923 my (@activity) = git_get_last_activity($pr->{'path'});
4924 unless (@activity) {
4925 next PROJECT;
4927 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4928 if (!defined $pr->{'descr'}) {
4929 my $descr = git_get_project_description($pr->{'path'}) || "";
4930 $descr = to_utf8($descr);
4931 $pr->{'descr_long'} = $descr;
4932 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4934 if (!defined $pr->{'owner'}) {
4935 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4937 if ($check_forks) {
4938 my $pname = $pr->{'path'};
4939 if (($pname =~ s/\.git$//) &&
4940 ($pname !~ /\/$/) &&
4941 (-d "$projectroot/$pname")) {
4942 $pr->{'forks'} = "-d $projectroot/$pname";
4943 } else {
4944 $pr->{'forks'} = 0;
4947 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4948 push @projects, $pr;
4951 return @projects;
4954 # print 'sort by' <th> element, generating 'sort by $name' replay link
4955 # if that order is not selected
4956 sub print_sort_th {
4957 print format_sort_th(@_);
4960 sub format_sort_th {
4961 my ($name, $order, $header) = @_;
4962 my $sort_th = "";
4963 $header ||= ucfirst($name);
4965 if ($order eq $name) {
4966 $sort_th .= "<th>$header</th>\n";
4967 } else {
4968 $sort_th .= "<th>" .
4969 $cgi->a({-href => href(-replay=>1, order=>$name),
4970 -class => "header"}, $header) .
4971 "</th>\n";
4974 return $sort_th;
4977 sub git_project_list_body {
4978 # actually uses global variable $project
4979 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4981 my $check_forks = gitweb_check_feature('forks');
4982 my @projects = fill_project_list_info($projlist, $check_forks);
4984 $order ||= $default_projects_order;
4985 $from = 0 unless defined $from;
4986 $to = $#projects if (!defined $to || $#projects < $to);
4988 my %order_info = (
4989 project => { key => 'path', type => 'str' },
4990 descr => { key => 'descr_long', type => 'str' },
4991 owner => { key => 'owner', type => 'str' },
4992 age => { key => 'age', type => 'num' }
4994 my $oi = $order_info{$order};
4995 if ($oi->{'type'} eq 'str') {
4996 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4997 } else {
4998 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
5001 my $show_ctags = gitweb_check_feature('ctags');
5002 if ($show_ctags) {
5003 my %ctags;
5004 foreach my $p (@projects) {
5005 foreach my $ct (keys %{$p->{'ctags'}}) {
5006 $ctags{$ct} += $p->{'ctags'}->{$ct};
5009 my $cloud = git_populate_project_tagcloud(\%ctags);
5010 print git_show_project_tagcloud($cloud, 64);
5013 print "<table class=\"project_list\">\n";
5014 unless ($no_header) {
5015 print "<tr>\n";
5016 if ($check_forks) {
5017 print "<th></th>\n";
5019 print_sort_th('project', $order, 'Project');
5020 print_sort_th('descr', $order, 'Description');
5021 print_sort_th('owner', $order, 'Owner');
5022 print_sort_th('age', $order, 'Last Change');
5023 print "<th></th>\n" . # for links
5024 "</tr>\n";
5026 my $alternate = 1;
5027 my $tagfilter = $cgi->param('by_tag');
5028 for (my $i = $from; $i <= $to; $i++) {
5029 my $pr = $projects[$i];
5031 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
5032 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
5033 and not $pr->{'descr_long'} =~ /$searchtext/;
5034 # Weed out forks or non-matching entries of search
5035 if ($check_forks) {
5036 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
5037 $forkbase="^$forkbase" if $forkbase;
5038 next if not $searchtext and not $tagfilter and $show_ctags
5039 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
5042 if ($alternate) {
5043 print "<tr class=\"dark\">\n";
5044 } else {
5045 print "<tr class=\"light\">\n";
5047 $alternate ^= 1;
5048 if ($check_forks) {
5049 print "<td>";
5050 if ($pr->{'forks'}) {
5051 print "<!-- $pr->{'forks'} -->\n";
5052 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
5054 print "</td>\n";
5056 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5057 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
5058 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5059 -class => "list", -title => $pr->{'descr_long'}},
5060 esc_html($pr->{'descr'})) . "</td>\n" .
5061 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5062 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5063 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
5064 "<td class=\"link\">" .
5065 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5066 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5067 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5068 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5069 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5070 "</td>\n" .
5071 "</tr>\n";
5073 if (defined $extra) {
5074 print "<tr>\n";
5075 if ($check_forks) {
5076 print "<td></td>\n";
5078 print "<td colspan=\"5\">$extra</td>\n" .
5079 "</tr>\n";
5081 print "</table>\n";
5084 sub git_log_body {
5085 # uses global variable $project
5086 my ($commitlist, $from, $to, $refs, $extra) = @_;
5088 $from = 0 unless defined $from;
5089 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5091 for (my $i = 0; $i <= $to; $i++) {
5092 my %co = %{$commitlist->[$i]};
5093 next if !%co;
5094 my $commit = $co{'id'};
5095 my $ref = format_ref_marker($refs, $commit);
5096 my %ad = parse_date($co{'author_epoch'});
5097 git_print_header_div('commit',
5098 "<span class=\"age\">$co{'age_string'}</span>" .
5099 esc_html($co{'title'}) . $ref,
5100 $commit);
5101 print "<div class=\"title_text\">\n" .
5102 "<div class=\"log_link\">\n" .
5103 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5104 " | " .
5105 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5106 " | " .
5107 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5108 "<br/>\n" .
5109 "</div>\n";
5110 git_print_authorship(\%co, -tag => 'span');
5111 print "<br/>\n</div>\n";
5113 print "<div class=\"log_body\">\n";
5114 git_print_log($co{'comment'}, -final_empty_line=> 1);
5115 print "</div>\n";
5117 if ($extra) {
5118 print "<div class=\"page_nav\">\n";
5119 print "$extra\n";
5120 print "</div>\n";
5124 sub git_shortlog_body {
5125 # uses global variable $project
5126 my ($commitlist, $from, $to, $refs, $extra) = @_;
5128 $from = 0 unless defined $from;
5129 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5131 print "<table class=\"shortlog\">\n";
5132 my $alternate = 1;
5133 for (my $i = $from; $i <= $to; $i++) {
5134 my %co = %{$commitlist->[$i]};
5135 my $commit = $co{'id'};
5136 my $ref = format_ref_marker($refs, $commit);
5137 if ($alternate) {
5138 print "<tr class=\"dark\">\n";
5139 } else {
5140 print "<tr class=\"light\">\n";
5142 $alternate ^= 1;
5143 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5144 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5145 format_author_html('td', \%co, 10) . "<td>";
5146 print format_subject_html($co{'title'}, $co{'title_short'},
5147 href(action=>"commit", hash=>$commit), $ref);
5148 print "</td>\n" .
5149 "<td class=\"link\">" .
5150 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5151 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5152 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5153 my $snapshot_links = format_snapshot_links($commit);
5154 if (defined $snapshot_links) {
5155 print " | " . $snapshot_links;
5157 print "</td>\n" .
5158 "</tr>\n";
5160 if (defined $extra) {
5161 print "<tr>\n" .
5162 "<td colspan=\"4\">$extra</td>\n" .
5163 "</tr>\n";
5165 print "</table>\n";
5168 sub git_history_body {
5169 # Warning: assumes constant type (blob or tree) during history
5170 my ($commitlist, $from, $to, $refs, $extra,
5171 $file_name, $file_hash, $ftype) = @_;
5173 $from = 0 unless defined $from;
5174 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5176 print "<table class=\"history\">\n";
5177 my $alternate = 1;
5178 for (my $i = $from; $i <= $to; $i++) {
5179 my %co = %{$commitlist->[$i]};
5180 if (!%co) {
5181 next;
5183 my $commit = $co{'id'};
5185 my $ref = format_ref_marker($refs, $commit);
5187 if ($alternate) {
5188 print "<tr class=\"dark\">\n";
5189 } else {
5190 print "<tr class=\"light\">\n";
5192 $alternate ^= 1;
5193 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5194 # shortlog: format_author_html('td', \%co, 10)
5195 format_author_html('td', \%co, 15, 3) . "<td>";
5196 # originally git_history used chop_str($co{'title'}, 50)
5197 print format_subject_html($co{'title'}, $co{'title_short'},
5198 href(action=>"commit", hash=>$commit), $ref);
5199 print "</td>\n" .
5200 "<td class=\"link\">" .
5201 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5202 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5204 if ($ftype eq 'blob') {
5205 my $blob_current = $file_hash;
5206 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5207 if (defined $blob_current && defined $blob_parent &&
5208 $blob_current ne $blob_parent) {
5209 print " | " .
5210 $cgi->a({-href => href(action=>"blobdiff",
5211 hash=>$blob_current, hash_parent=>$blob_parent,
5212 hash_base=>$hash_base, hash_parent_base=>$commit,
5213 file_name=>$file_name)},
5214 "diff to current");
5217 print "</td>\n" .
5218 "</tr>\n";
5220 if (defined $extra) {
5221 print "<tr>\n" .
5222 "<td colspan=\"4\">$extra</td>\n" .
5223 "</tr>\n";
5225 print "</table>\n";
5228 sub git_tags_body {
5229 # uses global variable $project
5230 my ($taglist, $from, $to, $extra) = @_;
5231 $from = 0 unless defined $from;
5232 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5234 print "<table class=\"tags\">\n";
5235 my $alternate = 1;
5236 for (my $i = $from; $i <= $to; $i++) {
5237 my $entry = $taglist->[$i];
5238 my %tag = %$entry;
5239 my $comment = $tag{'subject'};
5240 my $comment_short;
5241 if (defined $comment) {
5242 $comment_short = chop_str($comment, 30, 5);
5244 if ($alternate) {
5245 print "<tr class=\"dark\">\n";
5246 } else {
5247 print "<tr class=\"light\">\n";
5249 $alternate ^= 1;
5250 if (defined $tag{'age'}) {
5251 print "<td><i>$tag{'age'}</i></td>\n";
5252 } else {
5253 print "<td></td>\n";
5255 print "<td>" .
5256 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5257 -class => "list name"}, esc_html($tag{'name'})) .
5258 "</td>\n" .
5259 "<td>";
5260 if (defined $comment) {
5261 print format_subject_html($comment, $comment_short,
5262 href(action=>"tag", hash=>$tag{'id'}));
5264 print "</td>\n" .
5265 "<td class=\"selflink\">";
5266 if ($tag{'type'} eq "tag") {
5267 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5268 } else {
5269 print "&nbsp;";
5271 print "</td>\n" .
5272 "<td class=\"link\">" . " | " .
5273 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5274 if ($tag{'reftype'} eq "commit") {
5275 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5276 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5277 } elsif ($tag{'reftype'} eq "blob") {
5278 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5280 print "</td>\n" .
5281 "</tr>";
5283 if (defined $extra) {
5284 print "<tr>\n" .
5285 "<td colspan=\"5\">$extra</td>\n" .
5286 "</tr>\n";
5288 print "</table>\n";
5291 sub git_heads_body {
5292 # uses global variable $project
5293 my ($headlist, $head, $from, $to, $extra) = @_;
5294 $from = 0 unless defined $from;
5295 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5297 print "<table class=\"heads\">\n";
5298 my $alternate = 1;
5299 for (my $i = $from; $i <= $to; $i++) {
5300 my $entry = $headlist->[$i];
5301 my %ref = %$entry;
5302 my $curr = $ref{'id'} eq $head;
5303 if ($alternate) {
5304 print "<tr class=\"dark\">\n";
5305 } else {
5306 print "<tr class=\"light\">\n";
5308 $alternate ^= 1;
5309 print "<td><i>$ref{'age'}</i></td>\n" .
5310 ($curr ? "<td class=\"current_head\">" : "<td>") .
5311 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5312 -class => "list name"},esc_html($ref{'name'})) .
5313 "</td>\n" .
5314 "<td class=\"link\">" .
5315 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5316 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5317 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
5318 "</td>\n" .
5319 "</tr>";
5321 if (defined $extra) {
5322 print "<tr>\n" .
5323 "<td colspan=\"3\">$extra</td>\n" .
5324 "</tr>\n";
5326 print "</table>\n";
5329 sub git_search_grep_body {
5330 my ($commitlist, $from, $to, $extra) = @_;
5331 $from = 0 unless defined $from;
5332 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5334 print "<table class=\"commit_search\">\n";
5335 my $alternate = 1;
5336 for (my $i = $from; $i <= $to; $i++) {
5337 my %co = %{$commitlist->[$i]};
5338 if (!%co) {
5339 next;
5341 my $commit = $co{'id'};
5342 if ($alternate) {
5343 print "<tr class=\"dark\">\n";
5344 } else {
5345 print "<tr class=\"light\">\n";
5347 $alternate ^= 1;
5348 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5349 format_author_html('td', \%co, 15, 5) .
5350 "<td>" .
5351 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5352 -class => "list subject"},
5353 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5354 my $comment = $co{'comment'};
5355 foreach my $line (@$comment) {
5356 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5357 my ($lead, $match, $trail) = ($1, $2, $3);
5358 $match = chop_str($match, 70, 5, 'center');
5359 my $contextlen = int((80 - length($match))/2);
5360 $contextlen = 30 if ($contextlen > 30);
5361 $lead = chop_str($lead, $contextlen, 10, 'left');
5362 $trail = chop_str($trail, $contextlen, 10, 'right');
5364 $lead = esc_html($lead);
5365 $match = esc_html($match);
5366 $trail = esc_html($trail);
5368 print "$lead<span class=\"match\">$match</span>$trail<br />";
5371 print "</td>\n" .
5372 "<td class=\"link\">" .
5373 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5374 " | " .
5375 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5376 " | " .
5377 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5378 print "</td>\n" .
5379 "</tr>\n";
5381 if (defined $extra) {
5382 print "<tr>\n" .
5383 "<td colspan=\"3\">$extra</td>\n" .
5384 "</tr>\n";
5386 print "</table>\n";
5389 ## ======================================================================
5390 ## ======================================================================
5391 ## actions
5393 sub git_project_list {
5394 my $order = $input_params{'order'};
5395 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5396 die_error(400, "Unknown order parameter");
5399 my @list = git_get_projects_list();
5400 if (!@list) {
5401 die_error(404, "No projects found");
5404 git_header_html();
5405 if (defined $home_text && -f $home_text) {
5406 print "<div class=\"index_include\">\n";
5407 insert_file($home_text);
5408 print "</div>\n";
5410 print $cgi->startform(-method => "get") .
5411 "<p class=\"projsearch\">Search:\n" .
5412 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5413 "</p>" .
5414 $cgi->end_form() . "\n";
5415 git_project_list_body(\@list, $order);
5416 git_footer_html();
5419 sub git_forks {
5420 my $order = $input_params{'order'};
5421 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5422 die_error(400, "Unknown order parameter");
5425 my @list = git_get_projects_list($project);
5426 if (!@list) {
5427 die_error(404, "No forks found");
5430 git_header_html();
5431 git_print_page_nav('','');
5432 git_print_header_div('summary', "$project forks");
5433 git_project_list_body(\@list, $order);
5434 git_footer_html();
5437 sub git_project_index {
5438 my @projects = git_get_projects_list($project);
5440 print $cgi->header(
5441 -type => 'text/plain',
5442 -charset => 'utf-8',
5443 -content_disposition => 'inline; filename="index.aux"');
5445 foreach my $pr (@projects) {
5446 if (!exists $pr->{'owner'}) {
5447 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5450 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5451 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5452 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5453 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5454 $path =~ s/ /\+/g;
5455 $owner =~ s/ /\+/g;
5457 print "$path $owner\n";
5461 sub git_summary {
5462 my $descr = git_get_project_description($project) || "none";
5463 my %co = parse_commit("HEAD");
5464 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5465 my $head = $co{'id'};
5467 my $owner = git_get_project_owner($project);
5469 my $refs = git_get_references();
5470 # These get_*_list functions return one more to allow us to see if
5471 # there are more ...
5472 my @taglist = git_get_tags_list(16);
5473 my @headlist = git_get_heads_list(16);
5474 my @forklist;
5475 my $check_forks = gitweb_check_feature('forks');
5477 if ($check_forks) {
5478 @forklist = git_get_projects_list($project);
5481 git_header_html();
5482 git_print_page_nav('summary','', $head);
5484 print "<div class=\"title\">&nbsp;</div>\n";
5485 print "<table class=\"projects_list\">\n" .
5486 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5487 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5488 if (defined $cd{'rfc2822'}) {
5489 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5492 # use per project git URL list in $projectroot/$project/cloneurl
5493 # or make project git URL from git base URL and project name
5494 my $url_tag = "URL";
5495 my @url_list = git_get_project_url_list($project);
5496 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5497 foreach my $git_url (@url_list) {
5498 next unless $git_url;
5499 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5500 $url_tag = "";
5503 # Tag cloud
5504 my $show_ctags = gitweb_check_feature('ctags');
5505 if ($show_ctags) {
5506 my $ctags = git_get_project_ctags($project);
5507 my $cloud = git_populate_project_tagcloud($ctags);
5508 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5509 print "</td>\n<td>" unless %$ctags;
5510 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5511 print "</td>\n<td>" if %$ctags;
5512 print git_show_project_tagcloud($cloud, 48);
5513 print "</td></tr>";
5516 print "</table>\n";
5518 # If XSS prevention is on, we don't include README.html.
5519 # TODO: Allow a readme in some safe format.
5520 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5521 print "<div class=\"title\">readme</div>\n" .
5522 "<div class=\"readme\">\n";
5523 insert_file("$projectroot/$project/README.html");
5524 print "\n</div>\n"; # class="readme"
5527 # we need to request one more than 16 (0..15) to check if
5528 # those 16 are all
5529 my @commitlist = $head ? parse_commits($head, 17) : ();
5530 if (@commitlist) {
5531 git_print_header_div('shortlog');
5532 git_shortlog_body(\@commitlist, 0, 15, $refs,
5533 $#commitlist <= 15 ? undef :
5534 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5537 if (@taglist) {
5538 git_print_header_div('tags');
5539 git_tags_body(\@taglist, 0, 15,
5540 $#taglist <= 15 ? undef :
5541 $cgi->a({-href => href(action=>"tags")}, "..."));
5544 if (@headlist) {
5545 git_print_header_div('heads');
5546 git_heads_body(\@headlist, $head, 0, 15,
5547 $#headlist <= 15 ? undef :
5548 $cgi->a({-href => href(action=>"heads")}, "..."));
5551 if (@forklist) {
5552 git_print_header_div('forks');
5553 git_project_list_body(\@forklist, 'age', 0, 15,
5554 $#forklist <= 15 ? undef :
5555 $cgi->a({-href => href(action=>"forks")}, "..."),
5556 'no_header');
5559 git_footer_html();
5562 sub git_tag {
5563 my %tag = parse_tag($hash);
5565 if (! %tag) {
5566 die_error(404, "Unknown tag object");
5569 my $head = git_get_head_hash($project);
5570 git_header_html();
5571 git_print_page_nav('','', $head,undef,$head);
5572 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5573 print "<div class=\"title_text\">\n" .
5574 "<table class=\"object_header\">\n" .
5575 "<tr>\n" .
5576 "<td>object</td>\n" .
5577 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5578 $tag{'object'}) . "</td>\n" .
5579 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5580 $tag{'type'}) . "</td>\n" .
5581 "</tr>\n";
5582 if (defined($tag{'author'})) {
5583 git_print_authorship_rows(\%tag, 'author');
5585 print "</table>\n\n" .
5586 "</div>\n";
5587 print "<div class=\"page_body\">";
5588 my $comment = $tag{'comment'};
5589 foreach my $line (@$comment) {
5590 chomp $line;
5591 print esc_html($line, -nbsp=>1) . "<br/>\n";
5593 print "</div>\n";
5594 git_footer_html();
5597 sub git_blame_common {
5598 my $format = shift || 'porcelain';
5599 if ($format eq 'porcelain' && $cgi->param('js') &&
5600 !$caching_enabled) {
5601 $format = 'incremental';
5602 $action = 'blame_incremental'; # for page title etc
5605 # permissions
5606 gitweb_check_feature('blame')
5607 or die_error(403, "Blame view not allowed");
5609 # error checking
5610 die_error(400, "No file name given") unless $file_name;
5611 $hash_base ||= git_get_head_hash($project);
5612 die_error(404, "Couldn't find base commit") unless $hash_base;
5613 my %co = parse_commit($hash_base)
5614 or die_error(404, "Commit not found");
5615 my $ftype = "blob";
5616 if (!defined $hash) {
5617 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5618 or die_error(404, "Error looking up file");
5619 } else {
5620 $ftype = git_get_type($hash);
5621 if ($ftype !~ "blob") {
5622 die_error(400, "Object is not a blob");
5626 my $fd;
5627 if ($format eq 'incremental') {
5628 # get file contents (as base)
5629 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5630 or die_error(500, "Open git-cat-file failed");
5631 } elsif ($format eq 'data') {
5632 # run git-blame --incremental
5633 open $fd, "-|", git_cmd(), "blame", "--incremental",
5634 $hash_base, "--", $file_name
5635 or die_error(500, "Open git-blame --incremental failed");
5636 } else {
5637 # run git-blame --porcelain
5638 open $fd, "-|", git_cmd(), "blame", '-p',
5639 $hash_base, '--', $file_name
5640 or die_error(500, "Open git-blame --porcelain failed");
5643 # incremental blame data returns early
5644 if ($format eq 'data') {
5645 print $cgi->header(
5646 -type=>"text/plain", -charset => "utf-8",
5647 -status=> "200 OK");
5648 local $| = 1; # output autoflush
5649 print while <$fd>;
5650 close $fd
5651 or print "ERROR $!\n";
5653 print 'END';
5654 if (!$caching_enabled &&
5655 defined $t0 && gitweb_check_feature('timed')) {
5656 print ' '.
5657 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5658 ' '.$number_of_git_cmds;
5660 print "\n";
5662 return;
5665 # page header
5666 git_header_html();
5667 my $formats_nav =
5668 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5669 "blob") .
5670 " | ";
5671 if ($format eq 'incremental') {
5672 $formats_nav .=
5673 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5674 "blame") . " (non-incremental)";
5675 } elsif (!$caching_enabled) {
5676 $formats_nav .=
5677 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5678 "blame") . " (incremental)";
5680 $formats_nav .=
5681 " | " .
5682 $cgi->a({-href => href(action=>"history", -replay=>1)},
5683 "history") .
5684 " | " .
5685 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5686 "HEAD");
5687 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5688 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5689 git_print_page_path($file_name, $ftype, $hash_base);
5691 # page body
5692 if ($format eq 'incremental') {
5693 print "<noscript>\n<div class=\"error\"><center><b>\n".
5694 "This page requires JavaScript to run.\n Use ".
5695 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5696 'this page').
5697 " instead.\n".
5698 "</b></center></div>\n</noscript>\n";
5700 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5703 print qq!<div class="page_body">\n!;
5704 print qq!<div id="progress_info">... / ...</div>\n!
5705 if ($format eq 'incremental');
5706 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5707 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5708 qq!<thead>\n!.
5709 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5710 qq!</thead>\n!.
5711 qq!<tbody>\n!;
5713 my @rev_color = qw(light dark);
5714 my $num_colors = scalar(@rev_color);
5715 my $current_color = 0;
5717 if ($format eq 'incremental') {
5718 my $color_class = $rev_color[$current_color];
5720 #contents of a file
5721 my $linenr = 0;
5722 LINE:
5723 while (my $line = <$fd>) {
5724 chomp $line;
5725 $linenr++;
5727 print qq!<tr id="l$linenr" class="$color_class">!.
5728 qq!<td class="sha1"><a href=""> </a></td>!.
5729 qq!<td class="linenr">!.
5730 qq!<a class="linenr" href="">$linenr</a></td>!;
5731 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5732 print qq!</tr>\n!;
5735 } else { # porcelain, i.e. ordinary blame
5736 my %metainfo = (); # saves information about commits
5738 # blame data
5739 LINE:
5740 while (my $line = <$fd>) {
5741 chomp $line;
5742 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5743 # no <lines in group> for subsequent lines in group of lines
5744 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5745 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5746 if (!exists $metainfo{$full_rev}) {
5747 $metainfo{$full_rev} = { 'nprevious' => 0 };
5749 my $meta = $metainfo{$full_rev};
5750 my $data;
5751 while ($data = <$fd>) {
5752 chomp $data;
5753 last if ($data =~ s/^\t//); # contents of line
5754 if ($data =~ /^(\S+)(?: (.*))?$/) {
5755 $meta->{$1} = $2 unless exists $meta->{$1};
5757 if ($data =~ /^previous /) {
5758 $meta->{'nprevious'}++;
5761 my $short_rev = substr($full_rev, 0, 8);
5762 my $author = $meta->{'author'};
5763 my %date =
5764 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5765 my $date = $date{'iso-tz'};
5766 if ($group_size) {
5767 $current_color = ($current_color + 1) % $num_colors;
5769 my $tr_class = $rev_color[$current_color];
5770 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5771 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5772 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5773 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5774 if ($group_size) {
5775 print "<td class=\"sha1\"";
5776 print " title=\"". esc_html($author) . ", $date\"";
5777 print " rowspan=\"$group_size\"" if ($group_size > 1);
5778 print ">";
5779 print $cgi->a({-href => href(action=>"commit",
5780 hash=>$full_rev,
5781 file_name=>$file_name)},
5782 esc_html($short_rev));
5783 if ($group_size >= 2) {
5784 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5785 if (@author_initials) {
5786 print "<br />" .
5787 esc_html(join('', @author_initials));
5788 # or join('.', ...)
5791 print "</td>\n";
5793 # 'previous' <sha1 of parent commit> <filename at commit>
5794 if (exists $meta->{'previous'} &&
5795 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5796 $meta->{'parent'} = $1;
5797 $meta->{'file_parent'} = unquote($2);
5799 my $linenr_commit =
5800 exists($meta->{'parent'}) ?
5801 $meta->{'parent'} : $full_rev;
5802 my $linenr_filename =
5803 exists($meta->{'file_parent'}) ?
5804 $meta->{'file_parent'} : unquote($meta->{'filename'});
5805 my $blamed = href(action => 'blame',
5806 file_name => $linenr_filename,
5807 hash_base => $linenr_commit);
5808 print "<td class=\"linenr\">";
5809 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5810 -class => "linenr" },
5811 esc_html($lineno));
5812 print "</td>";
5813 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5814 print "</tr>\n";
5815 } # end while
5819 # footer
5820 print "</tbody>\n".
5821 "</table>\n"; # class="blame"
5822 print "</div>\n"; # class="blame_body"
5823 close $fd
5824 or print "Reading blob failed\n";
5826 git_footer_html();
5829 sub git_blame {
5830 git_blame_common();
5833 sub git_blame_incremental {
5834 git_blame_common(!$caching_enabled ? 'incremental' : undef);
5837 sub git_blame_data {
5838 git_blame_common('data');
5841 sub git_tags {
5842 my $head = git_get_head_hash($project);
5843 git_header_html();
5844 git_print_page_nav('','', $head,undef,$head);
5845 git_print_header_div('summary', $project);
5847 my @tagslist = git_get_tags_list();
5848 if (@tagslist) {
5849 git_tags_body(\@tagslist);
5851 git_footer_html();
5854 sub git_heads {
5855 my $head = git_get_head_hash($project);
5856 git_header_html();
5857 git_print_page_nav('','', $head,undef,$head);
5858 git_print_header_div('summary', $project);
5860 my @headslist = git_get_heads_list();
5861 if (@headslist) {
5862 git_heads_body(\@headslist, $head);
5864 git_footer_html();
5867 sub git_blob_plain {
5868 my $type = shift;
5869 my $expires;
5871 if (!defined $hash) {
5872 if (defined $file_name) {
5873 my $base = $hash_base || git_get_head_hash($project);
5874 $hash = git_get_hash_by_path($base, $file_name, "blob")
5875 or die_error(404, "Cannot find file");
5876 } else {
5877 die_error(400, "No file name defined");
5879 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5880 # blobs defined by non-textual hash id's can be cached
5881 $expires = "+1d";
5884 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5885 or die_error(500, "Open git-cat-file blob '$hash' failed");
5887 # content-type (can include charset)
5888 $type = blob_contenttype($fd, $file_name, $type);
5890 # "save as" filename, even when no $file_name is given
5891 my $save_as = "$hash";
5892 if (defined $file_name) {
5893 $save_as = $file_name;
5894 } elsif ($type =~ m/^text\//) {
5895 $save_as .= '.txt';
5898 # With XSS prevention on, blobs of all types except a few known safe
5899 # ones are served with "Content-Disposition: attachment" to make sure
5900 # they don't run in our security domain. For certain image types,
5901 # blob view writes an <img> tag referring to blob_plain view, and we
5902 # want to be sure not to break that by serving the image as an
5903 # attachment (though Firefox 3 doesn't seem to care).
5904 my $sandbox = $prevent_xss &&
5905 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5907 print $cgi->header(
5908 -type => $type,
5909 -expires => $expires,
5910 -content_disposition =>
5911 ($sandbox ? 'attachment' : 'inline')
5912 . '; filename="' . $save_as . '"');
5913 local $/ = undef;
5914 binmode STDOUT, ':raw';
5915 print <$fd>;
5916 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5917 close $fd;
5920 sub git_blob {
5921 my $expires;
5923 if (!defined $hash) {
5924 if (defined $file_name) {
5925 my $base = $hash_base || git_get_head_hash($project);
5926 $hash = git_get_hash_by_path($base, $file_name, "blob")
5927 or die_error(404, "Cannot find file");
5928 } else {
5929 die_error(400, "No file name defined");
5931 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5932 # blobs defined by non-textual hash id's can be cached
5933 $expires = "+1d";
5936 my $have_blame = gitweb_check_feature('blame');
5937 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5938 or die_error(500, "Couldn't cat $file_name, $hash");
5939 my $mimetype = blob_mimetype($fd, $file_name);
5940 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5941 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5942 close $fd;
5943 return git_blob_plain($mimetype);
5945 # we can have blame only for text/* mimetype
5946 $have_blame &&= ($mimetype =~ m!^text/!);
5948 my $highlight = gitweb_check_feature('highlight');
5949 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5950 $fd = run_highlighter($fd, $highlight, $syntax)
5951 if $syntax;
5953 git_header_html(undef, $expires);
5954 my $formats_nav = '';
5955 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5956 if (defined $file_name) {
5957 if ($have_blame) {
5958 $formats_nav .=
5959 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5960 "blame") .
5961 " | ";
5963 $formats_nav .=
5964 $cgi->a({-href => href(action=>"history", -replay=>1)},
5965 "history") .
5966 " | " .
5967 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5968 "raw") .
5969 " | " .
5970 $cgi->a({-href => href(action=>"blob",
5971 hash_base=>"HEAD", file_name=>$file_name)},
5972 "HEAD");
5973 } else {
5974 $formats_nav .=
5975 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5976 "raw");
5978 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5979 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5980 } else {
5981 print "<div class=\"page_nav\">\n" .
5982 "<br/><br/></div>\n" .
5983 "<div class=\"title\">$hash</div>\n";
5985 git_print_page_path($file_name, "blob", $hash_base);
5986 print "<div class=\"page_body\">\n";
5987 if ($mimetype =~ m!^image/!) {
5988 print qq!<img type="$mimetype"!;
5989 if ($file_name) {
5990 print qq! alt="$file_name" title="$file_name"!;
5992 print qq! src="! .
5993 href(action=>"blob_plain", hash=>$hash,
5994 hash_base=>$hash_base, file_name=>$file_name) .
5995 qq!" />\n!;
5996 } else {
5997 my $nr;
5998 while (my $line = <$fd>) {
5999 chomp $line;
6000 $nr++;
6001 $line = untabify($line);
6002 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
6003 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
6006 close $fd
6007 or print "Reading blob failed.\n";
6008 print "</div>";
6009 git_footer_html();
6012 sub git_tree {
6013 if (!defined $hash_base) {
6014 $hash_base = "HEAD";
6016 if (!defined $hash) {
6017 if (defined $file_name) {
6018 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
6019 } else {
6020 $hash = $hash_base;
6023 die_error(404, "No such tree") unless defined($hash);
6025 my $show_sizes = gitweb_check_feature('show-sizes');
6026 my $have_blame = gitweb_check_feature('blame');
6028 my @entries = ();
6030 local $/ = "\0";
6031 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
6032 ($show_sizes ? '-l' : ()), @extra_options, $hash
6033 or die_error(500, "Open git-ls-tree failed");
6034 @entries = map { chomp; $_ } <$fd>;
6035 close $fd
6036 or die_error(404, "Reading tree failed");
6039 my $refs = git_get_references();
6040 my $ref = format_ref_marker($refs, $hash_base);
6041 git_header_html();
6042 my $basedir = '';
6043 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6044 my @views_nav = ();
6045 if (defined $file_name) {
6046 push @views_nav,
6047 $cgi->a({-href => href(action=>"history", -replay=>1)},
6048 "history"),
6049 $cgi->a({-href => href(action=>"tree",
6050 hash_base=>"HEAD", file_name=>$file_name)},
6051 "HEAD"),
6053 my $snapshot_links = format_snapshot_links($hash);
6054 if (defined $snapshot_links) {
6055 # FIXME: Should be available when we have no hash base as well.
6056 push @views_nav, $snapshot_links;
6058 git_print_page_nav('tree','', $hash_base, undef, undef,
6059 join(' | ', @views_nav));
6060 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
6061 } else {
6062 undef $hash_base;
6063 print "<div class=\"page_nav\">\n";
6064 print "<br/><br/></div>\n";
6065 print "<div class=\"title\">$hash</div>\n";
6067 if (defined $file_name) {
6068 $basedir = $file_name;
6069 if ($basedir ne '' && substr($basedir, -1) ne '/') {
6070 $basedir .= '/';
6072 git_print_page_path($file_name, 'tree', $hash_base);
6074 print "<div class=\"page_body\">\n";
6075 print "<table class=\"tree\">\n";
6076 my $alternate = 1;
6077 # '..' (top directory) link if possible
6078 if (defined $hash_base &&
6079 defined $file_name && $file_name =~ m![^/]+$!) {
6080 if ($alternate) {
6081 print "<tr class=\"dark\">\n";
6082 } else {
6083 print "<tr class=\"light\">\n";
6085 $alternate ^= 1;
6087 my $up = $file_name;
6088 $up =~ s!/?[^/]+$!!;
6089 undef $up unless $up;
6090 # based on git_print_tree_entry
6091 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6092 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
6093 print '<td class="list">';
6094 print $cgi->a({-href => href(action=>"tree",
6095 hash_base=>$hash_base,
6096 file_name=>$up)},
6097 "..");
6098 print "</td>\n";
6099 print "<td class=\"link\"></td>\n";
6101 print "</tr>\n";
6103 foreach my $line (@entries) {
6104 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6106 if ($alternate) {
6107 print "<tr class=\"dark\">\n";
6108 } else {
6109 print "<tr class=\"light\">\n";
6111 $alternate ^= 1;
6113 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6115 print "</tr>\n";
6117 print "</table>\n" .
6118 "</div>";
6119 git_footer_html();
6122 sub snapshot_name {
6123 my ($project, $hash) = @_;
6125 # path/to/project.git -> project
6126 # path/to/project/.git -> project
6127 my $name = to_utf8($project);
6128 $name =~ s,([^/])/*\.git$,$1,;
6129 $name = basename($name);
6130 # sanitize name
6131 $name =~ s/[[:cntrl:]]/?/g;
6133 my $ver = $hash;
6134 if ($hash =~ /^[0-9a-fA-F]+$/) {
6135 # shorten SHA-1 hash
6136 my $full_hash = git_get_full_hash($project, $hash);
6137 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6138 $ver = git_get_short_hash($project, $hash);
6140 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6141 # tags don't need shortened SHA-1 hash
6142 $ver = $1;
6143 } else {
6144 # branches and other need shortened SHA-1 hash
6145 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6146 $ver = $1;
6148 $ver .= '-' . git_get_short_hash($project, $hash);
6150 # in case of hierarchical branch names
6151 $ver =~ s!/!.!g;
6153 # name = project-version_string
6154 $name = "$name-$ver";
6156 return wantarray ? ($name, $name) : $name;
6159 sub git_snapshot {
6160 my $format = $input_params{'snapshot_format'};
6161 if (!@snapshot_fmts) {
6162 die_error(403, "Snapshots not allowed");
6164 # default to first supported snapshot format
6165 $format ||= $snapshot_fmts[0];
6166 if ($format !~ m/^[a-z0-9]+$/) {
6167 die_error(400, "Invalid snapshot format parameter");
6168 } elsif (!exists($known_snapshot_formats{$format})) {
6169 die_error(400, "Unknown snapshot format");
6170 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6171 die_error(403, "Snapshot format not allowed");
6172 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6173 die_error(403, "Unsupported snapshot format");
6176 my $type = git_get_type("$hash^{}");
6177 if (!$type) {
6178 die_error(404, 'Object does not exist');
6179 } elsif ($type eq 'blob') {
6180 die_error(400, 'Object is not a tree-ish');
6183 my ($name, $prefix) = snapshot_name($project, $hash);
6184 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6185 my $cmd = quote_command(
6186 git_cmd(), 'archive',
6187 "--format=$known_snapshot_formats{$format}{'format'}",
6188 "--prefix=$prefix/", $hash);
6189 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6190 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6193 $filename =~ s/(["\\])/\\$1/g;
6194 print $cgi->header(
6195 -type => $known_snapshot_formats{$format}{'type'},
6196 -content_disposition => 'inline; filename="' . $filename . '"',
6197 -status => '200 OK');
6199 open my $fd, "-|", $cmd
6200 or die_error(500, "Execute git-archive failed");
6201 binmode STDOUT, ':raw';
6202 print <$fd>;
6203 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6204 close $fd;
6207 sub git_log_generic {
6208 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6210 my $head = git_get_head_hash($project);
6211 if (!defined $base) {
6212 $base = $head;
6214 if (!defined $page) {
6215 $page = 0;
6217 my $refs = git_get_references();
6219 my $commit_hash = $base;
6220 if (defined $parent) {
6221 $commit_hash = "$parent..$base";
6223 my @commitlist =
6224 parse_commits($commit_hash, 101, (100 * $page),
6225 defined $file_name ? ($file_name, "--full-history") : ());
6227 my $ftype;
6228 if (!defined $file_hash && defined $file_name) {
6229 # some commits could have deleted file in question,
6230 # and not have it in tree, but one of them has to have it
6231 for (my $i = 0; $i < @commitlist; $i++) {
6232 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6233 last if defined $file_hash;
6236 if (defined $file_hash) {
6237 $ftype = git_get_type($file_hash);
6239 if (defined $file_name && !defined $ftype) {
6240 die_error(500, "Unknown type of object");
6242 my %co;
6243 if (defined $file_name) {
6244 %co = parse_commit($base)
6245 or die_error(404, "Unknown commit object");
6249 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6250 my $next_link = '';
6251 if ($#commitlist >= 100) {
6252 $next_link =
6253 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6254 -accesskey => "n", -title => "Alt-n"}, "next");
6256 my $patch_max = gitweb_get_feature('patches');
6257 if ($patch_max && !defined $file_name) {
6258 if ($patch_max < 0 || @commitlist <= $patch_max) {
6259 $paging_nav .= " &sdot; " .
6260 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6261 "patches");
6265 git_header_html();
6266 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6267 if (defined $file_name) {
6268 git_print_header_div('commit', esc_html($co{'title'}), $base);
6269 } else {
6270 git_print_header_div('summary', $project)
6272 git_print_page_path($file_name, $ftype, $hash_base)
6273 if (defined $file_name);
6275 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6276 $file_name, $file_hash, $ftype);
6278 git_footer_html();
6281 sub git_log {
6282 git_log_generic('log', \&git_log_body,
6283 $hash, $hash_parent);
6286 sub git_commit {
6287 $hash ||= $hash_base || "HEAD";
6288 my %co = parse_commit($hash)
6289 or die_error(404, "Unknown commit object");
6291 my $parent = $co{'parent'};
6292 my $parents = $co{'parents'}; # listref
6294 # we need to prepare $formats_nav before any parameter munging
6295 my $formats_nav;
6296 if (!defined $parent) {
6297 # --root commitdiff
6298 $formats_nav .= '(initial)';
6299 } elsif (@$parents == 1) {
6300 # single parent commit
6301 $formats_nav .=
6302 '(parent: ' .
6303 $cgi->a({-href => href(action=>"commit",
6304 hash=>$parent)},
6305 esc_html(substr($parent, 0, 7))) .
6306 ')';
6307 } else {
6308 # merge commit
6309 $formats_nav .=
6310 '(merge: ' .
6311 join(' ', map {
6312 $cgi->a({-href => href(action=>"commit",
6313 hash=>$_)},
6314 esc_html(substr($_, 0, 7)));
6315 } @$parents ) .
6316 ')';
6318 if (gitweb_check_feature('patches') && @$parents <= 1) {
6319 $formats_nav .= " | " .
6320 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6321 "patch");
6324 if (!defined $parent) {
6325 $parent = "--root";
6327 my @difftree;
6328 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6329 @diff_opts,
6330 (@$parents <= 1 ? $parent : '-c'),
6331 $hash, "--"
6332 or die_error(500, "Open git-diff-tree failed");
6333 @difftree = map { chomp; $_ } <$fd>;
6334 close $fd or die_error(404, "Reading git-diff-tree failed");
6336 # non-textual hash id's can be cached
6337 my $expires;
6338 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6339 $expires = "+1d";
6341 my $refs = git_get_references();
6342 my $ref = format_ref_marker($refs, $co{'id'});
6344 git_header_html(undef, $expires);
6345 git_print_page_nav('commit', '',
6346 $hash, $co{'tree'}, $hash,
6347 $formats_nav);
6349 if (defined $co{'parent'}) {
6350 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6351 } else {
6352 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6354 print "<div class=\"title_text\">\n" .
6355 "<table class=\"object_header\">\n";
6356 git_print_authorship_rows(\%co);
6357 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6358 print "<tr>" .
6359 "<td>tree</td>" .
6360 "<td class=\"sha1\">" .
6361 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6362 class => "list"}, $co{'tree'}) .
6363 "</td>" .
6364 "<td class=\"link\">" .
6365 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6366 "tree");
6367 my $snapshot_links = format_snapshot_links($hash);
6368 if (defined $snapshot_links) {
6369 print " | " . $snapshot_links;
6371 print "</td>" .
6372 "</tr>\n";
6374 foreach my $par (@$parents) {
6375 print "<tr>" .
6376 "<td>parent</td>" .
6377 "<td class=\"sha1\">" .
6378 $cgi->a({-href => href(action=>"commit", hash=>$par),
6379 class => "list"}, $par) .
6380 "</td>" .
6381 "<td class=\"link\">" .
6382 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6383 " | " .
6384 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6385 "</td>" .
6386 "</tr>\n";
6388 print "</table>".
6389 "</div>\n";
6391 print "<div class=\"page_body\">\n";
6392 git_print_log($co{'comment'});
6393 print "</div>\n";
6395 git_difftree_body(\@difftree, $hash, @$parents);
6397 git_footer_html();
6400 sub git_object {
6401 # object is defined by:
6402 # - hash or hash_base alone
6403 # - hash_base and file_name
6404 my $type;
6406 # - hash or hash_base alone
6407 if ($hash || ($hash_base && !defined $file_name)) {
6408 my $object_id = $hash || $hash_base;
6410 open my $fd, "-|", quote_command(
6411 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6412 or die_error(404, "Object does not exist");
6413 $type = <$fd>;
6414 chomp $type;
6415 close $fd
6416 or die_error(404, "Object does not exist");
6418 # - hash_base and file_name
6419 } elsif ($hash_base && defined $file_name) {
6420 $file_name =~ s,/+$,,;
6422 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6423 or die_error(404, "Base object does not exist");
6425 # here errors should not hapen
6426 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6427 or die_error(500, "Open git-ls-tree failed");
6428 my $line = <$fd>;
6429 close $fd;
6431 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6432 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6433 die_error(404, "File or directory for given base does not exist");
6435 $type = $2;
6436 $hash = $3;
6437 } else {
6438 die_error(400, "Not enough information to find object");
6441 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6442 hash=>$hash, hash_base=>$hash_base,
6443 file_name=>$file_name),
6444 -status => '302 Found');
6447 sub git_blobdiff {
6448 my $format = shift || 'html';
6450 my $fd;
6451 my @difftree;
6452 my %diffinfo;
6453 my $expires;
6455 # preparing $fd and %diffinfo for git_patchset_body
6456 # new style URI
6457 if (defined $hash_base && defined $hash_parent_base) {
6458 if (defined $file_name) {
6459 # read raw output
6460 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6461 $hash_parent_base, $hash_base,
6462 "--", (defined $file_parent ? $file_parent : ()), $file_name
6463 or die_error(500, "Open git-diff-tree failed");
6464 @difftree = map { chomp; $_ } <$fd>;
6465 close $fd
6466 or die_error(404, "Reading git-diff-tree failed");
6467 @difftree
6468 or die_error(404, "Blob diff not found");
6470 } elsif (defined $hash &&
6471 $hash =~ /[0-9a-fA-F]{40}/) {
6472 # try to find filename from $hash
6474 # read filtered raw output
6475 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6476 $hash_parent_base, $hash_base, "--"
6477 or die_error(500, "Open git-diff-tree failed");
6478 @difftree =
6479 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6480 # $hash == to_id
6481 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6482 map { chomp; $_ } <$fd>;
6483 close $fd
6484 or die_error(404, "Reading git-diff-tree failed");
6485 @difftree
6486 or die_error(404, "Blob diff not found");
6488 } else {
6489 die_error(400, "Missing one of the blob diff parameters");
6492 if (@difftree > 1) {
6493 die_error(400, "Ambiguous blob diff specification");
6496 %diffinfo = parse_difftree_raw_line($difftree[0]);
6497 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6498 $file_name ||= $diffinfo{'to_file'};
6500 $hash_parent ||= $diffinfo{'from_id'};
6501 $hash ||= $diffinfo{'to_id'};
6503 # non-textual hash id's can be cached
6504 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6505 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6506 $expires = '+1d';
6509 # open patch output
6510 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6511 '-p', ($format eq 'html' ? "--full-index" : ()),
6512 $hash_parent_base, $hash_base,
6513 "--", (defined $file_parent ? $file_parent : ()), $file_name
6514 or die_error(500, "Open git-diff-tree failed");
6517 # old/legacy style URI -- not generated anymore since 1.4.3.
6518 if (!%diffinfo) {
6519 die_error('404 Not Found', "Missing one of the blob diff parameters")
6522 # header
6523 if ($format eq 'html') {
6524 my $formats_nav =
6525 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6526 "raw");
6527 git_header_html(undef, $expires);
6528 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6529 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6530 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6531 } else {
6532 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6533 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6535 if (defined $file_name) {
6536 git_print_page_path($file_name, "blob", $hash_base);
6537 } else {
6538 print "<div class=\"page_path\"></div>\n";
6541 } elsif ($format eq 'plain') {
6542 print $cgi->header(
6543 -type => 'text/plain',
6544 -charset => 'utf-8',
6545 -expires => $expires,
6546 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6548 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6550 } else {
6551 die_error(400, "Unknown blobdiff format");
6554 # patch
6555 if ($format eq 'html') {
6556 print "<div class=\"page_body\">\n";
6558 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6559 close $fd;
6561 print "</div>\n"; # class="page_body"
6562 git_footer_html();
6564 } else {
6565 while (my $line = <$fd>) {
6566 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6567 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6569 print $line;
6571 last if $line =~ m!^\+\+\+!;
6573 local $/ = undef;
6574 print <$fd>;
6575 close $fd;
6579 sub git_blobdiff_plain {
6580 git_blobdiff('plain');
6583 sub git_commitdiff {
6584 my %params = @_;
6585 my $format = $params{-format} || 'html';
6587 my ($patch_max) = gitweb_get_feature('patches');
6588 if ($format eq 'patch') {
6589 die_error(403, "Patch view not allowed") unless $patch_max;
6592 $hash ||= $hash_base || "HEAD";
6593 my %co = parse_commit($hash)
6594 or die_error(404, "Unknown commit object");
6596 # choose format for commitdiff for merge
6597 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6598 $hash_parent = '--cc';
6600 # we need to prepare $formats_nav before almost any parameter munging
6601 my $formats_nav;
6602 if ($format eq 'html') {
6603 $formats_nav =
6604 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6605 "raw");
6606 if ($patch_max && @{$co{'parents'}} <= 1) {
6607 $formats_nav .= " | " .
6608 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6609 "patch");
6612 if (defined $hash_parent &&
6613 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6614 # commitdiff with two commits given
6615 my $hash_parent_short = $hash_parent;
6616 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6617 $hash_parent_short = substr($hash_parent, 0, 7);
6619 $formats_nav .=
6620 ' (from';
6621 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6622 if ($co{'parents'}[$i] eq $hash_parent) {
6623 $formats_nav .= ' parent ' . ($i+1);
6624 last;
6627 $formats_nav .= ': ' .
6628 $cgi->a({-href => href(action=>"commitdiff",
6629 hash=>$hash_parent)},
6630 esc_html($hash_parent_short)) .
6631 ')';
6632 } elsif (!$co{'parent'}) {
6633 # --root commitdiff
6634 $formats_nav .= ' (initial)';
6635 } elsif (scalar @{$co{'parents'}} == 1) {
6636 # single parent commit
6637 $formats_nav .=
6638 ' (parent: ' .
6639 $cgi->a({-href => href(action=>"commitdiff",
6640 hash=>$co{'parent'})},
6641 esc_html(substr($co{'parent'}, 0, 7))) .
6642 ')';
6643 } else {
6644 # merge commit
6645 if ($hash_parent eq '--cc') {
6646 $formats_nav .= ' | ' .
6647 $cgi->a({-href => href(action=>"commitdiff",
6648 hash=>$hash, hash_parent=>'-c')},
6649 'combined');
6650 } else { # $hash_parent eq '-c'
6651 $formats_nav .= ' | ' .
6652 $cgi->a({-href => href(action=>"commitdiff",
6653 hash=>$hash, hash_parent=>'--cc')},
6654 'compact');
6656 $formats_nav .=
6657 ' (merge: ' .
6658 join(' ', map {
6659 $cgi->a({-href => href(action=>"commitdiff",
6660 hash=>$_)},
6661 esc_html(substr($_, 0, 7)));
6662 } @{$co{'parents'}} ) .
6663 ')';
6667 my $hash_parent_param = $hash_parent;
6668 if (!defined $hash_parent_param) {
6669 # --cc for multiple parents, --root for parentless
6670 $hash_parent_param =
6671 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6674 # read commitdiff
6675 my $fd;
6676 my @difftree;
6677 if ($format eq 'html') {
6678 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6679 "--no-commit-id", "--patch-with-raw", "--full-index",
6680 $hash_parent_param, $hash, "--"
6681 or die_error(500, "Open git-diff-tree failed");
6683 while (my $line = <$fd>) {
6684 chomp $line;
6685 # empty line ends raw part of diff-tree output
6686 last unless $line;
6687 push @difftree, scalar parse_difftree_raw_line($line);
6690 } elsif ($format eq 'plain') {
6691 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6692 '-p', $hash_parent_param, $hash, "--"
6693 or die_error(500, "Open git-diff-tree failed");
6694 } elsif ($format eq 'patch') {
6695 # For commit ranges, we limit the output to the number of
6696 # patches specified in the 'patches' feature.
6697 # For single commits, we limit the output to a single patch,
6698 # diverging from the git-format-patch default.
6699 my @commit_spec = ();
6700 if ($hash_parent) {
6701 if ($patch_max > 0) {
6702 push @commit_spec, "-$patch_max";
6704 push @commit_spec, '-n', "$hash_parent..$hash";
6705 } else {
6706 if ($params{-single}) {
6707 push @commit_spec, '-1';
6708 } else {
6709 if ($patch_max > 0) {
6710 push @commit_spec, "-$patch_max";
6712 push @commit_spec, "-n";
6714 push @commit_spec, '--root', $hash;
6716 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6717 '--encoding=utf8', '--stdout', @commit_spec
6718 or die_error(500, "Open git-format-patch failed");
6719 } else {
6720 die_error(400, "Unknown commitdiff format");
6723 # non-textual hash id's can be cached
6724 my $expires;
6725 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6726 $expires = "+1d";
6729 # write commit message
6730 if ($format eq 'html') {
6731 my $refs = git_get_references();
6732 my $ref = format_ref_marker($refs, $co{'id'});
6734 git_header_html(undef, $expires);
6735 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6736 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6737 print "<div class=\"title_text\">\n" .
6738 "<table class=\"object_header\">\n";
6739 git_print_authorship_rows(\%co);
6740 print "</table>".
6741 "</div>\n";
6742 print "<div class=\"page_body\">\n";
6743 if (@{$co{'comment'}} > 1) {
6744 print "<div class=\"log\">\n";
6745 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6746 print "</div>\n"; # class="log"
6749 } elsif ($format eq 'plain') {
6750 my $refs = git_get_references("tags");
6751 my $tagname = git_get_rev_name_tags($hash);
6752 my $filename = basename($project) . "-$hash.patch";
6754 print $cgi->header(
6755 -type => 'text/plain',
6756 -charset => 'utf-8',
6757 -expires => $expires,
6758 -content_disposition => 'inline; filename="' . "$filename" . '"');
6759 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6760 print "From: " . to_utf8($co{'author'}) . "\n";
6761 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6762 print "Subject: " . to_utf8($co{'title'}) . "\n";
6764 print "X-Git-Tag: $tagname\n" if $tagname;
6765 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6767 foreach my $line (@{$co{'comment'}}) {
6768 print to_utf8($line) . "\n";
6770 print "---\n\n";
6771 } elsif ($format eq 'patch') {
6772 my $filename = basename($project) . "-$hash.patch";
6774 print $cgi->header(
6775 -type => 'text/plain',
6776 -charset => 'utf-8',
6777 -expires => $expires,
6778 -content_disposition => 'inline; filename="' . "$filename" . '"');
6781 # write patch
6782 if ($format eq 'html') {
6783 my $use_parents = !defined $hash_parent ||
6784 $hash_parent eq '-c' || $hash_parent eq '--cc';
6785 git_difftree_body(\@difftree, $hash,
6786 $use_parents ? @{$co{'parents'}} : $hash_parent);
6787 print "<br/>\n";
6789 git_patchset_body($fd, \@difftree, $hash,
6790 $use_parents ? @{$co{'parents'}} : $hash_parent);
6791 close $fd;
6792 print "</div>\n"; # class="page_body"
6793 git_footer_html();
6795 } elsif ($format eq 'plain') {
6796 local $/ = undef;
6797 print <$fd>;
6798 close $fd
6799 or print "Reading git-diff-tree failed\n";
6800 } elsif ($format eq 'patch') {
6801 local $/ = undef;
6802 print <$fd>;
6803 close $fd
6804 or print "Reading git-format-patch failed\n";
6808 sub git_commitdiff_plain {
6809 git_commitdiff(-format => 'plain');
6812 # format-patch-style patches
6813 sub git_patch {
6814 git_commitdiff(-format => 'patch', -single => 1);
6817 sub git_patches {
6818 git_commitdiff(-format => 'patch');
6821 sub git_history {
6822 git_log_generic('history', \&git_history_body,
6823 $hash_base, $hash_parent_base,
6824 $file_name, $hash);
6827 sub git_search {
6828 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6829 if (!defined $searchtext) {
6830 die_error(400, "Text field is empty");
6832 if (!defined $hash) {
6833 $hash = git_get_head_hash($project);
6835 my %co = parse_commit($hash);
6836 if (!%co) {
6837 die_error(404, "Unknown commit object");
6839 if (!defined $page) {
6840 $page = 0;
6843 $searchtype ||= 'commit';
6844 if ($searchtype eq 'pickaxe') {
6845 # pickaxe may take all resources of your box and run for several minutes
6846 # with every query - so decide by yourself how public you make this feature
6847 gitweb_check_feature('pickaxe')
6848 or die_error(403, "Pickaxe is disabled");
6850 if ($searchtype eq 'grep') {
6851 gitweb_check_feature('grep')
6852 or die_error(403, "Grep is disabled");
6855 git_header_html();
6857 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6858 my $greptype;
6859 if ($searchtype eq 'commit') {
6860 $greptype = "--grep=";
6861 } elsif ($searchtype eq 'author') {
6862 $greptype = "--author=";
6863 } elsif ($searchtype eq 'committer') {
6864 $greptype = "--committer=";
6866 $greptype .= $searchtext;
6867 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6868 $greptype, '--regexp-ignore-case',
6869 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6871 my $paging_nav = '';
6872 if ($page > 0) {
6873 $paging_nav .=
6874 $cgi->a({-href => href(action=>"search", hash=>$hash,
6875 searchtext=>$searchtext,
6876 searchtype=>$searchtype)},
6877 "first");
6878 $paging_nav .= " &sdot; " .
6879 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6880 -accesskey => "p", -title => "Alt-p"}, "prev");
6881 } else {
6882 $paging_nav .= "first";
6883 $paging_nav .= " &sdot; prev";
6885 my $next_link = '';
6886 if ($#commitlist >= 100) {
6887 $next_link =
6888 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6889 -accesskey => "n", -title => "Alt-n"}, "next");
6890 $paging_nav .= " &sdot; $next_link";
6891 } else {
6892 $paging_nav .= " &sdot; next";
6895 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6896 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6897 if ($page == 0 && !@commitlist) {
6898 print "<p>No match.</p>\n";
6899 } else {
6900 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6904 if ($searchtype eq 'pickaxe') {
6905 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6906 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6908 print "<table class=\"pickaxe search\">\n";
6909 my $alternate = 1;
6910 local $/ = "\n";
6911 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6912 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6913 ($search_use_regexp ? '--pickaxe-regex' : ());
6914 undef %co;
6915 my @files;
6916 while (my $line = <$fd>) {
6917 chomp $line;
6918 next unless $line;
6920 my %set = parse_difftree_raw_line($line);
6921 if (defined $set{'commit'}) {
6922 # finish previous commit
6923 if (%co) {
6924 print "</td>\n" .
6925 "<td class=\"link\">" .
6926 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6927 " | " .
6928 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6929 print "</td>\n" .
6930 "</tr>\n";
6933 if ($alternate) {
6934 print "<tr class=\"dark\">\n";
6935 } else {
6936 print "<tr class=\"light\">\n";
6938 $alternate ^= 1;
6939 %co = parse_commit($set{'commit'});
6940 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6941 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6942 "<td><i>$author</i></td>\n" .
6943 "<td>" .
6944 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6945 -class => "list subject"},
6946 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6947 } elsif (defined $set{'to_id'}) {
6948 next if ($set{'to_id'} =~ m/^0{40}$/);
6950 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6951 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6952 -class => "list"},
6953 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6954 "<br/>\n";
6957 close $fd;
6959 # finish last commit (warning: repetition!)
6960 if (%co) {
6961 print "</td>\n" .
6962 "<td class=\"link\">" .
6963 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6964 " | " .
6965 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6966 print "</td>\n" .
6967 "</tr>\n";
6970 print "</table>\n";
6973 if ($searchtype eq 'grep') {
6974 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6975 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6977 print "<table class=\"grep_search\">\n";
6978 my $alternate = 1;
6979 my $matches = 0;
6980 local $/ = "\n";
6981 open my $fd, "-|", git_cmd(), 'grep', '-n',
6982 $search_use_regexp ? ('-E', '-i') : '-F',
6983 $searchtext, $co{'tree'};
6984 my $lastfile = '';
6985 while (my $line = <$fd>) {
6986 chomp $line;
6987 my ($file, $lno, $ltext, $binary);
6988 last if ($matches++ > 1000);
6989 if ($line =~ /^Binary file (.+) matches$/) {
6990 $file = $1;
6991 $binary = 1;
6992 } else {
6993 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6995 if ($file ne $lastfile) {
6996 $lastfile and print "</td></tr>\n";
6997 if ($alternate++) {
6998 print "<tr class=\"dark\">\n";
6999 } else {
7000 print "<tr class=\"light\">\n";
7002 print "<td class=\"list\">".
7003 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
7004 file_name=>"$file"),
7005 -class => "list"}, esc_path($file));
7006 print "</td><td>\n";
7007 $lastfile = $file;
7009 if ($binary) {
7010 print "<div class=\"binary\">Binary file</div>\n";
7011 } else {
7012 $ltext = untabify($ltext);
7013 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
7014 $ltext = esc_html($1, -nbsp=>1);
7015 $ltext .= '<span class="match">';
7016 $ltext .= esc_html($2, -nbsp=>1);
7017 $ltext .= '</span>';
7018 $ltext .= esc_html($3, -nbsp=>1);
7019 } else {
7020 $ltext = esc_html($ltext, -nbsp=>1);
7022 print "<div class=\"pre\">" .
7023 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
7024 file_name=>"$file").'#l'.$lno,
7025 -class => "linenr"}, sprintf('%4i', $lno))
7026 . ' ' . $ltext . "</div>\n";
7029 if ($lastfile) {
7030 print "</td></tr>\n";
7031 if ($matches > 1000) {
7032 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
7034 } else {
7035 print "<div class=\"diff nodifferences\">No matches found</div>\n";
7037 close $fd;
7039 print "</table>\n";
7041 git_footer_html();
7044 sub git_search_help {
7045 git_header_html();
7046 git_print_page_nav('','', $hash,$hash,$hash);
7047 print <<EOT;
7048 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7049 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7050 the pattern entered is recognized as the POSIX extended
7051 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7052 insensitive).</p>
7053 <dl>
7054 <dt><b>commit</b></dt>
7055 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7057 my $have_grep = gitweb_check_feature('grep');
7058 if ($have_grep) {
7059 print <<EOT;
7060 <dt><b>grep</b></dt>
7061 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7062 a different one) are searched for the given pattern. On large trees, this search can take
7063 a while and put some strain on the server, so please use it with some consideration. Note that
7064 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7065 case-sensitive.</dd>
7068 print <<EOT;
7069 <dt><b>author</b></dt>
7070 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7071 <dt><b>committer</b></dt>
7072 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7074 my $have_pickaxe = gitweb_check_feature('pickaxe');
7075 if ($have_pickaxe) {
7076 print <<EOT;
7077 <dt><b>pickaxe</b></dt>
7078 <dd>All commits that caused the string to appear or disappear from any file (changes that
7079 added, removed or "modified" the string) will be listed. This search can take a while and
7080 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7081 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7084 print "</dl>\n";
7085 git_footer_html();
7088 sub git_shortlog {
7089 git_log_generic('shortlog', \&git_shortlog_body,
7090 $hash, $hash_parent);
7093 ## ......................................................................
7094 ## feeds (RSS, Atom; OPML)
7096 sub git_feed {
7097 my $format = shift || 'atom';
7098 my $have_blame = gitweb_check_feature('blame');
7100 # Atom: http://www.atomenabled.org/developers/syndication/
7101 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7102 if ($format ne 'rss' && $format ne 'atom') {
7103 die_error(400, "Unknown web feed format");
7106 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7107 my $head = $hash || 'HEAD';
7108 my @commitlist = parse_commits($head, 150, 0, $file_name);
7110 my %latest_commit;
7111 my %latest_date;
7112 my $content_type = "application/$format+xml";
7113 if (defined $cgi->http('HTTP_ACCEPT') &&
7114 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7115 # browser (feed reader) prefers text/xml
7116 $content_type = 'text/xml';
7118 if (defined($commitlist[0])) {
7119 %latest_commit = %{$commitlist[0]};
7120 my $latest_epoch = $latest_commit{'committer_epoch'};
7121 %latest_date = parse_date($latest_epoch);
7122 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7123 if (defined $if_modified) {
7124 my $since;
7125 if (eval { require HTTP::Date; 1; }) {
7126 $since = HTTP::Date::str2time($if_modified);
7127 } elsif (eval { require Time::ParseDate; 1; }) {
7128 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7130 if (defined $since && $latest_epoch <= $since) {
7131 print $cgi->header(
7132 -type => $content_type,
7133 -charset => 'utf-8',
7134 -last_modified => $latest_date{'rfc2822'},
7135 -status => '304 Not Modified');
7136 return;
7139 print $cgi->header(
7140 -type => $content_type,
7141 -charset => 'utf-8',
7142 -last_modified => $latest_date{'rfc2822'});
7143 } else {
7144 print $cgi->header(
7145 -type => $content_type,
7146 -charset => 'utf-8');
7149 # Optimization: skip generating the body if client asks only
7150 # for Last-Modified date.
7151 return if ($cgi->request_method() eq 'HEAD');
7153 # header variables
7154 my $title = "$site_name - $project/$action";
7155 my $feed_type = 'log';
7156 if (defined $hash) {
7157 $title .= " - '$hash'";
7158 $feed_type = 'branch log';
7159 if (defined $file_name) {
7160 $title .= " :: $file_name";
7161 $feed_type = 'history';
7163 } elsif (defined $file_name) {
7164 $title .= " - $file_name";
7165 $feed_type = 'history';
7167 $title .= " $feed_type";
7168 my $descr = git_get_project_description($project);
7169 if (defined $descr) {
7170 $descr = esc_html($descr);
7171 } else {
7172 $descr = "$project " .
7173 ($format eq 'rss' ? 'RSS' : 'Atom') .
7174 " feed";
7176 my $owner = git_get_project_owner($project);
7177 $owner = esc_html($owner);
7179 #header
7180 my $alt_url;
7181 if (defined $file_name) {
7182 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7183 } elsif (defined $hash) {
7184 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7185 } else {
7186 $alt_url = href(-full=>1, action=>"summary");
7188 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7189 if ($format eq 'rss') {
7190 print <<XML;
7191 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7192 <channel>
7194 print "<title>$title</title>\n" .
7195 "<link>$alt_url</link>\n" .
7196 "<description>$descr</description>\n" .
7197 "<language>en</language>\n" .
7198 # project owner is responsible for 'editorial' content
7199 "<managingEditor>$owner</managingEditor>\n";
7200 if (defined $logo || defined $favicon) {
7201 # prefer the logo to the favicon, since RSS
7202 # doesn't allow both
7203 my $img = esc_url($logo || $favicon);
7204 print "<image>\n" .
7205 "<url>$img</url>\n" .
7206 "<title>$title</title>\n" .
7207 "<link>$alt_url</link>\n" .
7208 "</image>\n";
7210 if (%latest_date) {
7211 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7212 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7214 print "<generator>gitweb v.$version/$git_version</generator>\n";
7215 } elsif ($format eq 'atom') {
7216 print <<XML;
7217 <feed xmlns="http://www.w3.org/2005/Atom">
7219 print "<title>$title</title>\n" .
7220 "<subtitle>$descr</subtitle>\n" .
7221 '<link rel="alternate" type="text/html" href="' .
7222 $alt_url . '" />' . "\n" .
7223 '<link rel="self" type="' . $content_type . '" href="' .
7224 $cgi->self_url() . '" />' . "\n" .
7225 "<id>" . href(-full=>1) . "</id>\n" .
7226 # use project owner for feed author
7227 "<author><name>$owner</name></author>\n";
7228 if (defined $favicon) {
7229 print "<icon>" . esc_url($favicon) . "</icon>\n";
7231 if (defined $logo_url) {
7232 # not twice as wide as tall: 72 x 27 pixels
7233 print "<logo>" . esc_url($logo) . "</logo>\n";
7235 if (! %latest_date) {
7236 # dummy date to keep the feed valid until commits trickle in:
7237 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7238 } else {
7239 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7241 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7244 # contents
7245 for (my $i = 0; $i <= $#commitlist; $i++) {
7246 my %co = %{$commitlist[$i]};
7247 my $commit = $co{'id'};
7248 # we read 150, we always show 30 and the ones more recent than 48 hours
7249 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7250 last;
7252 my %cd = parse_date($co{'author_epoch'});
7254 # get list of changed files
7255 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7256 $co{'parent'} || "--root",
7257 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7258 or next;
7259 my @difftree = map { chomp; $_ } <$fd>;
7260 close $fd
7261 or next;
7263 # print element (entry, item)
7264 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7265 if ($format eq 'rss') {
7266 print "<item>\n" .
7267 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7268 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7269 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7270 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7271 "<link>$co_url</link>\n" .
7272 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7273 "<content:encoded>" .
7274 "<![CDATA[\n";
7275 } elsif ($format eq 'atom') {
7276 print "<entry>\n" .
7277 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7278 "<updated>$cd{'iso-8601'}</updated>\n" .
7279 "<author>\n" .
7280 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7281 if ($co{'author_email'}) {
7282 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7284 print "</author>\n" .
7285 # use committer for contributor
7286 "<contributor>\n" .
7287 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7288 if ($co{'committer_email'}) {
7289 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7291 print "</contributor>\n" .
7292 "<published>$cd{'iso-8601'}</published>\n" .
7293 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7294 "<id>$co_url</id>\n" .
7295 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7296 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7298 my $comment = $co{'comment'};
7299 print "<pre>\n";
7300 foreach my $line (@$comment) {
7301 $line = esc_html($line);
7302 print "$line\n";
7304 print "</pre><ul>\n";
7305 foreach my $difftree_line (@difftree) {
7306 my %difftree = parse_difftree_raw_line($difftree_line);
7307 next if !$difftree{'from_id'};
7309 my $file = $difftree{'file'} || $difftree{'to_file'};
7311 print "<li>" .
7312 "[" .
7313 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7314 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7315 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7316 file_name=>$file, file_parent=>$difftree{'from_file'}),
7317 -title => "diff"}, 'D');
7318 if ($have_blame) {
7319 print $cgi->a({-href => href(-full=>1, action=>"blame",
7320 file_name=>$file, hash_base=>$commit),
7321 -title => "blame"}, 'B');
7323 # if this is not a feed of a file history
7324 if (!defined $file_name || $file_name ne $file) {
7325 print $cgi->a({-href => href(-full=>1, action=>"history",
7326 file_name=>$file, hash=>$commit),
7327 -title => "history"}, 'H');
7329 $file = esc_path($file);
7330 print "] ".
7331 "$file</li>\n";
7333 if ($format eq 'rss') {
7334 print "</ul>]]>\n" .
7335 "</content:encoded>\n" .
7336 "</item>\n";
7337 } elsif ($format eq 'atom') {
7338 print "</ul>\n</div>\n" .
7339 "</content>\n" .
7340 "</entry>\n";
7344 # end of feed
7345 if ($format eq 'rss') {
7346 print "</channel>\n</rss>\n";
7347 } elsif ($format eq 'atom') {
7348 print "</feed>\n";
7352 sub git_rss {
7353 git_feed('rss');
7356 sub git_atom {
7357 git_feed('atom');
7360 sub git_opml {
7361 my @list = git_get_projects_list();
7363 print $cgi->header(
7364 -type => 'text/xml',
7365 -charset => 'utf-8',
7366 -content_disposition => 'inline; filename="opml.xml"');
7368 print <<XML;
7369 <?xml version="1.0" encoding="utf-8"?>
7370 <opml version="1.0">
7371 <head>
7372 <title>$site_name OPML Export</title>
7373 </head>
7374 <body>
7375 <outline text="git RSS feeds">
7378 foreach my $pr (@list) {
7379 my %proj = %$pr;
7380 my $head = git_get_head_hash($proj{'path'});
7381 if (!defined $head) {
7382 next;
7384 $git_dir = "$projectroot/$proj{'path'}";
7385 my %co = parse_commit($head);
7386 if (!%co) {
7387 next;
7390 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7391 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7392 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7393 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7395 print <<XML;
7396 </outline>
7397 </body>
7398 </opml>