gitweb: Add startup delay to activity indicator for cache
[git/jnareb-git.git] / gitweb / gitweb.perl
blobd181ba3648546d00187e83c7095da6aecc6c975e
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 # You define site-wide options for "Generating..." page (if enabled) here
370 # (which means that $cache_options{'generating_info'} is set to coderef);
371 # override them with $GITWEB_CONFIG as necessary.
372 our %generating_options = (
373 # The delay before displaying "Generating..." page, in seconds. It is
374 # intended for "Generating..." page to be shown only when really needed.
375 'startup_delay' => 1,
376 # The time between generating new piece of output to prevent from
377 # redirection before data is ready, i.e. time between printing each
378 # dot in activity indicator / progress info, in seconds.
379 'print_interval' => 2,
380 # Maximum time "Generating..." page would be present, waiting for data,
381 # before unconditional redirect, in seconds.
382 'timeout' => $cache_options{'expires_min'},
384 # Set to _initialized_ instance of GitwebCache::Capture compatibile capturing
385 # engine, i.e. one implementing ->new() constructor, and ->capture($code)
386 # method. If unset (default), the GitwebCache::Capture::Simple would be used.
387 our $capture;
389 # You define site-wide feature defaults here; override them with
390 # $GITWEB_CONFIG as necessary.
391 our %feature = (
392 # feature => {
393 # 'sub' => feature-sub (subroutine),
394 # 'override' => allow-override (boolean),
395 # 'default' => [ default options...] (array reference)}
397 # if feature is overridable (it means that allow-override has true value),
398 # then feature-sub will be called with default options as parameters;
399 # return value of feature-sub indicates if to enable specified feature
401 # if there is no 'sub' key (no feature-sub), then feature cannot be
402 # overridden
404 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
405 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
406 # is enabled
408 # Enable the 'blame' blob view, showing the last commit that modified
409 # each line in the file. This can be very CPU-intensive.
411 # To enable system wide have in $GITWEB_CONFIG
412 # $feature{'blame'}{'default'} = [1];
413 # To have project specific config enable override in $GITWEB_CONFIG
414 # $feature{'blame'}{'override'} = 1;
415 # and in project config gitweb.blame = 0|1;
416 'blame' => {
417 'sub' => sub { feature_bool('blame', @_) },
418 'override' => 0,
419 'default' => [0]},
421 # Enable the 'snapshot' link, providing a compressed archive of any
422 # tree. This can potentially generate high traffic if you have large
423 # project.
425 # Value is a list of formats defined in %known_snapshot_formats that
426 # you wish to offer.
427 # To disable system wide have in $GITWEB_CONFIG
428 # $feature{'snapshot'}{'default'} = [];
429 # To have project specific config enable override in $GITWEB_CONFIG
430 # $feature{'snapshot'}{'override'} = 1;
431 # and in project config, a comma-separated list of formats or "none"
432 # to disable. Example: gitweb.snapshot = tbz2,zip;
433 'snapshot' => {
434 'sub' => \&feature_snapshot,
435 'override' => 0,
436 'default' => ['tgz']},
438 # Enable text search, which will list the commits which match author,
439 # committer or commit text to a given string. Enabled by default.
440 # Project specific override is not supported.
441 'search' => {
442 'override' => 0,
443 'default' => [1]},
445 # Enable grep search, which will list the files in currently selected
446 # tree containing the given string. Enabled by default. This can be
447 # potentially CPU-intensive, of course.
449 # To enable system wide have in $GITWEB_CONFIG
450 # $feature{'grep'}{'default'} = [1];
451 # To have project specific config enable override in $GITWEB_CONFIG
452 # $feature{'grep'}{'override'} = 1;
453 # and in project config gitweb.grep = 0|1;
454 'grep' => {
455 'sub' => sub { feature_bool('grep', @_) },
456 'override' => 0,
457 'default' => [1]},
459 # Enable the pickaxe search, which will list the commits that modified
460 # a given string in a file. This can be practical and quite faster
461 # alternative to 'blame', but still potentially CPU-intensive.
463 # To enable system wide have in $GITWEB_CONFIG
464 # $feature{'pickaxe'}{'default'} = [1];
465 # To have project specific config enable override in $GITWEB_CONFIG
466 # $feature{'pickaxe'}{'override'} = 1;
467 # and in project config gitweb.pickaxe = 0|1;
468 'pickaxe' => {
469 'sub' => sub { feature_bool('pickaxe', @_) },
470 'override' => 0,
471 'default' => [1]},
473 # Enable showing size of blobs in a 'tree' view, in a separate
474 # column, similar to what 'ls -l' does. This cost a bit of IO.
476 # To disable system wide have in $GITWEB_CONFIG
477 # $feature{'show-sizes'}{'default'} = [0];
478 # To have project specific config enable override in $GITWEB_CONFIG
479 # $feature{'show-sizes'}{'override'} = 1;
480 # and in project config gitweb.showsizes = 0|1;
481 'show-sizes' => {
482 'sub' => sub { feature_bool('showsizes', @_) },
483 'override' => 0,
484 'default' => [1]},
486 # Make gitweb use an alternative format of the URLs which can be
487 # more readable and natural-looking: project name is embedded
488 # directly in the path and the query string contains other
489 # auxiliary information. All gitweb installations recognize
490 # URL in either format; this configures in which formats gitweb
491 # generates links.
493 # To enable system wide have in $GITWEB_CONFIG
494 # $feature{'pathinfo'}{'default'} = [1];
495 # Project specific override is not supported.
497 # Note that you will need to change the default location of CSS,
498 # favicon, logo and possibly other files to an absolute URL. Also,
499 # if gitweb.cgi serves as your indexfile, you will need to force
500 # $my_uri to contain the script name in your $GITWEB_CONFIG.
501 'pathinfo' => {
502 'override' => 0,
503 'default' => [0]},
505 # Make gitweb consider projects in project root subdirectories
506 # to be forks of existing projects. Given project $projname.git,
507 # projects matching $projname/*.git will not be shown in the main
508 # projects list, instead a '+' mark will be added to $projname
509 # there and a 'forks' view will be enabled for the project, listing
510 # all the forks. If project list is taken from a file, forks have
511 # to be listed after the main project.
513 # To enable system wide have in $GITWEB_CONFIG
514 # $feature{'forks'}{'default'} = [1];
515 # Project specific override is not supported.
516 'forks' => {
517 'override' => 0,
518 'default' => [0]},
520 # Insert custom links to the action bar of all project pages.
521 # This enables you mainly to link to third-party scripts integrating
522 # into gitweb; e.g. git-browser for graphical history representation
523 # or custom web-based repository administration interface.
525 # The 'default' value consists of a list of triplets in the form
526 # (label, link, position) where position is the label after which
527 # to insert the link and link is a format string where %n expands
528 # to the project name, %f to the project path within the filesystem,
529 # %h to the current hash (h gitweb parameter) and %b to the current
530 # hash base (hb gitweb parameter); %% expands to %.
532 # To enable system wide have in $GITWEB_CONFIG e.g.
533 # $feature{'actions'}{'default'} = [('graphiclog',
534 # '/git-browser/by-commit.html?r=%n', 'summary')];
535 # Project specific override is not supported.
536 'actions' => {
537 'override' => 0,
538 'default' => []},
540 # Allow gitweb scan project content tags described in ctags/
541 # of project repository, and display the popular Web 2.0-ish
542 # "tag cloud" near the project list. Note that this is something
543 # COMPLETELY different from the normal Git tags.
545 # gitweb by itself can show existing tags, but it does not handle
546 # tagging itself; you need an external application for that.
547 # For an example script, check Girocco's cgi/tagproj.cgi.
548 # You may want to install the HTML::TagCloud Perl module to get
549 # a pretty tag cloud instead of just a list of tags.
551 # To enable system wide have in $GITWEB_CONFIG
552 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
553 # Project specific override is not supported.
554 'ctags' => {
555 'override' => 0,
556 'default' => [0]},
558 # The maximum number of patches in a patchset generated in patch
559 # view. Set this to 0 or undef to disable patch view, or to a
560 # negative number to remove any limit.
562 # To disable system wide have in $GITWEB_CONFIG
563 # $feature{'patches'}{'default'} = [0];
564 # To have project specific config enable override in $GITWEB_CONFIG
565 # $feature{'patches'}{'override'} = 1;
566 # and in project config gitweb.patches = 0|n;
567 # where n is the maximum number of patches allowed in a patchset.
568 'patches' => {
569 'sub' => \&feature_patches,
570 'override' => 0,
571 'default' => [16]},
573 # Avatar support. When this feature is enabled, views such as
574 # shortlog or commit will display an avatar associated with
575 # the email of the committer(s) and/or author(s).
577 # Currently available providers are gravatar and picon.
578 # If an unknown provider is specified, the feature is disabled.
580 # Gravatar depends on Digest::MD5.
581 # Picon currently relies on the indiana.edu database.
583 # To enable system wide have in $GITWEB_CONFIG
584 # $feature{'avatar'}{'default'} = ['<provider>'];
585 # where <provider> is either gravatar or picon.
586 # To have project specific config enable override in $GITWEB_CONFIG
587 # $feature{'avatar'}{'override'} = 1;
588 # and in project config gitweb.avatar = <provider>;
589 'avatar' => {
590 'sub' => \&feature_avatar,
591 'override' => 0,
592 'default' => ['']},
594 # Enable displaying how much time and how many git commands
595 # it took to generate and display page. Disabled by default.
596 # Project specific override is not supported.
597 'timed' => {
598 'override' => 0,
599 'default' => [0]},
601 # Enable turning some links into links to actions which require
602 # JavaScript to run (like 'blame_incremental'). Not enabled by
603 # default. Project specific override is currently not supported.
604 'javascript-actions' => {
605 'override' => 0,
606 'default' => [0]},
608 # Syntax highlighting support. This is based on Daniel Svensson's
609 # and Sham Chukoury's work in gitweb-xmms2.git.
610 # It requires the 'highlight' program present in $PATH,
611 # and therefore is disabled by default.
613 # To enable system wide have in $GITWEB_CONFIG
614 # $feature{'highlight'}{'default'} = [1];
616 'highlight' => {
617 'sub' => sub { feature_bool('highlight', @_) },
618 'override' => 0,
619 'default' => [0]},
622 sub gitweb_get_feature {
623 my ($name) = @_;
624 return unless exists $feature{$name};
625 my ($sub, $override, @defaults) = (
626 $feature{$name}{'sub'},
627 $feature{$name}{'override'},
628 @{$feature{$name}{'default'}});
629 # project specific override is possible only if we have project
630 our $git_dir; # global variable, declared later
631 if (!$override || !defined $git_dir) {
632 return @defaults;
634 if (!defined $sub) {
635 warn "feature $name is not overridable";
636 return @defaults;
638 return $sub->(@defaults);
641 # A wrapper to check if a given feature is enabled.
642 # With this, you can say
644 # my $bool_feat = gitweb_check_feature('bool_feat');
645 # gitweb_check_feature('bool_feat') or somecode;
647 # instead of
649 # my ($bool_feat) = gitweb_get_feature('bool_feat');
650 # (gitweb_get_feature('bool_feat'))[0] or somecode;
652 sub gitweb_check_feature {
653 return (gitweb_get_feature(@_))[0];
657 sub feature_bool {
658 my $key = shift;
659 my ($val) = git_get_project_config($key, '--bool');
661 if (!defined $val) {
662 return ($_[0]);
663 } elsif ($val eq 'true') {
664 return (1);
665 } elsif ($val eq 'false') {
666 return (0);
670 sub feature_snapshot {
671 my (@fmts) = @_;
673 my ($val) = git_get_project_config('snapshot');
675 if ($val) {
676 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
679 return @fmts;
682 sub feature_patches {
683 my @val = (git_get_project_config('patches', '--int'));
685 if (@val) {
686 return @val;
689 return ($_[0]);
692 sub feature_avatar {
693 my @val = (git_get_project_config('avatar'));
695 return @val ? @val : @_;
698 # checking HEAD file with -e is fragile if the repository was
699 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
700 # and then pruned.
701 sub check_head_link {
702 my ($dir) = @_;
703 my $headfile = "$dir/HEAD";
704 return ((-e $headfile) ||
705 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
708 sub check_export_ok {
709 my ($dir) = @_;
710 return (check_head_link($dir) &&
711 (!$export_ok || -e "$dir/$export_ok") &&
712 (!$export_auth_hook || $export_auth_hook->($dir)));
715 # process alternate names for backward compatibility
716 # filter out unsupported (unknown) snapshot formats
717 sub filter_snapshot_fmts {
718 my @fmts = @_;
720 @fmts = map {
721 exists $known_snapshot_format_aliases{$_} ?
722 $known_snapshot_format_aliases{$_} : $_} @fmts;
723 @fmts = grep {
724 exists $known_snapshot_formats{$_} &&
725 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
728 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
729 sub evaluate_gitweb_config {
730 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
731 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
732 # die if there are errors parsing config file
733 if (-e $GITWEB_CONFIG) {
734 do $GITWEB_CONFIG;
735 die $@ if $@;
736 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
737 do $GITWEB_CONFIG_SYSTEM;
738 die $@ if $@;
742 # Get loadavg of system, to compare against $maxload.
743 # Currently it requires '/proc/loadavg' present to get loadavg;
744 # if it is not present it returns 0, which means no load checking.
745 sub get_loadavg {
746 if( -e '/proc/loadavg' ){
747 open my $fd, '<', '/proc/loadavg'
748 or return 0;
749 my @load = split(/\s+/, scalar <$fd>);
750 close $fd;
752 # The first three columns measure CPU and IO utilization of the last one,
753 # five, and 10 minute periods. The fourth column shows the number of
754 # currently running processes and the total number of processes in the m/n
755 # format. The last column displays the last process ID used.
756 return $load[0] || 0;
758 # additional checks for load average should go here for things that don't export
759 # /proc/loadavg
761 return 0;
764 # version of the core git binary
765 our $git_version;
766 sub evaluate_git_version {
767 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
768 $number_of_git_cmds++;
771 sub check_loadavg {
772 if (defined $maxload && get_loadavg() > $maxload) {
773 die_error(503, "The load average on the server is too high");
777 # ======================================================================
778 # input validation and dispatch
780 # input parameters can be collected from a variety of sources (presently, CGI
781 # and PATH_INFO), so we define an %input_params hash that collects them all
782 # together during validation: this allows subsequent uses (e.g. href()) to be
783 # agnostic of the parameter origin
785 our %input_params = ();
787 # input parameters are stored with the long parameter name as key. This will
788 # also be used in the href subroutine to convert parameters to their CGI
789 # equivalent, and since the href() usage is the most frequent one, we store
790 # the name -> CGI key mapping here, instead of the reverse.
792 # XXX: Warning: If you touch this, check the search form for updating,
793 # too.
795 our @cgi_param_mapping = (
796 project => "p",
797 action => "a",
798 file_name => "f",
799 file_parent => "fp",
800 hash => "h",
801 hash_parent => "hp",
802 hash_base => "hb",
803 hash_parent_base => "hpb",
804 page => "pg",
805 order => "o",
806 searchtext => "s",
807 searchtype => "st",
808 snapshot_format => "sf",
809 extra_options => "opt",
810 search_use_regexp => "sr",
811 # this must be last entry (for manipulation from JavaScript)
812 javascript => "js"
814 our %cgi_param_mapping = @cgi_param_mapping;
816 # we will also need to know the possible actions, for validation
817 our %actions = (
818 "blame" => \&git_blame,
819 "blame_incremental" => \&git_blame_incremental,
820 "blame_data" => \&git_blame_data,
821 "blobdiff" => \&git_blobdiff,
822 "blobdiff_plain" => \&git_blobdiff_plain,
823 "blob" => \&git_blob,
824 "blob_plain" => \&git_blob_plain,
825 "commitdiff" => \&git_commitdiff,
826 "commitdiff_plain" => \&git_commitdiff_plain,
827 "commit" => \&git_commit,
828 "forks" => \&git_forks,
829 "heads" => \&git_heads,
830 "history" => \&git_history,
831 "log" => \&git_log,
832 "patch" => \&git_patch,
833 "patches" => \&git_patches,
834 "rss" => \&git_rss,
835 "atom" => \&git_atom,
836 "search" => \&git_search,
837 "search_help" => \&git_search_help,
838 "shortlog" => \&git_shortlog,
839 "summary" => \&git_summary,
840 "tag" => \&git_tag,
841 "tags" => \&git_tags,
842 "tree" => \&git_tree,
843 "snapshot" => \&git_snapshot,
844 "object" => \&git_object,
845 # those below don't need $project
846 "opml" => \&git_opml,
847 "project_list" => \&git_project_list,
848 "project_index" => \&git_project_index,
851 # finally, we have the hash of allowed extra_options for the commands that
852 # allow them
853 our %allowed_options = (
854 "--no-merges" => [ qw(rss atom log shortlog history) ],
857 our %actions_info = ();
858 sub evaluate_actions_info {
859 our %actions_info;
860 our (%actions);
862 # unless explicitely stated otherwise, default output format is html
863 foreach my $action (keys %actions) {
864 $actions_info{$action}{'output_format'} = 'html';
866 # list all exceptions; undef means variable (no definite format)
867 map { $actions_info{$_}{'output_format'} = 'text' }
868 qw(commitdiff_plain patch patches project_index blame_data);
869 map { $actions_info{$_}{'output_format'} = 'xml' }
870 qw(rss atom opml); # there are different types (document formats) of XML
871 map { $actions_info{$_}{'output_format'} = undef }
872 qw(blob_plain object);
873 $actions_info{'snapshot'}{'output_format'} = 'binary';
876 sub action_outputs_html {
877 my $action = shift;
878 return $actions_info{$action}{'output_format'} eq 'html';
881 sub browser_is_robot {
882 return 1 if !exists $ENV{'HTTP_USER_AGENT'}; # gitweb run as script
883 if (eval { require HTTP::BrowserDetect; }) {
884 my $browser = HTTP::BrowserDetect->new();
885 return $browser->robot();
887 # fallback on detecting known web browsers
888 return 0 if ($ENV{'HTTP_USER_AGENT'} =~ /\b(?:Mozilla|Opera|Safari|IE)\b/);
889 # be conservative; if not sure, assume non-interactive
890 return 1;
893 # fill %input_params with the CGI parameters. All values except for 'opt'
894 # should be single values, but opt can be an array. We should probably
895 # build an array of parameters that can be multi-valued, but since for the time
896 # being it's only this one, we just single it out
897 sub evaluate_query_params {
898 our $cgi;
900 while (my ($name, $symbol) = each %cgi_param_mapping) {
901 if ($symbol eq 'opt') {
902 $input_params{$name} = [ $cgi->param($symbol) ];
903 } else {
904 $input_params{$name} = $cgi->param($symbol);
909 # now read PATH_INFO and update the parameter list for missing parameters
910 sub evaluate_path_info {
911 return if defined $input_params{'project'};
912 return if !$path_info;
913 $path_info =~ s,^/+,,;
914 return if !$path_info;
916 # find which part of PATH_INFO is project
917 my $project = $path_info;
918 $project =~ s,/+$,,;
919 while ($project && !check_head_link("$projectroot/$project")) {
920 $project =~ s,/*[^/]*$,,;
922 return unless $project;
923 $input_params{'project'} = $project;
925 # do not change any parameters if an action is given using the query string
926 return if $input_params{'action'};
927 $path_info =~ s,^\Q$project\E/*,,;
929 # next, check if we have an action
930 my $action = $path_info;
931 $action =~ s,/.*$,,;
932 if (exists $actions{$action}) {
933 $path_info =~ s,^$action/*,,;
934 $input_params{'action'} = $action;
937 # list of actions that want hash_base instead of hash, but can have no
938 # pathname (f) parameter
939 my @wants_base = (
940 'tree',
941 'history',
944 # we want to catch, among others
945 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
946 my ($parentrefname, $parentpathname, $refname, $pathname) =
947 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
949 # first, analyze the 'current' part
950 if (defined $pathname) {
951 # we got "branch:filename" or "branch:dir/"
952 # we could use git_get_type(branch:pathname), but:
953 # - it needs $git_dir
954 # - it does a git() call
955 # - the convention of terminating directories with a slash
956 # makes it superfluous
957 # - embedding the action in the PATH_INFO would make it even
958 # more superfluous
959 $pathname =~ s,^/+,,;
960 if (!$pathname || substr($pathname, -1) eq "/") {
961 $input_params{'action'} ||= "tree";
962 $pathname =~ s,/$,,;
963 } else {
964 # the default action depends on whether we had parent info
965 # or not
966 if ($parentrefname) {
967 $input_params{'action'} ||= "blobdiff_plain";
968 } else {
969 $input_params{'action'} ||= "blob_plain";
972 $input_params{'hash_base'} ||= $refname;
973 $input_params{'file_name'} ||= $pathname;
974 } elsif (defined $refname) {
975 # we got "branch". In this case we have to choose if we have to
976 # set hash or hash_base.
978 # Most of the actions without a pathname only want hash to be
979 # set, except for the ones specified in @wants_base that want
980 # hash_base instead. It should also be noted that hand-crafted
981 # links having 'history' as an action and no pathname or hash
982 # set will fail, but that happens regardless of PATH_INFO.
983 if (defined $parentrefname) {
984 # if there is parent let the default be 'shortlog' action
985 # (for http://git.example.com/repo.git/A..B links); if there
986 # is no parent, dispatch will detect type of object and set
987 # action appropriately if required (if action is not set)
988 $input_params{'action'} ||= "shortlog";
990 if ($input_params{'action'} &&
991 grep { $_ eq $input_params{'action'} } @wants_base) {
992 $input_params{'hash_base'} ||= $refname;
993 } else {
994 $input_params{'hash'} ||= $refname;
998 # next, handle the 'parent' part, if present
999 if (defined $parentrefname) {
1000 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1001 # someproject/blobdiff/oldrev..newrev:/filename
1002 if ($parentpathname) {
1003 $parentpathname =~ s,^/+,,;
1004 $parentpathname =~ s,/$,,;
1005 $input_params{'file_parent'} ||= $parentpathname;
1006 } else {
1007 $input_params{'file_parent'} ||= $input_params{'file_name'};
1009 # we assume that hash_parent_base is wanted if a path was specified,
1010 # or if the action wants hash_base instead of hash
1011 if (defined $input_params{'file_parent'} ||
1012 grep { $_ eq $input_params{'action'} } @wants_base) {
1013 $input_params{'hash_parent_base'} ||= $parentrefname;
1014 } else {
1015 $input_params{'hash_parent'} ||= $parentrefname;
1019 # for the snapshot action, we allow URLs in the form
1020 # $project/snapshot/$hash.ext
1021 # where .ext determines the snapshot and gets removed from the
1022 # passed $refname to provide the $hash.
1024 # To be able to tell that $refname includes the format extension, we
1025 # require the following two conditions to be satisfied:
1026 # - the hash input parameter MUST have been set from the $refname part
1027 # of the URL (i.e. they must be equal)
1028 # - the snapshot format MUST NOT have been defined already (e.g. from
1029 # CGI parameter sf)
1030 # It's also useless to try any matching unless $refname has a dot,
1031 # so we check for that too
1032 if (defined $input_params{'action'} &&
1033 $input_params{'action'} eq 'snapshot' &&
1034 defined $refname && index($refname, '.') != -1 &&
1035 $refname eq $input_params{'hash'} &&
1036 !defined $input_params{'snapshot_format'}) {
1037 # We loop over the known snapshot formats, checking for
1038 # extensions. Allowed extensions are both the defined suffix
1039 # (which includes the initial dot already) and the snapshot
1040 # format key itself, with a prepended dot
1041 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1042 my $hash = $refname;
1043 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1044 next;
1046 my $sfx = $1;
1047 # a valid suffix was found, so set the snapshot format
1048 # and reset the hash parameter
1049 $input_params{'snapshot_format'} = $fmt;
1050 $input_params{'hash'} = $hash;
1051 # we also set the format suffix to the one requested
1052 # in the URL: this way a request for e.g. .tgz returns
1053 # a .tgz instead of a .tar.gz
1054 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1055 last;
1060 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1061 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1062 $searchtext, $search_regexp);
1063 sub evaluate_and_validate_params {
1064 our $action = $input_params{'action'};
1065 if (defined $action) {
1066 if (!validate_action($action)) {
1067 die_error(400, "Invalid action parameter");
1071 # parameters which are pathnames
1072 our $project = $input_params{'project'};
1073 if (defined $project) {
1074 if (!validate_project($project)) {
1075 undef $project;
1076 die_error(404, "No such project");
1080 our $file_name = $input_params{'file_name'};
1081 if (defined $file_name) {
1082 if (!validate_pathname($file_name)) {
1083 die_error(400, "Invalid file parameter");
1087 our $file_parent = $input_params{'file_parent'};
1088 if (defined $file_parent) {
1089 if (!validate_pathname($file_parent)) {
1090 die_error(400, "Invalid file parent parameter");
1094 # parameters which are refnames
1095 our $hash = $input_params{'hash'};
1096 if (defined $hash) {
1097 if (!validate_refname($hash)) {
1098 die_error(400, "Invalid hash parameter");
1102 our $hash_parent = $input_params{'hash_parent'};
1103 if (defined $hash_parent) {
1104 if (!validate_refname($hash_parent)) {
1105 die_error(400, "Invalid hash parent parameter");
1109 our $hash_base = $input_params{'hash_base'};
1110 if (defined $hash_base) {
1111 if (!validate_refname($hash_base)) {
1112 die_error(400, "Invalid hash base parameter");
1116 our @extra_options = @{$input_params{'extra_options'}};
1117 # @extra_options is always defined, since it can only be (currently) set from
1118 # CGI, and $cgi->param() returns the empty array in array context if the param
1119 # is not set
1120 foreach my $opt (@extra_options) {
1121 if (not exists $allowed_options{$opt}) {
1122 die_error(400, "Invalid option parameter");
1124 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1125 die_error(400, "Invalid option parameter for this action");
1129 our $hash_parent_base = $input_params{'hash_parent_base'};
1130 if (defined $hash_parent_base) {
1131 if (!validate_refname($hash_parent_base)) {
1132 die_error(400, "Invalid hash parent base parameter");
1136 # other parameters
1137 our $page = $input_params{'page'};
1138 if (defined $page) {
1139 if ($page =~ m/[^0-9]/) {
1140 die_error(400, "Invalid page parameter");
1144 our $searchtype = $input_params{'searchtype'};
1145 if (defined $searchtype) {
1146 if ($searchtype =~ m/[^a-z]/) {
1147 die_error(400, "Invalid searchtype parameter");
1151 our $search_use_regexp = $input_params{'search_use_regexp'};
1153 our $searchtext = $input_params{'searchtext'};
1154 our $search_regexp;
1155 if (defined $searchtext) {
1156 if (length($searchtext) < 2) {
1157 die_error(403, "At least two characters are required for search parameter");
1159 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1163 # path to the current git repository
1164 our $git_dir;
1165 sub evaluate_git_dir {
1166 our $git_dir = "$projectroot/$project" if $project;
1169 our (@snapshot_fmts, $git_avatar);
1170 sub configure_gitweb_features {
1171 # list of supported snapshot formats
1172 our @snapshot_fmts = gitweb_get_feature('snapshot');
1173 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1175 # check that the avatar feature is set to a known provider name,
1176 # and for each provider check if the dependencies are satisfied.
1177 # if the provider name is invalid or the dependencies are not met,
1178 # reset $git_avatar to the empty string.
1179 our ($git_avatar) = gitweb_get_feature('avatar');
1180 if ($git_avatar eq 'gravatar') {
1181 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1182 } elsif ($git_avatar eq 'picon') {
1183 # no dependencies
1184 } else {
1185 $git_avatar = '';
1189 # custom error handler: 'die <message>' is Internal Server Error
1190 sub handle_errors_html {
1191 my $msg = shift; # it is already HTML escaped
1193 # to avoid infinite loop where error occurs in die_error,
1194 # change handler to default handler, disabling handle_errors_html
1195 set_message("Error occured when inside die_error:\n$msg");
1197 # you cannot jump out of die_error when called as error handler;
1198 # the subroutine set via CGI::Carp::set_message is called _after_
1199 # HTTP headers are already written, so it cannot write them itself
1200 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1202 set_message(\&handle_errors_html);
1204 # dispatch
1205 sub dispatch {
1206 if (!defined $action) {
1207 if (defined $hash) {
1208 $action = git_get_type($hash);
1209 } elsif (defined $hash_base && defined $file_name) {
1210 $action = git_get_type("$hash_base:$file_name");
1211 } elsif (defined $project) {
1212 $action = 'summary';
1213 } else {
1214 $action = 'project_list';
1217 if (!defined($actions{$action})) {
1218 die_error(400, "Unknown action");
1220 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1221 !$project) {
1222 die_error(400, "Project needed");
1225 if ($caching_enabled) {
1226 # human readable key identifying gitweb output
1227 my $output_key = href(-replay => 1, -full => 1, -path_info => 0);
1229 cache_output($cache, $capture, $output_key, $actions{$action});
1230 } else {
1231 $actions{$action}->();
1235 sub reset_timer {
1236 our $t0 = [Time::HiRes::gettimeofday()]
1237 if defined $t0;
1238 our $number_of_git_cmds = 0;
1241 sub run_request {
1242 reset_timer();
1244 evaluate_uri();
1245 evaluate_gitweb_config();
1246 evaluate_git_version();
1247 check_loadavg();
1248 configure_caching()
1249 if ($caching_enabled);
1251 # $projectroot and $projects_list might be set in gitweb config file
1252 $projects_list ||= $projectroot;
1254 evaluate_query_params();
1255 evaluate_path_info();
1256 evaluate_and_validate_params();
1257 evaluate_git_dir();
1259 configure_gitweb_features();
1261 dispatch();
1264 our $is_last_request = sub { 1 };
1265 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1266 our $CGI = 'CGI';
1267 our $cgi;
1268 sub configure_as_fcgi {
1269 require CGI::Fast;
1270 our $CGI = 'CGI::Fast';
1272 my $request_number = 0;
1273 # let each child service 100 requests
1274 our $is_last_request = sub { ++$request_number > 100 };
1276 sub evaluate_argv {
1277 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1278 configure_as_fcgi()
1279 if $script_name =~ /\.fcgi$/;
1281 return unless (@ARGV);
1283 require Getopt::Long;
1284 Getopt::Long::GetOptions(
1285 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1286 'nproc|n=i' => sub {
1287 my ($arg, $val) = @_;
1288 return unless eval { require FCGI::ProcManager; 1; };
1289 my $proc_manager = FCGI::ProcManager->new({
1290 n_processes => $val,
1292 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1293 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1294 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1299 sub run {
1300 evaluate_argv();
1301 evaluate_actions_info();
1303 $pre_listen_hook->()
1304 if $pre_listen_hook;
1306 REQUEST:
1307 while ($cgi = $CGI->new()) {
1308 $pre_dispatch_hook->()
1309 if $pre_dispatch_hook;
1311 run_request();
1313 $post_dispatch_hook->()
1314 if $post_dispatch_hook;
1316 last REQUEST if ($is_last_request->());
1319 DONE_GITWEB:
1323 sub configure_caching {
1324 if (!eval { require GitwebCache::CacheOutput; 1; }) {
1325 # cache is configured _before_ handling request, so $cgi is not defined,
1326 # so we can't just "die" with sending error message to web browser
1327 #die_error(500, "Caching enabled and GitwebCache::CacheOutput not found");
1329 # turn off caching and warn instead
1330 $caching_enabled = 0;
1331 warn "Caching enabled and GitwebCache::CacheOutput not found";
1333 GitwebCache::CacheOutput->import();
1335 # $cache might be initialized (instantiated) cache, i.e. cache object,
1336 # or it might be name of class, or it might be undefined
1337 unless (defined $cache && ref($cache)) {
1338 $cache ||= 'GitwebCache::FileCacheWithLocking';
1339 eval "require $cache";
1340 die $@ if $@;
1341 $cache = $cache->new({
1342 %cache_options,
1343 #'cache_root' => '/tmp/cache',
1344 #'cache_depth' => 2,
1345 #'expires_in' => 20, # in seconds (CHI compatibile)
1346 # (Cache::Cache compatibile initialization)
1347 'default_expires_in' => $cache_options{'expires_in'},
1348 # (CHI compatibile initialization)
1349 'root_dir' => $cache_options{'cache_root'},
1350 'depth' => $cache_options{'cache_depth'},
1353 unless (defined $capture && ref($capture)) {
1354 require GitwebCache::Capture::Simple;
1355 $capture = GitwebCache::Capture::Simple->new();
1359 run();
1361 if (defined caller) {
1362 # wrapped in a subroutine processing requests,
1363 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1364 return;
1365 } else {
1366 # pure CGI script, serving single request
1367 exit;
1370 ## ======================================================================
1371 ## action links
1373 # possible values of extra options
1374 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1375 # -replay => 1 - start from a current view (replay with modifications)
1376 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1377 sub href {
1378 my %params = @_;
1379 # default is to use -absolute url() i.e. $my_uri
1380 my $href = $params{-full} ? $my_url : $my_uri;
1382 $params{'project'} = $project unless exists $params{'project'};
1384 if ($params{-replay}) {
1385 while (my ($name, $symbol) = each %cgi_param_mapping) {
1386 if (!exists $params{$name}) {
1387 $params{$name} = $input_params{$name};
1392 my $use_pathinfo = gitweb_check_feature('pathinfo');
1393 if (defined $params{'project'} &&
1394 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1395 # try to put as many parameters as possible in PATH_INFO:
1396 # - project name
1397 # - action
1398 # - hash_parent or hash_parent_base:/file_parent
1399 # - hash or hash_base:/filename
1400 # - the snapshot_format as an appropriate suffix
1402 # When the script is the root DirectoryIndex for the domain,
1403 # $href here would be something like http://gitweb.example.com/
1404 # Thus, we strip any trailing / from $href, to spare us double
1405 # slashes in the final URL
1406 $href =~ s,/$,,;
1408 # Then add the project name, if present
1409 $href .= "/".esc_url($params{'project'});
1410 delete $params{'project'};
1412 # since we destructively absorb parameters, we keep this
1413 # boolean that remembers if we're handling a snapshot
1414 my $is_snapshot = $params{'action'} eq 'snapshot';
1416 # Summary just uses the project path URL, any other action is
1417 # added to the URL
1418 if (defined $params{'action'}) {
1419 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1420 delete $params{'action'};
1423 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1424 # stripping nonexistent or useless pieces
1425 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1426 || $params{'hash_parent'} || $params{'hash'});
1427 if (defined $params{'hash_base'}) {
1428 if (defined $params{'hash_parent_base'}) {
1429 $href .= esc_url($params{'hash_parent_base'});
1430 # skip the file_parent if it's the same as the file_name
1431 if (defined $params{'file_parent'}) {
1432 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1433 delete $params{'file_parent'};
1434 } elsif ($params{'file_parent'} !~ /\.\./) {
1435 $href .= ":/".esc_url($params{'file_parent'});
1436 delete $params{'file_parent'};
1439 $href .= "..";
1440 delete $params{'hash_parent'};
1441 delete $params{'hash_parent_base'};
1442 } elsif (defined $params{'hash_parent'}) {
1443 $href .= esc_url($params{'hash_parent'}). "..";
1444 delete $params{'hash_parent'};
1447 $href .= esc_url($params{'hash_base'});
1448 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1449 $href .= ":/".esc_url($params{'file_name'});
1450 delete $params{'file_name'};
1452 delete $params{'hash'};
1453 delete $params{'hash_base'};
1454 } elsif (defined $params{'hash'}) {
1455 $href .= esc_url($params{'hash'});
1456 delete $params{'hash'};
1459 # If the action was a snapshot, we can absorb the
1460 # snapshot_format parameter too
1461 if ($is_snapshot) {
1462 my $fmt = $params{'snapshot_format'};
1463 # snapshot_format should always be defined when href()
1464 # is called, but just in case some code forgets, we
1465 # fall back to the default
1466 $fmt ||= $snapshot_fmts[0];
1467 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1468 delete $params{'snapshot_format'};
1472 # now encode the parameters explicitly
1473 my @result = ();
1474 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1475 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1476 if (defined $params{$name}) {
1477 if (ref($params{$name}) eq "ARRAY") {
1478 foreach my $par (@{$params{$name}}) {
1479 push @result, $symbol . "=" . esc_param($par);
1481 } else {
1482 push @result, $symbol . "=" . esc_param($params{$name});
1486 $href .= "?" . join(';', @result) if scalar @result;
1488 return $href;
1492 ## ======================================================================
1493 ## validation, quoting/unquoting and escaping
1495 sub validate_action {
1496 my $input = shift || return undef;
1497 return undef unless exists $actions{$input};
1498 return $input;
1501 sub validate_project {
1502 my $input = shift || return undef;
1503 if (!validate_pathname($input) ||
1504 !(-d "$projectroot/$input") ||
1505 !check_export_ok("$projectroot/$input") ||
1506 ($strict_export && !project_in_list($input))) {
1507 return undef;
1508 } else {
1509 return $input;
1513 sub validate_pathname {
1514 my $input = shift || return undef;
1516 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1517 # at the beginning, at the end, and between slashes.
1518 # also this catches doubled slashes
1519 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1520 return undef;
1522 # no null characters
1523 if ($input =~ m!\0!) {
1524 return undef;
1526 return $input;
1529 sub validate_refname {
1530 my $input = shift || return undef;
1532 # textual hashes are O.K.
1533 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1534 return $input;
1536 # it must be correct pathname
1537 $input = validate_pathname($input)
1538 or return undef;
1539 # restrictions on ref name according to git-check-ref-format
1540 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1541 return undef;
1543 return $input;
1546 # decode sequences of octets in utf8 into Perl's internal form,
1547 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1548 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1549 sub to_utf8 {
1550 my $str = shift;
1551 return undef unless defined $str;
1552 if (utf8::valid($str)) {
1553 utf8::decode($str);
1554 return $str;
1555 } else {
1556 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1560 # quote unsafe chars, but keep the slash, even when it's not
1561 # correct, but quoted slashes look too horrible in bookmarks
1562 sub esc_param {
1563 my $str = shift;
1564 return undef unless defined $str;
1565 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1566 $str =~ s/ /\+/g;
1567 return $str;
1570 # quote unsafe chars in whole URL, so some characters cannot be quoted
1571 sub esc_url {
1572 my $str = shift;
1573 return undef unless defined $str;
1574 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1575 $str =~ s/ /\+/g;
1576 return $str;
1579 # replace invalid utf8 character with SUBSTITUTION sequence
1580 sub esc_html {
1581 my $str = shift;
1582 my %opts = @_;
1584 return undef unless defined $str;
1586 $str = to_utf8($str);
1587 $str = $cgi->escapeHTML($str);
1588 if ($opts{'-nbsp'}) {
1589 $str =~ s/ /&nbsp;/g;
1591 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1592 return $str;
1595 # quote control characters and escape filename to HTML
1596 sub esc_path {
1597 my $str = shift;
1598 my %opts = @_;
1600 return undef unless defined $str;
1602 $str = to_utf8($str);
1603 $str = $cgi->escapeHTML($str);
1604 if ($opts{'-nbsp'}) {
1605 $str =~ s/ /&nbsp;/g;
1607 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1608 return $str;
1611 # Make control characters "printable", using character escape codes (CEC)
1612 sub quot_cec {
1613 my $cntrl = shift;
1614 my %opts = @_;
1615 my %es = ( # character escape codes, aka escape sequences
1616 "\t" => '\t', # tab (HT)
1617 "\n" => '\n', # line feed (LF)
1618 "\r" => '\r', # carrige return (CR)
1619 "\f" => '\f', # form feed (FF)
1620 "\b" => '\b', # backspace (BS)
1621 "\a" => '\a', # alarm (bell) (BEL)
1622 "\e" => '\e', # escape (ESC)
1623 "\013" => '\v', # vertical tab (VT)
1624 "\000" => '\0', # nul character (NUL)
1626 my $chr = ( (exists $es{$cntrl})
1627 ? $es{$cntrl}
1628 : sprintf('\%2x', ord($cntrl)) );
1629 if ($opts{-nohtml}) {
1630 return $chr;
1631 } else {
1632 return "<span class=\"cntrl\">$chr</span>";
1636 # Alternatively use unicode control pictures codepoints,
1637 # Unicode "printable representation" (PR)
1638 sub quot_upr {
1639 my $cntrl = shift;
1640 my %opts = @_;
1642 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1643 if ($opts{-nohtml}) {
1644 return $chr;
1645 } else {
1646 return "<span class=\"cntrl\">$chr</span>";
1650 # git may return quoted and escaped filenames
1651 sub unquote {
1652 my $str = shift;
1654 sub unq {
1655 my $seq = shift;
1656 my %es = ( # character escape codes, aka escape sequences
1657 't' => "\t", # tab (HT, TAB)
1658 'n' => "\n", # newline (NL)
1659 'r' => "\r", # return (CR)
1660 'f' => "\f", # form feed (FF)
1661 'b' => "\b", # backspace (BS)
1662 'a' => "\a", # alarm (bell) (BEL)
1663 'e' => "\e", # escape (ESC)
1664 'v' => "\013", # vertical tab (VT)
1667 if ($seq =~ m/^[0-7]{1,3}$/) {
1668 # octal char sequence
1669 return chr(oct($seq));
1670 } elsif (exists $es{$seq}) {
1671 # C escape sequence, aka character escape code
1672 return $es{$seq};
1674 # quoted ordinary character
1675 return $seq;
1678 if ($str =~ m/^"(.*)"$/) {
1679 # needs unquoting
1680 $str = $1;
1681 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1683 return $str;
1686 # escape tabs (convert tabs to spaces)
1687 sub untabify {
1688 my $line = shift;
1690 while ((my $pos = index($line, "\t")) != -1) {
1691 if (my $count = (8 - ($pos % 8))) {
1692 my $spaces = ' ' x $count;
1693 $line =~ s/\t/$spaces/;
1697 return $line;
1700 sub project_in_list {
1701 my $project = shift;
1702 my @list = git_get_projects_list();
1703 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1706 ## ----------------------------------------------------------------------
1707 ## HTML aware string manipulation
1709 # Try to chop given string on a word boundary between position
1710 # $len and $len+$add_len. If there is no word boundary there,
1711 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1712 # (marking chopped part) would be longer than given string.
1713 sub chop_str {
1714 my $str = shift;
1715 my $len = shift;
1716 my $add_len = shift || 10;
1717 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1719 # Make sure perl knows it is utf8 encoded so we don't
1720 # cut in the middle of a utf8 multibyte char.
1721 $str = to_utf8($str);
1723 # allow only $len chars, but don't cut a word if it would fit in $add_len
1724 # if it doesn't fit, cut it if it's still longer than the dots we would add
1725 # remove chopped character entities entirely
1727 # when chopping in the middle, distribute $len into left and right part
1728 # return early if chopping wouldn't make string shorter
1729 if ($where eq 'center') {
1730 return $str if ($len + 5 >= length($str)); # filler is length 5
1731 $len = int($len/2);
1732 } else {
1733 return $str if ($len + 4 >= length($str)); # filler is length 4
1736 # regexps: ending and beginning with word part up to $add_len
1737 my $endre = qr/.{$len}\w{0,$add_len}/;
1738 my $begre = qr/\w{0,$add_len}.{$len}/;
1740 if ($where eq 'left') {
1741 $str =~ m/^(.*?)($begre)$/;
1742 my ($lead, $body) = ($1, $2);
1743 if (length($lead) > 4) {
1744 $lead = " ...";
1746 return "$lead$body";
1748 } elsif ($where eq 'center') {
1749 $str =~ m/^($endre)(.*)$/;
1750 my ($left, $str) = ($1, $2);
1751 $str =~ m/^(.*?)($begre)$/;
1752 my ($mid, $right) = ($1, $2);
1753 if (length($mid) > 5) {
1754 $mid = " ... ";
1756 return "$left$mid$right";
1758 } else {
1759 $str =~ m/^($endre)(.*)$/;
1760 my $body = $1;
1761 my $tail = $2;
1762 if (length($tail) > 4) {
1763 $tail = "... ";
1765 return "$body$tail";
1769 # takes the same arguments as chop_str, but also wraps a <span> around the
1770 # result with a title attribute if it does get chopped. Additionally, the
1771 # string is HTML-escaped.
1772 sub chop_and_escape_str {
1773 my ($str) = @_;
1775 my $chopped = chop_str(@_);
1776 if ($chopped eq $str) {
1777 return esc_html($chopped);
1778 } else {
1779 $str =~ s/[[:cntrl:]]/?/g;
1780 return $cgi->span({-title=>$str}, esc_html($chopped));
1784 ## ----------------------------------------------------------------------
1785 ## functions returning short strings
1787 # CSS class for given age value (in seconds)
1788 sub age_class {
1789 my $age = shift;
1791 if (!defined $age) {
1792 return "noage";
1793 } elsif ($age < 60*60*2) {
1794 return "age0";
1795 } elsif ($age < 60*60*24*2) {
1796 return "age1";
1797 } else {
1798 return "age2";
1802 # convert age in seconds to "nn units ago" string
1803 sub age_string {
1804 my $age = shift;
1805 my $age_str;
1807 if ($age > 60*60*24*365*2) {
1808 $age_str = (int $age/60/60/24/365);
1809 $age_str .= " years ago";
1810 } elsif ($age > 60*60*24*(365/12)*2) {
1811 $age_str = int $age/60/60/24/(365/12);
1812 $age_str .= " months ago";
1813 } elsif ($age > 60*60*24*7*2) {
1814 $age_str = int $age/60/60/24/7;
1815 $age_str .= " weeks ago";
1816 } elsif ($age > 60*60*24*2) {
1817 $age_str = int $age/60/60/24;
1818 $age_str .= " days ago";
1819 } elsif ($age > 60*60*2) {
1820 $age_str = int $age/60/60;
1821 $age_str .= " hours ago";
1822 } elsif ($age > 60*2) {
1823 $age_str = int $age/60;
1824 $age_str .= " min ago";
1825 } elsif ($age > 2) {
1826 $age_str = int $age;
1827 $age_str .= " sec ago";
1828 } else {
1829 $age_str .= " right now";
1831 return $age_str;
1834 use constant {
1835 S_IFINVALID => 0030000,
1836 S_IFGITLINK => 0160000,
1839 # submodule/subproject, a commit object reference
1840 sub S_ISGITLINK {
1841 my $mode = shift;
1843 return (($mode & S_IFMT) == S_IFGITLINK)
1846 # convert file mode in octal to symbolic file mode string
1847 sub mode_str {
1848 my $mode = oct shift;
1850 if (S_ISGITLINK($mode)) {
1851 return 'm---------';
1852 } elsif (S_ISDIR($mode & S_IFMT)) {
1853 return 'drwxr-xr-x';
1854 } elsif (S_ISLNK($mode)) {
1855 return 'lrwxrwxrwx';
1856 } elsif (S_ISREG($mode)) {
1857 # git cares only about the executable bit
1858 if ($mode & S_IXUSR) {
1859 return '-rwxr-xr-x';
1860 } else {
1861 return '-rw-r--r--';
1863 } else {
1864 return '----------';
1868 # convert file mode in octal to file type string
1869 sub file_type {
1870 my $mode = shift;
1872 if ($mode !~ m/^[0-7]+$/) {
1873 return $mode;
1874 } else {
1875 $mode = oct $mode;
1878 if (S_ISGITLINK($mode)) {
1879 return "submodule";
1880 } elsif (S_ISDIR($mode & S_IFMT)) {
1881 return "directory";
1882 } elsif (S_ISLNK($mode)) {
1883 return "symlink";
1884 } elsif (S_ISREG($mode)) {
1885 return "file";
1886 } else {
1887 return "unknown";
1891 # convert file mode in octal to file type description string
1892 sub file_type_long {
1893 my $mode = shift;
1895 if ($mode !~ m/^[0-7]+$/) {
1896 return $mode;
1897 } else {
1898 $mode = oct $mode;
1901 if (S_ISGITLINK($mode)) {
1902 return "submodule";
1903 } elsif (S_ISDIR($mode & S_IFMT)) {
1904 return "directory";
1905 } elsif (S_ISLNK($mode)) {
1906 return "symlink";
1907 } elsif (S_ISREG($mode)) {
1908 if ($mode & S_IXUSR) {
1909 return "executable";
1910 } else {
1911 return "file";
1913 } else {
1914 return "unknown";
1919 ## ----------------------------------------------------------------------
1920 ## functions returning short HTML fragments, or transforming HTML fragments
1921 ## which don't belong to other sections
1923 # format line of commit message.
1924 sub format_log_line_html {
1925 my $line = shift;
1927 $line = esc_html($line, -nbsp=>1);
1928 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1929 $cgi->a({-href => href(action=>"object", hash=>$1),
1930 -class => "text"}, $1);
1931 }eg;
1933 return $line;
1936 # format marker of refs pointing to given object
1938 # the destination action is chosen based on object type and current context:
1939 # - for annotated tags, we choose the tag view unless it's the current view
1940 # already, in which case we go to shortlog view
1941 # - for other refs, we keep the current view if we're in history, shortlog or
1942 # log view, and select shortlog otherwise
1943 sub format_ref_marker {
1944 my ($refs, $id) = @_;
1945 my $markers = '';
1947 if (defined $refs->{$id}) {
1948 foreach my $ref (@{$refs->{$id}}) {
1949 # this code exploits the fact that non-lightweight tags are the
1950 # only indirect objects, and that they are the only objects for which
1951 # we want to use tag instead of shortlog as action
1952 my ($type, $name) = qw();
1953 my $indirect = ($ref =~ s/\^\{\}$//);
1954 # e.g. tags/v2.6.11 or heads/next
1955 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1956 $type = $1;
1957 $name = $2;
1958 } else {
1959 $type = "ref";
1960 $name = $ref;
1963 my $class = $type;
1964 $class .= " indirect" if $indirect;
1966 my $dest_action = "shortlog";
1968 if ($indirect) {
1969 $dest_action = "tag" unless $action eq "tag";
1970 } elsif ($action =~ /^(history|(short)?log)$/) {
1971 $dest_action = $action;
1974 my $dest = "";
1975 $dest .= "refs/" unless $ref =~ m!^refs/!;
1976 $dest .= $ref;
1978 my $link = $cgi->a({
1979 -href => href(
1980 action=>$dest_action,
1981 hash=>$dest
1982 )}, $name);
1984 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1985 $link . "</span>";
1989 if ($markers) {
1990 return ' <span class="refs">'. $markers . '</span>';
1991 } else {
1992 return "";
1996 # format, perhaps shortened and with markers, title line
1997 sub format_subject_html {
1998 my ($long, $short, $href, $extra) = @_;
1999 $extra = '' unless defined($extra);
2001 if (length($short) < length($long)) {
2002 $long =~ s/[[:cntrl:]]/?/g;
2003 return $cgi->a({-href => $href, -class => "list subject",
2004 -title => to_utf8($long)},
2005 esc_html($short)) . $extra;
2006 } else {
2007 return $cgi->a({-href => $href, -class => "list subject"},
2008 esc_html($long)) . $extra;
2012 # Rather than recomputing the url for an email multiple times, we cache it
2013 # after the first hit. This gives a visible benefit in views where the avatar
2014 # for the same email is used repeatedly (e.g. shortlog).
2015 # The cache is shared by all avatar engines (currently gravatar only), which
2016 # are free to use it as preferred. Since only one avatar engine is used for any
2017 # given page, there's no risk for cache conflicts.
2018 our %avatar_cache = ();
2020 # Compute the picon url for a given email, by using the picon search service over at
2021 # http://www.cs.indiana.edu/picons/search.html
2022 sub picon_url {
2023 my $email = lc shift;
2024 if (!$avatar_cache{$email}) {
2025 my ($user, $domain) = split('@', $email);
2026 $avatar_cache{$email} =
2027 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2028 "$domain/$user/" .
2029 "users+domains+unknown/up/single";
2031 return $avatar_cache{$email};
2034 # Compute the gravatar url for a given email, if it's not in the cache already.
2035 # Gravatar stores only the part of the URL before the size, since that's the
2036 # one computationally more expensive. This also allows reuse of the cache for
2037 # different sizes (for this particular engine).
2038 sub gravatar_url {
2039 my $email = lc shift;
2040 my $size = shift;
2041 $avatar_cache{$email} ||=
2042 "http://www.gravatar.com/avatar/" .
2043 Digest::MD5::md5_hex($email) . "?s=";
2044 return $avatar_cache{$email} . $size;
2047 # Insert an avatar for the given $email at the given $size if the feature
2048 # is enabled.
2049 sub git_get_avatar {
2050 my ($email, %opts) = @_;
2051 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2052 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2053 $opts{-size} ||= 'default';
2054 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2055 my $url = "";
2056 if ($git_avatar eq 'gravatar') {
2057 $url = gravatar_url($email, $size);
2058 } elsif ($git_avatar eq 'picon') {
2059 $url = picon_url($email);
2061 # Other providers can be added by extending the if chain, defining $url
2062 # as needed. If no variant puts something in $url, we assume avatars
2063 # are completely disabled/unavailable.
2064 if ($url) {
2065 return $pre_white .
2066 "<img width=\"$size\" " .
2067 "class=\"avatar\" " .
2068 "src=\"$url\" " .
2069 "alt=\"\" " .
2070 "/>" . $post_white;
2071 } else {
2072 return "";
2076 sub format_search_author {
2077 my ($author, $searchtype, $displaytext) = @_;
2078 my $have_search = gitweb_check_feature('search');
2080 if ($have_search) {
2081 my $performed = "";
2082 if ($searchtype eq 'author') {
2083 $performed = "authored";
2084 } elsif ($searchtype eq 'committer') {
2085 $performed = "committed";
2088 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2089 searchtext=>$author,
2090 searchtype=>$searchtype), class=>"list",
2091 title=>"Search for commits $performed by $author"},
2092 $displaytext);
2094 } else {
2095 return $displaytext;
2099 # format the author name of the given commit with the given tag
2100 # the author name is chopped and escaped according to the other
2101 # optional parameters (see chop_str).
2102 sub format_author_html {
2103 my $tag = shift;
2104 my $co = shift;
2105 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2106 return "<$tag class=\"author\">" .
2107 format_search_author($co->{'author_name'}, "author",
2108 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2109 $author) .
2110 "</$tag>";
2113 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2114 sub format_git_diff_header_line {
2115 my $line = shift;
2116 my $diffinfo = shift;
2117 my ($from, $to) = @_;
2119 if ($diffinfo->{'nparents'}) {
2120 # combined diff
2121 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2122 if ($to->{'href'}) {
2123 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2124 esc_path($to->{'file'}));
2125 } else { # file was deleted (no href)
2126 $line .= esc_path($to->{'file'});
2128 } else {
2129 # "ordinary" diff
2130 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2131 if ($from->{'href'}) {
2132 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2133 'a/' . esc_path($from->{'file'}));
2134 } else { # file was added (no href)
2135 $line .= 'a/' . esc_path($from->{'file'});
2137 $line .= ' ';
2138 if ($to->{'href'}) {
2139 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2140 'b/' . esc_path($to->{'file'}));
2141 } else { # file was deleted
2142 $line .= 'b/' . esc_path($to->{'file'});
2146 return "<div class=\"diff header\">$line</div>\n";
2149 # format extended diff header line, before patch itself
2150 sub format_extended_diff_header_line {
2151 my $line = shift;
2152 my $diffinfo = shift;
2153 my ($from, $to) = @_;
2155 # match <path>
2156 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2157 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2158 esc_path($from->{'file'}));
2160 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2161 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2162 esc_path($to->{'file'}));
2164 # match single <mode>
2165 if ($line =~ m/\s(\d{6})$/) {
2166 $line .= '<span class="info"> (' .
2167 file_type_long($1) .
2168 ')</span>';
2170 # match <hash>
2171 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2172 # can match only for combined diff
2173 $line = 'index ';
2174 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2175 if ($from->{'href'}[$i]) {
2176 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2177 -class=>"hash"},
2178 substr($diffinfo->{'from_id'}[$i],0,7));
2179 } else {
2180 $line .= '0' x 7;
2182 # separator
2183 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2185 $line .= '..';
2186 if ($to->{'href'}) {
2187 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2188 substr($diffinfo->{'to_id'},0,7));
2189 } else {
2190 $line .= '0' x 7;
2193 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2194 # can match only for ordinary diff
2195 my ($from_link, $to_link);
2196 if ($from->{'href'}) {
2197 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2198 substr($diffinfo->{'from_id'},0,7));
2199 } else {
2200 $from_link = '0' x 7;
2202 if ($to->{'href'}) {
2203 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2204 substr($diffinfo->{'to_id'},0,7));
2205 } else {
2206 $to_link = '0' x 7;
2208 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2209 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2212 return $line . "<br/>\n";
2215 # format from-file/to-file diff header
2216 sub format_diff_from_to_header {
2217 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2218 my $line;
2219 my $result = '';
2221 $line = $from_line;
2222 #assert($line =~ m/^---/) if DEBUG;
2223 # no extra formatting for "^--- /dev/null"
2224 if (! $diffinfo->{'nparents'}) {
2225 # ordinary (single parent) diff
2226 if ($line =~ m!^--- "?a/!) {
2227 if ($from->{'href'}) {
2228 $line = '--- a/' .
2229 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2230 esc_path($from->{'file'}));
2231 } else {
2232 $line = '--- a/' .
2233 esc_path($from->{'file'});
2236 $result .= qq!<div class="diff from_file">$line</div>\n!;
2238 } else {
2239 # combined diff (merge commit)
2240 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2241 if ($from->{'href'}[$i]) {
2242 $line = '--- ' .
2243 $cgi->a({-href=>href(action=>"blobdiff",
2244 hash_parent=>$diffinfo->{'from_id'}[$i],
2245 hash_parent_base=>$parents[$i],
2246 file_parent=>$from->{'file'}[$i],
2247 hash=>$diffinfo->{'to_id'},
2248 hash_base=>$hash,
2249 file_name=>$to->{'file'}),
2250 -class=>"path",
2251 -title=>"diff" . ($i+1)},
2252 $i+1) .
2253 '/' .
2254 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2255 esc_path($from->{'file'}[$i]));
2256 } else {
2257 $line = '--- /dev/null';
2259 $result .= qq!<div class="diff from_file">$line</div>\n!;
2263 $line = $to_line;
2264 #assert($line =~ m/^\+\+\+/) if DEBUG;
2265 # no extra formatting for "^+++ /dev/null"
2266 if ($line =~ m!^\+\+\+ "?b/!) {
2267 if ($to->{'href'}) {
2268 $line = '+++ b/' .
2269 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2270 esc_path($to->{'file'}));
2271 } else {
2272 $line = '+++ b/' .
2273 esc_path($to->{'file'});
2276 $result .= qq!<div class="diff to_file">$line</div>\n!;
2278 return $result;
2281 # create note for patch simplified by combined diff
2282 sub format_diff_cc_simplified {
2283 my ($diffinfo, @parents) = @_;
2284 my $result = '';
2286 $result .= "<div class=\"diff header\">" .
2287 "diff --cc ";
2288 if (!is_deleted($diffinfo)) {
2289 $result .= $cgi->a({-href => href(action=>"blob",
2290 hash_base=>$hash,
2291 hash=>$diffinfo->{'to_id'},
2292 file_name=>$diffinfo->{'to_file'}),
2293 -class => "path"},
2294 esc_path($diffinfo->{'to_file'}));
2295 } else {
2296 $result .= esc_path($diffinfo->{'to_file'});
2298 $result .= "</div>\n" . # class="diff header"
2299 "<div class=\"diff nodifferences\">" .
2300 "Simple merge" .
2301 "</div>\n"; # class="diff nodifferences"
2303 return $result;
2306 # format patch (diff) line (not to be used for diff headers)
2307 sub format_diff_line {
2308 my $line = shift;
2309 my ($from, $to) = @_;
2310 my $diff_class = "";
2312 chomp $line;
2314 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2315 # combined diff
2316 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2317 if ($line =~ m/^\@{3}/) {
2318 $diff_class = " chunk_header";
2319 } elsif ($line =~ m/^\\/) {
2320 $diff_class = " incomplete";
2321 } elsif ($prefix =~ tr/+/+/) {
2322 $diff_class = " add";
2323 } elsif ($prefix =~ tr/-/-/) {
2324 $diff_class = " rem";
2326 } else {
2327 # assume ordinary diff
2328 my $char = substr($line, 0, 1);
2329 if ($char eq '+') {
2330 $diff_class = " add";
2331 } elsif ($char eq '-') {
2332 $diff_class = " rem";
2333 } elsif ($char eq '@') {
2334 $diff_class = " chunk_header";
2335 } elsif ($char eq "\\") {
2336 $diff_class = " incomplete";
2339 $line = untabify($line);
2340 if ($from && $to && $line =~ m/^\@{2} /) {
2341 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2342 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2344 $from_lines = 0 unless defined $from_lines;
2345 $to_lines = 0 unless defined $to_lines;
2347 if ($from->{'href'}) {
2348 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2349 -class=>"list"}, $from_text);
2351 if ($to->{'href'}) {
2352 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2353 -class=>"list"}, $to_text);
2355 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2356 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2357 return "<div class=\"diff$diff_class\">$line</div>\n";
2358 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2359 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2360 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2362 @from_text = split(' ', $ranges);
2363 for (my $i = 0; $i < @from_text; ++$i) {
2364 ($from_start[$i], $from_nlines[$i]) =
2365 (split(',', substr($from_text[$i], 1)), 0);
2368 $to_text = pop @from_text;
2369 $to_start = pop @from_start;
2370 $to_nlines = pop @from_nlines;
2372 $line = "<span class=\"chunk_info\">$prefix ";
2373 for (my $i = 0; $i < @from_text; ++$i) {
2374 if ($from->{'href'}[$i]) {
2375 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2376 -class=>"list"}, $from_text[$i]);
2377 } else {
2378 $line .= $from_text[$i];
2380 $line .= " ";
2382 if ($to->{'href'}) {
2383 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2384 -class=>"list"}, $to_text);
2385 } else {
2386 $line .= $to_text;
2388 $line .= " $prefix</span>" .
2389 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2390 return "<div class=\"diff$diff_class\">$line</div>\n";
2392 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2395 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2396 # linked. Pass the hash of the tree/commit to snapshot.
2397 sub format_snapshot_links {
2398 my ($hash) = @_;
2399 my $num_fmts = @snapshot_fmts;
2400 if ($num_fmts > 1) {
2401 # A parenthesized list of links bearing format names.
2402 # e.g. "snapshot (_tar.gz_ _zip_)"
2403 return "snapshot (" . join(' ', map
2404 $cgi->a({
2405 -href => href(
2406 action=>"snapshot",
2407 hash=>$hash,
2408 snapshot_format=>$_
2410 }, $known_snapshot_formats{$_}{'display'})
2411 , @snapshot_fmts) . ")";
2412 } elsif ($num_fmts == 1) {
2413 # A single "snapshot" link whose tooltip bears the format name.
2414 # i.e. "_snapshot_"
2415 my ($fmt) = @snapshot_fmts;
2416 return
2417 $cgi->a({
2418 -href => href(
2419 action=>"snapshot",
2420 hash=>$hash,
2421 snapshot_format=>$fmt
2423 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2424 }, "snapshot");
2425 } else { # $num_fmts == 0
2426 return undef;
2430 ## ......................................................................
2431 ## functions returning values to be passed, perhaps after some
2432 ## transformation, to other functions; e.g. returning arguments to href()
2434 # returns hash to be passed to href to generate gitweb URL
2435 # in -title key it returns description of link
2436 sub get_feed_info {
2437 my $format = shift || 'Atom';
2438 my %res = (action => lc($format));
2440 # feed links are possible only for project views
2441 return unless (defined $project);
2442 # some views should link to OPML, or to generic project feed,
2443 # or don't have specific feed yet (so they should use generic)
2444 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2446 my $branch;
2447 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2448 # from tag links; this also makes possible to detect branch links
2449 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2450 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2451 $branch = $1;
2453 # find log type for feed description (title)
2454 my $type = 'log';
2455 if (defined $file_name) {
2456 $type = "history of $file_name";
2457 $type .= "/" if ($action eq 'tree');
2458 $type .= " on '$branch'" if (defined $branch);
2459 } else {
2460 $type = "log of $branch" if (defined $branch);
2463 $res{-title} = $type;
2464 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2465 $res{'file_name'} = $file_name;
2467 return %res;
2470 ## ----------------------------------------------------------------------
2471 ## git utility subroutines, invoking git commands
2473 # returns path to the core git executable and the --git-dir parameter as list
2474 sub git_cmd {
2475 $number_of_git_cmds++;
2476 return $GIT, '--git-dir='.$git_dir;
2479 # quote the given arguments for passing them to the shell
2480 # quote_command("command", "arg 1", "arg with ' and ! characters")
2481 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2482 # Try to avoid using this function wherever possible.
2483 sub quote_command {
2484 return join(' ',
2485 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2488 # get HEAD ref of given project as hash
2489 sub git_get_head_hash {
2490 return git_get_full_hash(shift, 'HEAD');
2493 sub git_get_full_hash {
2494 return git_get_hash(@_);
2497 sub git_get_short_hash {
2498 return git_get_hash(@_, '--short=7');
2501 sub git_get_hash {
2502 my ($project, $hash, @options) = @_;
2503 my $o_git_dir = $git_dir;
2504 my $retval = undef;
2505 $git_dir = "$projectroot/$project";
2506 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2507 '--verify', '-q', @options, $hash) {
2508 $retval = <$fd>;
2509 chomp $retval if defined $retval;
2510 close $fd;
2512 if (defined $o_git_dir) {
2513 $git_dir = $o_git_dir;
2515 return $retval;
2518 # get type of given object
2519 sub git_get_type {
2520 my $hash = shift;
2522 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2523 my $type = <$fd>;
2524 close $fd or return;
2525 chomp $type;
2526 return $type;
2529 # repository configuration
2530 our $config_file = '';
2531 our %config;
2533 # store multiple values for single key as anonymous array reference
2534 # single values stored directly in the hash, not as [ <value> ]
2535 sub hash_set_multi {
2536 my ($hash, $key, $value) = @_;
2538 if (!exists $hash->{$key}) {
2539 $hash->{$key} = $value;
2540 } elsif (!ref $hash->{$key}) {
2541 $hash->{$key} = [ $hash->{$key}, $value ];
2542 } else {
2543 push @{$hash->{$key}}, $value;
2547 # return hash of git project configuration
2548 # optionally limited to some section, e.g. 'gitweb'
2549 sub git_parse_project_config {
2550 my $section_regexp = shift;
2551 my %config;
2553 local $/ = "\0";
2555 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2556 or return;
2558 while (my $keyval = <$fh>) {
2559 chomp $keyval;
2560 my ($key, $value) = split(/\n/, $keyval, 2);
2562 hash_set_multi(\%config, $key, $value)
2563 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2565 close $fh;
2567 return %config;
2570 # convert config value to boolean: 'true' or 'false'
2571 # no value, number > 0, 'true' and 'yes' values are true
2572 # rest of values are treated as false (never as error)
2573 sub config_to_bool {
2574 my $val = shift;
2576 return 1 if !defined $val; # section.key
2578 # strip leading and trailing whitespace
2579 $val =~ s/^\s+//;
2580 $val =~ s/\s+$//;
2582 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2583 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2586 # convert config value to simple decimal number
2587 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2588 # to be multiplied by 1024, 1048576, or 1073741824
2589 sub config_to_int {
2590 my $val = shift;
2592 # strip leading and trailing whitespace
2593 $val =~ s/^\s+//;
2594 $val =~ s/\s+$//;
2596 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2597 $unit = lc($unit);
2598 # unknown unit is treated as 1
2599 return $num * ($unit eq 'g' ? 1073741824 :
2600 $unit eq 'm' ? 1048576 :
2601 $unit eq 'k' ? 1024 : 1);
2603 return $val;
2606 # convert config value to array reference, if needed
2607 sub config_to_multi {
2608 my $val = shift;
2610 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2613 sub git_get_project_config {
2614 my ($key, $type) = @_;
2616 return unless defined $git_dir;
2618 # key sanity check
2619 return unless ($key);
2620 $key =~ s/^gitweb\.//;
2621 return if ($key =~ m/\W/);
2623 # type sanity check
2624 if (defined $type) {
2625 $type =~ s/^--//;
2626 $type = undef
2627 unless ($type eq 'bool' || $type eq 'int');
2630 # get config
2631 if (!defined $config_file ||
2632 $config_file ne "$git_dir/config") {
2633 %config = git_parse_project_config('gitweb');
2634 $config_file = "$git_dir/config";
2637 # check if config variable (key) exists
2638 return unless exists $config{"gitweb.$key"};
2640 # ensure given type
2641 if (!defined $type) {
2642 return $config{"gitweb.$key"};
2643 } elsif ($type eq 'bool') {
2644 # backward compatibility: 'git config --bool' returns true/false
2645 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2646 } elsif ($type eq 'int') {
2647 return config_to_int($config{"gitweb.$key"});
2649 return $config{"gitweb.$key"};
2652 # get hash of given path at given ref
2653 sub git_get_hash_by_path {
2654 my $base = shift;
2655 my $path = shift || return undef;
2656 my $type = shift;
2658 $path =~ s,/+$,,;
2660 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2661 or die_error(500, "Open git-ls-tree failed");
2662 my $line = <$fd>;
2663 close $fd or return undef;
2665 if (!defined $line) {
2666 # there is no tree or hash given by $path at $base
2667 return undef;
2670 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2671 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2672 if (defined $type && $type ne $2) {
2673 # type doesn't match
2674 return undef;
2676 return $3;
2679 # get path of entry with given hash at given tree-ish (ref)
2680 # used to get 'from' filename for combined diff (merge commit) for renames
2681 sub git_get_path_by_hash {
2682 my $base = shift || return;
2683 my $hash = shift || return;
2685 local $/ = "\0";
2687 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2688 or return undef;
2689 while (my $line = <$fd>) {
2690 chomp $line;
2692 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2693 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2694 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2695 close $fd;
2696 return $1;
2699 close $fd;
2700 return undef;
2703 ## ......................................................................
2704 ## git utility functions, directly accessing git repository
2706 sub git_get_project_description {
2707 my $path = shift;
2709 $git_dir = "$projectroot/$path";
2710 open my $fd, '<', "$git_dir/description"
2711 or return git_get_project_config('description');
2712 my $descr = <$fd>;
2713 close $fd;
2714 if (defined $descr) {
2715 chomp $descr;
2717 return $descr;
2720 sub git_get_project_ctags {
2721 my $path = shift;
2722 my $ctags = {};
2724 $git_dir = "$projectroot/$path";
2725 opendir my $dh, "$git_dir/ctags"
2726 or return $ctags;
2727 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2728 open my $ct, '<', $_ or next;
2729 my $val = <$ct>;
2730 chomp $val;
2731 close $ct;
2732 my $ctag = $_; $ctag =~ s#.*/##;
2733 $ctags->{$ctag} = $val;
2735 closedir $dh;
2736 $ctags;
2739 sub git_populate_project_tagcloud {
2740 my $ctags = shift;
2742 # First, merge different-cased tags; tags vote on casing
2743 my %ctags_lc;
2744 foreach (keys %$ctags) {
2745 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2746 if (not $ctags_lc{lc $_}->{topcount}
2747 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2748 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2749 $ctags_lc{lc $_}->{topname} = $_;
2753 my $cloud;
2754 if (eval { require HTML::TagCloud; 1; }) {
2755 $cloud = HTML::TagCloud->new;
2756 foreach (sort keys %ctags_lc) {
2757 # Pad the title with spaces so that the cloud looks
2758 # less crammed.
2759 my $title = $ctags_lc{$_}->{topname};
2760 $title =~ s/ /&nbsp;/g;
2761 $title =~ s/^/&nbsp;/g;
2762 $title =~ s/$/&nbsp;/g;
2763 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2765 } else {
2766 $cloud = \%ctags_lc;
2768 $cloud;
2771 sub git_show_project_tagcloud {
2772 my ($cloud, $count) = @_;
2773 print STDERR ref($cloud)."..\n";
2774 if (ref $cloud eq 'HTML::TagCloud') {
2775 return $cloud->html_and_css($count);
2776 } else {
2777 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2778 return '<p align="center">' . join (', ', map {
2779 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2780 } splice(@tags, 0, $count)) . '</p>';
2784 sub git_get_project_url_list {
2785 my $path = shift;
2787 $git_dir = "$projectroot/$path";
2788 open my $fd, '<', "$git_dir/cloneurl"
2789 or return wantarray ?
2790 @{ config_to_multi(git_get_project_config('url')) } :
2791 config_to_multi(git_get_project_config('url'));
2792 my @git_project_url_list = map { chomp; $_ } <$fd>;
2793 close $fd;
2795 return wantarray ? @git_project_url_list : \@git_project_url_list;
2798 sub git_get_projects_list {
2799 my ($filter) = @_;
2800 my @list;
2802 $filter ||= '';
2803 $filter =~ s/\.git$//;
2805 my $check_forks = gitweb_check_feature('forks');
2807 if (-d $projects_list) {
2808 # search in directory
2809 my $dir = $projects_list . ($filter ? "/$filter" : '');
2810 # remove the trailing "/"
2811 $dir =~ s!/+$!!;
2812 my $pfxlen = length("$dir");
2813 my $pfxdepth = ($dir =~ tr!/!!);
2815 File::Find::find({
2816 follow_fast => 1, # follow symbolic links
2817 follow_skip => 2, # ignore duplicates
2818 dangling_symlinks => 0, # ignore dangling symlinks, silently
2819 wanted => sub {
2820 # global variables
2821 our $project_maxdepth;
2822 our $projectroot;
2823 # skip project-list toplevel, if we get it.
2824 return if (m!^[/.]$!);
2825 # only directories can be git repositories
2826 return unless (-d $_);
2827 # don't traverse too deep (Find is super slow on os x)
2828 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2829 $File::Find::prune = 1;
2830 return;
2833 my $subdir = substr($File::Find::name, $pfxlen + 1);
2834 # we check related file in $projectroot
2835 my $path = ($filter ? "$filter/" : '') . $subdir;
2836 if (check_export_ok("$projectroot/$path")) {
2837 push @list, { path => $path };
2838 $File::Find::prune = 1;
2841 }, "$dir");
2843 } elsif (-f $projects_list) {
2844 # read from file(url-encoded):
2845 # 'git%2Fgit.git Linus+Torvalds'
2846 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2847 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2848 my %paths;
2849 open my $fd, '<', $projects_list or return;
2850 PROJECT:
2851 while (my $line = <$fd>) {
2852 chomp $line;
2853 my ($path, $owner) = split ' ', $line;
2854 $path = unescape($path);
2855 $owner = unescape($owner);
2856 if (!defined $path) {
2857 next;
2859 if ($filter ne '') {
2860 # looking for forks;
2861 my $pfx = substr($path, 0, length($filter));
2862 if ($pfx ne $filter) {
2863 next PROJECT;
2865 my $sfx = substr($path, length($filter));
2866 if ($sfx !~ /^\/.*\.git$/) {
2867 next PROJECT;
2869 } elsif ($check_forks) {
2870 PATH:
2871 foreach my $filter (keys %paths) {
2872 # looking for forks;
2873 my $pfx = substr($path, 0, length($filter));
2874 if ($pfx ne $filter) {
2875 next PATH;
2877 my $sfx = substr($path, length($filter));
2878 if ($sfx !~ /^\/.*\.git$/) {
2879 next PATH;
2881 # is a fork, don't include it in
2882 # the list
2883 next PROJECT;
2886 if (check_export_ok("$projectroot/$path")) {
2887 my $pr = {
2888 path => $path,
2889 owner => to_utf8($owner),
2891 push @list, $pr;
2892 (my $forks_path = $path) =~ s/\.git$//;
2893 $paths{$forks_path}++;
2896 close $fd;
2898 return @list;
2901 our $gitweb_project_owner = undef;
2902 sub git_get_project_list_from_file {
2904 return if (defined $gitweb_project_owner);
2906 $gitweb_project_owner = {};
2907 # read from file (url-encoded):
2908 # 'git%2Fgit.git Linus+Torvalds'
2909 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2910 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2911 if (-f $projects_list) {
2912 open(my $fd, '<', $projects_list);
2913 while (my $line = <$fd>) {
2914 chomp $line;
2915 my ($pr, $ow) = split ' ', $line;
2916 $pr = unescape($pr);
2917 $ow = unescape($ow);
2918 $gitweb_project_owner->{$pr} = to_utf8($ow);
2920 close $fd;
2924 sub git_get_project_owner {
2925 my $project = shift;
2926 my $owner;
2928 return undef unless $project;
2929 $git_dir = "$projectroot/$project";
2931 if (!defined $gitweb_project_owner) {
2932 git_get_project_list_from_file();
2935 if (exists $gitweb_project_owner->{$project}) {
2936 $owner = $gitweb_project_owner->{$project};
2938 if (!defined $owner){
2939 $owner = git_get_project_config('owner');
2941 if (!defined $owner) {
2942 $owner = get_file_owner("$git_dir");
2945 return $owner;
2948 sub git_get_last_activity {
2949 my ($path) = @_;
2950 my $fd;
2952 $git_dir = "$projectroot/$path";
2953 open($fd, "-|", git_cmd(), 'for-each-ref',
2954 '--format=%(committer)',
2955 '--sort=-committerdate',
2956 '--count=1',
2957 'refs/heads') or return;
2958 my $most_recent = <$fd>;
2959 close $fd or return;
2960 if (defined $most_recent &&
2961 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2962 my $timestamp = $1;
2963 my $age = time - $timestamp;
2964 return ($age, age_string($age));
2966 return (undef, undef);
2969 sub git_get_references {
2970 my $type = shift || "";
2971 my %refs;
2972 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2973 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2974 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2975 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2976 or return;
2978 while (my $line = <$fd>) {
2979 chomp $line;
2980 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2981 if (defined $refs{$1}) {
2982 push @{$refs{$1}}, $2;
2983 } else {
2984 $refs{$1} = [ $2 ];
2988 close $fd or return;
2989 return \%refs;
2992 sub git_get_rev_name_tags {
2993 my $hash = shift || return undef;
2995 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2996 or return;
2997 my $name_rev = <$fd>;
2998 close $fd;
3000 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3001 return $1;
3002 } else {
3003 # catches also '$hash undefined' output
3004 return undef;
3008 ## ----------------------------------------------------------------------
3009 ## parse to hash functions
3011 sub parse_date {
3012 my $epoch = shift;
3013 my $tz = shift || "-0000";
3015 my %date;
3016 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3017 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3018 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3019 $date{'hour'} = $hour;
3020 $date{'minute'} = $min;
3021 $date{'mday'} = $mday;
3022 $date{'day'} = $days[$wday];
3023 $date{'month'} = $months[$mon];
3024 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3025 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3026 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3027 $mday, $months[$mon], $hour ,$min;
3028 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3029 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3031 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
3032 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
3033 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3034 $date{'hour_local'} = $hour;
3035 $date{'minute_local'} = $min;
3036 $date{'tz_local'} = $tz;
3037 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3038 1900+$year, $mon+1, $mday,
3039 $hour, $min, $sec, $tz);
3040 return %date;
3043 sub parse_tag {
3044 my $tag_id = shift;
3045 my %tag;
3046 my @comment;
3048 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3049 $tag{'id'} = $tag_id;
3050 while (my $line = <$fd>) {
3051 chomp $line;
3052 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3053 $tag{'object'} = $1;
3054 } elsif ($line =~ m/^type (.+)$/) {
3055 $tag{'type'} = $1;
3056 } elsif ($line =~ m/^tag (.+)$/) {
3057 $tag{'name'} = $1;
3058 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3059 $tag{'author'} = $1;
3060 $tag{'author_epoch'} = $2;
3061 $tag{'author_tz'} = $3;
3062 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3063 $tag{'author_name'} = $1;
3064 $tag{'author_email'} = $2;
3065 } else {
3066 $tag{'author_name'} = $tag{'author'};
3068 } elsif ($line =~ m/--BEGIN/) {
3069 push @comment, $line;
3070 last;
3071 } elsif ($line eq "") {
3072 last;
3075 push @comment, <$fd>;
3076 $tag{'comment'} = \@comment;
3077 close $fd or return;
3078 if (!defined $tag{'name'}) {
3079 return
3081 return %tag
3084 sub parse_commit_text {
3085 my ($commit_text, $withparents) = @_;
3086 my @commit_lines = split '\n', $commit_text;
3087 my %co;
3089 pop @commit_lines; # Remove '\0'
3091 if (! @commit_lines) {
3092 return;
3095 my $header = shift @commit_lines;
3096 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3097 return;
3099 ($co{'id'}, my @parents) = split ' ', $header;
3100 while (my $line = shift @commit_lines) {
3101 last if $line eq "\n";
3102 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3103 $co{'tree'} = $1;
3104 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3105 push @parents, $1;
3106 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3107 $co{'author'} = to_utf8($1);
3108 $co{'author_epoch'} = $2;
3109 $co{'author_tz'} = $3;
3110 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3111 $co{'author_name'} = $1;
3112 $co{'author_email'} = $2;
3113 } else {
3114 $co{'author_name'} = $co{'author'};
3116 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3117 $co{'committer'} = to_utf8($1);
3118 $co{'committer_epoch'} = $2;
3119 $co{'committer_tz'} = $3;
3120 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3121 $co{'committer_name'} = $1;
3122 $co{'committer_email'} = $2;
3123 } else {
3124 $co{'committer_name'} = $co{'committer'};
3128 if (!defined $co{'tree'}) {
3129 return;
3131 $co{'parents'} = \@parents;
3132 $co{'parent'} = $parents[0];
3134 foreach my $title (@commit_lines) {
3135 $title =~ s/^ //;
3136 if ($title ne "") {
3137 $co{'title'} = chop_str($title, 80, 5);
3138 # remove leading stuff of merges to make the interesting part visible
3139 if (length($title) > 50) {
3140 $title =~ s/^Automatic //;
3141 $title =~ s/^merge (of|with) /Merge ... /i;
3142 if (length($title) > 50) {
3143 $title =~ s/(http|rsync):\/\///;
3145 if (length($title) > 50) {
3146 $title =~ s/(master|www|rsync)\.//;
3148 if (length($title) > 50) {
3149 $title =~ s/kernel.org:?//;
3151 if (length($title) > 50) {
3152 $title =~ s/\/pub\/scm//;
3155 $co{'title_short'} = chop_str($title, 50, 5);
3156 last;
3159 if (! defined $co{'title'} || $co{'title'} eq "") {
3160 $co{'title'} = $co{'title_short'} = '(no commit message)';
3162 # remove added spaces
3163 foreach my $line (@commit_lines) {
3164 $line =~ s/^ //;
3166 $co{'comment'} = \@commit_lines;
3168 my $age = time - $co{'committer_epoch'};
3169 $co{'age'} = $age;
3170 $co{'age_string'} = age_string($age);
3171 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3172 if ($age > 60*60*24*7*2) {
3173 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3174 $co{'age_string_age'} = $co{'age_string'};
3175 } else {
3176 $co{'age_string_date'} = $co{'age_string'};
3177 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3179 return %co;
3182 sub parse_commit {
3183 my ($commit_id) = @_;
3184 my %co;
3186 local $/ = "\0";
3188 open my $fd, "-|", git_cmd(), "rev-list",
3189 "--parents",
3190 "--header",
3191 "--max-count=1",
3192 $commit_id,
3193 "--",
3194 or die_error(500, "Open git-rev-list failed");
3195 %co = parse_commit_text(<$fd>, 1);
3196 close $fd;
3198 return %co;
3201 sub parse_commits {
3202 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3203 my @cos;
3205 $maxcount ||= 1;
3206 $skip ||= 0;
3208 local $/ = "\0";
3210 open my $fd, "-|", git_cmd(), "rev-list",
3211 "--header",
3212 @args,
3213 ("--max-count=" . $maxcount),
3214 ("--skip=" . $skip),
3215 @extra_options,
3216 $commit_id,
3217 "--",
3218 ($filename ? ($filename) : ())
3219 or die_error(500, "Open git-rev-list failed");
3220 while (my $line = <$fd>) {
3221 my %co = parse_commit_text($line);
3222 push @cos, \%co;
3224 close $fd;
3226 return wantarray ? @cos : \@cos;
3229 # parse line of git-diff-tree "raw" output
3230 sub parse_difftree_raw_line {
3231 my $line = shift;
3232 my %res;
3234 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3235 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3236 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3237 $res{'from_mode'} = $1;
3238 $res{'to_mode'} = $2;
3239 $res{'from_id'} = $3;
3240 $res{'to_id'} = $4;
3241 $res{'status'} = $5;
3242 $res{'similarity'} = $6;
3243 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3244 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3245 } else {
3246 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3249 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3250 # combined diff (for merge commit)
3251 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3252 $res{'nparents'} = length($1);
3253 $res{'from_mode'} = [ split(' ', $2) ];
3254 $res{'to_mode'} = pop @{$res{'from_mode'}};
3255 $res{'from_id'} = [ split(' ', $3) ];
3256 $res{'to_id'} = pop @{$res{'from_id'}};
3257 $res{'status'} = [ split('', $4) ];
3258 $res{'to_file'} = unquote($5);
3260 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3261 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3262 $res{'commit'} = $1;
3265 return wantarray ? %res : \%res;
3268 # wrapper: return parsed line of git-diff-tree "raw" output
3269 # (the argument might be raw line, or parsed info)
3270 sub parsed_difftree_line {
3271 my $line_or_ref = shift;
3273 if (ref($line_or_ref) eq "HASH") {
3274 # pre-parsed (or generated by hand)
3275 return $line_or_ref;
3276 } else {
3277 return parse_difftree_raw_line($line_or_ref);
3281 # parse line of git-ls-tree output
3282 sub parse_ls_tree_line {
3283 my $line = shift;
3284 my %opts = @_;
3285 my %res;
3287 if ($opts{'-l'}) {
3288 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3289 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3291 $res{'mode'} = $1;
3292 $res{'type'} = $2;
3293 $res{'hash'} = $3;
3294 $res{'size'} = $4;
3295 if ($opts{'-z'}) {
3296 $res{'name'} = $5;
3297 } else {
3298 $res{'name'} = unquote($5);
3300 } else {
3301 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3302 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3304 $res{'mode'} = $1;
3305 $res{'type'} = $2;
3306 $res{'hash'} = $3;
3307 if ($opts{'-z'}) {
3308 $res{'name'} = $4;
3309 } else {
3310 $res{'name'} = unquote($4);
3314 return wantarray ? %res : \%res;
3317 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3318 sub parse_from_to_diffinfo {
3319 my ($diffinfo, $from, $to, @parents) = @_;
3321 if ($diffinfo->{'nparents'}) {
3322 # combined diff
3323 $from->{'file'} = [];
3324 $from->{'href'} = [];
3325 fill_from_file_info($diffinfo, @parents)
3326 unless exists $diffinfo->{'from_file'};
3327 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3328 $from->{'file'}[$i] =
3329 defined $diffinfo->{'from_file'}[$i] ?
3330 $diffinfo->{'from_file'}[$i] :
3331 $diffinfo->{'to_file'};
3332 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3333 $from->{'href'}[$i] = href(action=>"blob",
3334 hash_base=>$parents[$i],
3335 hash=>$diffinfo->{'from_id'}[$i],
3336 file_name=>$from->{'file'}[$i]);
3337 } else {
3338 $from->{'href'}[$i] = undef;
3341 } else {
3342 # ordinary (not combined) diff
3343 $from->{'file'} = $diffinfo->{'from_file'};
3344 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3345 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3346 hash=>$diffinfo->{'from_id'},
3347 file_name=>$from->{'file'});
3348 } else {
3349 delete $from->{'href'};
3353 $to->{'file'} = $diffinfo->{'to_file'};
3354 if (!is_deleted($diffinfo)) { # file exists in result
3355 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3356 hash=>$diffinfo->{'to_id'},
3357 file_name=>$to->{'file'});
3358 } else {
3359 delete $to->{'href'};
3363 ## ......................................................................
3364 ## parse to array of hashes functions
3366 sub git_get_heads_list {
3367 my $limit = shift;
3368 my @headslist;
3370 open my $fd, '-|', git_cmd(), 'for-each-ref',
3371 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3372 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3373 'refs/heads'
3374 or return;
3375 while (my $line = <$fd>) {
3376 my %ref_item;
3378 chomp $line;
3379 my ($refinfo, $committerinfo) = split(/\0/, $line);
3380 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3381 my ($committer, $epoch, $tz) =
3382 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3383 $ref_item{'fullname'} = $name;
3384 $name =~ s!^refs/heads/!!;
3386 $ref_item{'name'} = $name;
3387 $ref_item{'id'} = $hash;
3388 $ref_item{'title'} = $title || '(no commit message)';
3389 $ref_item{'epoch'} = $epoch;
3390 if ($epoch) {
3391 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3392 } else {
3393 $ref_item{'age'} = "unknown";
3396 push @headslist, \%ref_item;
3398 close $fd;
3400 return wantarray ? @headslist : \@headslist;
3403 sub git_get_tags_list {
3404 my $limit = shift;
3405 my @tagslist;
3407 open my $fd, '-|', git_cmd(), 'for-each-ref',
3408 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3409 '--format=%(objectname) %(objecttype) %(refname) '.
3410 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3411 'refs/tags'
3412 or return;
3413 while (my $line = <$fd>) {
3414 my %ref_item;
3416 chomp $line;
3417 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3418 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3419 my ($creator, $epoch, $tz) =
3420 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3421 $ref_item{'fullname'} = $name;
3422 $name =~ s!^refs/tags/!!;
3424 $ref_item{'type'} = $type;
3425 $ref_item{'id'} = $id;
3426 $ref_item{'name'} = $name;
3427 if ($type eq "tag") {
3428 $ref_item{'subject'} = $title;
3429 $ref_item{'reftype'} = $reftype;
3430 $ref_item{'refid'} = $refid;
3431 } else {
3432 $ref_item{'reftype'} = $type;
3433 $ref_item{'refid'} = $id;
3436 if ($type eq "tag" || $type eq "commit") {
3437 $ref_item{'epoch'} = $epoch;
3438 if ($epoch) {
3439 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3440 } else {
3441 $ref_item{'age'} = "unknown";
3445 push @tagslist, \%ref_item;
3447 close $fd;
3449 return wantarray ? @tagslist : \@tagslist;
3452 ## ----------------------------------------------------------------------
3453 ## filesystem-related functions
3455 sub get_file_owner {
3456 my $path = shift;
3458 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3459 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3460 if (!defined $gcos) {
3461 return undef;
3463 my $owner = $gcos;
3464 $owner =~ s/[,;].*$//;
3465 return to_utf8($owner);
3468 # assume that file exists
3469 sub insert_file {
3470 my $filename = shift;
3472 open my $fd, '<', $filename;
3473 print map { to_utf8($_) } <$fd>;
3474 close $fd;
3477 ## ......................................................................
3478 ## mimetype related functions
3480 sub mimetype_guess_file {
3481 my $filename = shift;
3482 my $mimemap = shift;
3483 -r $mimemap or return undef;
3485 my %mimemap;
3486 open(my $mh, '<', $mimemap) or return undef;
3487 while (<$mh>) {
3488 next if m/^#/; # skip comments
3489 my ($mimetype, $exts) = split(/\t+/);
3490 if (defined $exts) {
3491 my @exts = split(/\s+/, $exts);
3492 foreach my $ext (@exts) {
3493 $mimemap{$ext} = $mimetype;
3497 close($mh);
3499 $filename =~ /\.([^.]*)$/;
3500 return $mimemap{$1};
3503 sub mimetype_guess {
3504 my $filename = shift;
3505 my $mime;
3506 $filename =~ /\./ or return undef;
3508 if ($mimetypes_file) {
3509 my $file = $mimetypes_file;
3510 if ($file !~ m!^/!) { # if it is relative path
3511 # it is relative to project
3512 $file = "$projectroot/$project/$file";
3514 $mime = mimetype_guess_file($filename, $file);
3516 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3517 return $mime;
3520 sub blob_mimetype {
3521 my $fd = shift;
3522 my $filename = shift;
3524 if ($filename) {
3525 my $mime = mimetype_guess($filename);
3526 $mime and return $mime;
3529 # just in case
3530 return $default_blob_plain_mimetype unless $fd;
3532 if (-T $fd) {
3533 return 'text/plain';
3534 } elsif (! $filename) {
3535 return 'application/octet-stream';
3536 } elsif ($filename =~ m/\.png$/i) {
3537 return 'image/png';
3538 } elsif ($filename =~ m/\.gif$/i) {
3539 return 'image/gif';
3540 } elsif ($filename =~ m/\.jpe?g$/i) {
3541 return 'image/jpeg';
3542 } else {
3543 return 'application/octet-stream';
3547 sub blob_contenttype {
3548 my ($fd, $file_name, $type) = @_;
3550 $type ||= blob_mimetype($fd, $file_name);
3551 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3552 $type .= "; charset=$default_text_plain_charset";
3555 return $type;
3558 # guess file syntax for syntax highlighting; return undef if no highlighting
3559 # the name of syntax can (in the future) depend on syntax highlighter used
3560 sub guess_file_syntax {
3561 my ($highlight, $mimetype, $file_name) = @_;
3562 return undef unless ($highlight && defined $file_name);
3563 my $basename = basename($file_name, '.in');
3564 return $highlight_basename{$basename}
3565 if exists $highlight_basename{$basename};
3567 $basename =~ /\.([^.]*)$/;
3568 my $ext = $1 or return undef;
3569 return $highlight_ext{$ext}
3570 if exists $highlight_ext{$ext};
3572 return undef;
3575 # run highlighter and return FD of its output,
3576 # or return original FD if no highlighting
3577 sub run_highlighter {
3578 my ($fd, $highlight, $syntax) = @_;
3579 return $fd unless ($highlight && defined $syntax);
3581 close $fd
3582 or die_error(404, "Reading blob failed");
3583 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3584 quote_command($highlight_bin).
3585 " --xhtml --fragment --syntax $syntax |"
3586 or die_error(500, "Couldn't open file or run syntax highlighter");
3587 return $fd;
3590 ## ======================================================================
3591 ## functions printing HTML: header, footer, error page
3593 sub get_page_title {
3594 my $title = to_utf8($site_name);
3596 return $title unless (defined $project);
3597 $title .= " - " . to_utf8($project);
3599 return $title unless (defined $action);
3600 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3602 return $title unless (defined $file_name);
3603 $title .= " - " . esc_path($file_name);
3604 if ($action eq "tree" && $file_name !~ m|/$|) {
3605 $title .= "/";
3608 return $title;
3611 # creates "Generating..." page when caching enabled and not in cache
3612 sub git_generating_data_html {
3613 my ($cache, $key, $lock_fh) = @_;
3615 # whitelist of actions that should get "Generating..." page
3616 if (!action_outputs_html($action) ||
3617 browser_is_robot()) {
3618 return;
3621 # Initial delay
3622 if ($generating_options{'startup_delay'} > 0) {
3623 eval {
3624 local $SIG{ALRM} = sub { die "alarm clock restart\n" }; # NB: \n required
3625 alarm $generating_options{'startup_delay'};
3626 flock($lock_fh, LOCK_SH); # blocking readers lock
3627 alarm 0;
3629 if ($@) {
3630 # propagate unexpected errors
3631 die $@ if $@ !~ /alarm clock restart/;
3632 } else {
3633 # we got response within 'startup_delay' timeout
3634 return;
3638 my $title = "[Generating...] " . get_page_title();
3639 # TODO: the following line of code duplicates the one
3640 # in git_header_html, and it should probably be refactored.
3641 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3643 # Use the trick that 'refresh' HTTP header equivalent (set via http-equiv)
3644 # with timeout of 0 seconds would redirect as soon as page is finished.
3645 # It assumes that browser would display partially received page.
3646 # This "Generating..." redirect page should not be cached (externally).
3647 my %no_cache = (
3648 # HTTP/1.0
3649 -Pragma => 'no-cache',
3650 # HTTP/1.1
3651 -Cache_Control => join(', ', qw(private no-cache no-store must-revalidate
3652 max-age=0 pre-check=0 post-check=0)),
3654 print STDOUT $cgi->header(-type => 'text/html', -charset => 'utf-8',
3655 -status=> '200 OK', -expires => 'now',
3656 %no_cache);
3657 print STDOUT <<"EOF";
3658 <?xml version="1.0" encoding="utf-8"?>
3659 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3660 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3661 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3662 <!-- git web interface version $version -->
3663 <!-- git core binaries version $git_version -->
3664 <head>
3665 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
3666 <meta http-equiv="refresh" content="0" />
3667 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version" />
3668 <meta name="robots" content="noindex, nofollow" />
3669 <title>$title</title>
3670 </head>
3671 <body>
3674 local $| = 1; # autoflush
3675 print STDOUT 'Generating...';
3677 my $total_time = 0;
3678 my $interval = $generating_options{'print_interval'} || 1;
3679 my $timeout = $generating_options{'timeout'};
3680 my $alarm_handler = sub {
3681 local $! = 1;
3682 print STDOUT '.';
3683 $total_time += $interval;
3684 if ($total_time > $timeout) {
3685 die "timeout\n";
3688 eval {
3689 local $SIG{ALRM} = $alarm_handler;
3690 Time::HiRes::alarm($interval, $interval);
3691 my $lock_acquired;
3692 do {
3693 # loop is needed here because SIGALRM (from 'alarm')
3694 # can interrupt process of acquiring lock
3695 $lock_acquired = flock($lock_fh, LOCK_SH); # blocking readers lock
3696 } until ($lock_acquired);
3697 alarm 0;
3699 # It doesn't really matter if we got lock, or timed-out
3700 # but we should re-throw unknown (unexpected) errors
3701 die $@ if ($@ and $@ !~ /timeout/);
3703 print STDOUT <<"EOF";
3705 </body>
3706 </html>
3709 # after refresh web browser would reload page and send new request
3710 goto DONE_GITWEB;
3711 #exit 0;
3712 #return;
3715 sub git_header_html {
3716 my $status = shift || "200 OK";
3717 my $expires = shift;
3718 my %opts = @_;
3720 my $title = get_page_title();
3721 my $content_type;
3722 # require explicit support from the UA if we are to send the page as
3723 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3724 # we have to do this because MSIE sometimes globs '*/*', pretending to
3725 # support xhtml+xml but choking when it gets what it asked for.
3726 # Disable content-type negotiation when caching (use mimetype good for all).
3727 if (!$caching_enabled &&
3728 defined $cgi->http('HTTP_ACCEPT') &&
3729 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3730 $cgi->Accept('application/xhtml+xml') != 0) {
3731 $content_type = 'application/xhtml+xml';
3732 } else {
3733 $content_type = 'text/html';
3735 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3736 -status=> $status, -expires => $expires)
3737 unless ($opts{'-no_http_header'});
3738 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3739 print <<EOF;
3740 <?xml version="1.0" encoding="utf-8"?>
3741 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3742 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3743 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3744 <!-- git core binaries version $git_version -->
3745 <head>
3746 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3747 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3748 <meta name="robots" content="index, nofollow"/>
3749 <title>$title</title>
3751 # the stylesheet, favicon etc urls won't work correctly with path_info
3752 # unless we set the appropriate base URL
3753 # if caching is enabled we can get it from cache for path_info when it
3754 # is generated without path_info
3755 if ($ENV{'PATH_INFO'} || $caching_enabled) {
3756 print "<base href=\"".esc_url($base_url)."\" />\n";
3758 # print out each stylesheet that exist, providing backwards capability
3759 # for those people who defined $stylesheet in a config file
3760 if (defined $stylesheet) {
3761 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3762 } else {
3763 foreach my $stylesheet (@stylesheets) {
3764 next unless $stylesheet;
3765 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3768 if (defined $project) {
3769 my %href_params = get_feed_info();
3770 if (!exists $href_params{'-title'}) {
3771 $href_params{'-title'} = 'log';
3774 foreach my $format qw(RSS Atom) {
3775 my $type = lc($format);
3776 my %link_attr = (
3777 '-rel' => 'alternate',
3778 '-title' => "$project - $href_params{'-title'} - $format feed",
3779 '-type' => "application/$type+xml"
3782 $href_params{'action'} = $type;
3783 $link_attr{'-href'} = href(%href_params);
3784 print "<link ".
3785 "rel=\"$link_attr{'-rel'}\" ".
3786 "title=\"$link_attr{'-title'}\" ".
3787 "href=\"$link_attr{'-href'}\" ".
3788 "type=\"$link_attr{'-type'}\" ".
3789 "/>\n";
3791 $href_params{'extra_options'} = '--no-merges';
3792 $link_attr{'-href'} = href(%href_params);
3793 $link_attr{'-title'} .= ' (no merges)';
3794 print "<link ".
3795 "rel=\"$link_attr{'-rel'}\" ".
3796 "title=\"$link_attr{'-title'}\" ".
3797 "href=\"$link_attr{'-href'}\" ".
3798 "type=\"$link_attr{'-type'}\" ".
3799 "/>\n";
3802 } else {
3803 printf('<link rel="alternate" title="%s projects list" '.
3804 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3805 $site_name, href(project=>undef, action=>"project_index"));
3806 printf('<link rel="alternate" title="%s projects feeds" '.
3807 'href="%s" type="text/x-opml" />'."\n",
3808 $site_name, href(project=>undef, action=>"opml"));
3810 if (defined $favicon) {
3811 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3814 print "</head>\n" .
3815 "<body>\n";
3817 if (defined $site_header && -f $site_header) {
3818 insert_file($site_header);
3821 print "<div class=\"page_header\">\n" .
3822 $cgi->a({-href => esc_url($logo_url),
3823 -title => $logo_label},
3824 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3825 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3826 if (defined $project) {
3827 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3828 if (defined $action) {
3829 print " / $action";
3831 print "\n";
3833 print "</div>\n";
3835 my $have_search = gitweb_check_feature('search');
3836 if (defined $project && $have_search) {
3837 if (!defined $searchtext) {
3838 $searchtext = "";
3840 my $search_hash;
3841 if (defined $hash_base) {
3842 $search_hash = $hash_base;
3843 } elsif (defined $hash) {
3844 $search_hash = $hash;
3845 } else {
3846 $search_hash = "HEAD";
3848 my $action = $my_uri;
3849 my $use_pathinfo = gitweb_check_feature('pathinfo');
3850 if ($use_pathinfo) {
3851 $action .= "/".esc_url($project);
3853 print $cgi->startform(-method => "get", -action => $action) .
3854 "<div class=\"search\">\n" .
3855 (!$use_pathinfo &&
3856 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3857 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3858 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3859 $cgi->popup_menu(-name => 'st', -default => 'commit',
3860 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3861 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3862 " search:\n",
3863 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3864 "<span title=\"Extended regular expression\">" .
3865 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3866 -checked => $search_use_regexp) .
3867 "</span>" .
3868 "</div>" .
3869 $cgi->end_form() . "\n";
3873 sub git_footer_html {
3874 my $feed_class = 'rss_logo';
3876 print "<div class=\"page_footer\">\n";
3877 if (defined $project) {
3878 my $descr = git_get_project_description($project);
3879 if (defined $descr) {
3880 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3883 my %href_params = get_feed_info();
3884 if (!%href_params) {
3885 $feed_class .= ' generic';
3887 $href_params{'-title'} ||= 'log';
3889 foreach my $format qw(RSS Atom) {
3890 $href_params{'action'} = lc($format);
3891 print $cgi->a({-href => href(%href_params),
3892 -title => "$href_params{'-title'} $format feed",
3893 -class => $feed_class}, $format)."\n";
3896 } else {
3897 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3898 -class => $feed_class}, "OPML") . " ";
3899 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3900 -class => $feed_class}, "TXT") . "\n";
3902 print "</div>\n"; # class="page_footer"
3904 # timing info doesn't make much sense with output (response) caching,
3905 # so when caching is enabled gitweb prints the time of page generation
3906 if ((defined $t0 || $caching_enabled) &&
3907 gitweb_check_feature('timed')) {
3908 print "<div id=\"generating_info\">\n";
3909 if ($caching_enabled) {
3910 print 'This page was generated at '.
3911 gmtime( time() )." GMT\n";
3912 } else {
3913 print 'This page took '.
3914 '<span id="generating_time" class="time_span">'.
3915 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3916 ' seconds </span>'.
3917 ' and '.
3918 '<span id="generating_cmd">'.
3919 $number_of_git_cmds.
3920 '</span> git commands '.
3921 " to generate.\n";
3923 print "</div>\n"; # class="page_footer"
3926 if (defined $site_footer && -f $site_footer) {
3927 insert_file($site_footer);
3930 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3931 if (!$caching_enabled &&
3932 defined $action && $action eq 'blame_incremental') {
3933 print qq!<script type="text/javascript">\n!.
3934 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3935 qq! "!. href() .qq!");\n!.
3936 qq!</script>\n!;
3937 } elsif (gitweb_check_feature('javascript-actions')) {
3938 print qq!<script type="text/javascript">\n!.
3939 qq!window.onload = fixLinks;\n!.
3940 qq!</script>\n!;
3943 print "</body>\n" .
3944 "</html>";
3947 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3948 # Example: die_error(404, 'Hash not found')
3949 # By convention, use the following status codes (as defined in RFC 2616):
3950 # 400: Invalid or missing CGI parameters, or
3951 # requested object exists but has wrong type.
3952 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3953 # this server or project.
3954 # 404: Requested object/revision/project doesn't exist.
3955 # 500: The server isn't configured properly, or
3956 # an internal error occurred (e.g. failed assertions caused by bugs), or
3957 # an unknown error occurred (e.g. the git binary died unexpectedly).
3958 # 503: The server is currently unavailable (because it is overloaded,
3959 # or down for maintenance). Generally, this is a temporary state.
3960 sub die_error {
3961 my $status = shift || 500;
3962 my $error = esc_html(shift) || "Internal Server Error";
3963 my $extra = shift;
3964 my %opts = @_;
3966 my %http_responses = (
3967 400 => '400 Bad Request',
3968 403 => '403 Forbidden',
3969 404 => '404 Not Found',
3970 500 => '500 Internal Server Error',
3971 503 => '503 Service Unavailable',
3974 # Do not cache error pages
3975 capture_stop($cache, $capture) if ($capture && $caching_enabled);
3977 git_header_html($http_responses{$status}, undef, %opts);
3978 print <<EOF;
3979 <div class="page_body">
3980 <br /><br />
3981 $status - $error
3982 <br />
3984 if (defined $extra) {
3985 print "<hr />\n" .
3986 "$extra\n";
3988 print "</div>\n";
3990 git_footer_html();
3991 goto DONE_GITWEB
3992 unless ($opts{'-error_handler'});
3995 ## ----------------------------------------------------------------------
3996 ## functions printing or outputting HTML: navigation
3998 sub git_print_page_nav {
3999 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4000 $extra = '' if !defined $extra; # pager or formats
4002 my @navs = qw(summary shortlog log commit commitdiff tree);
4003 if ($suppress) {
4004 @navs = grep { $_ ne $suppress } @navs;
4007 my %arg = map { $_ => {action=>$_} } @navs;
4008 if (defined $head) {
4009 for (qw(commit commitdiff)) {
4010 $arg{$_}{'hash'} = $head;
4012 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4013 for (qw(shortlog log)) {
4014 $arg{$_}{'hash'} = $head;
4019 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4020 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4022 my @actions = gitweb_get_feature('actions');
4023 my %repl = (
4024 '%' => '%',
4025 'n' => $project, # project name
4026 'f' => $git_dir, # project path within filesystem
4027 'h' => $treehead || '', # current hash ('h' parameter)
4028 'b' => $treebase || '', # hash base ('hb' parameter)
4030 while (@actions) {
4031 my ($label, $link, $pos) = splice(@actions,0,3);
4032 # insert
4033 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4034 # munch munch
4035 $link =~ s/%([%nfhb])/$repl{$1}/g;
4036 $arg{$label}{'_href'} = $link;
4039 print "<div class=\"page_nav\">\n" .
4040 (join " | ",
4041 map { $_ eq $current ?
4042 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4043 } @navs);
4044 print "<br/>\n$extra<br/>\n" .
4045 "</div>\n";
4048 sub format_paging_nav {
4049 my ($action, $page, $has_next_link) = @_;
4050 my $paging_nav;
4053 if ($page > 0) {
4054 $paging_nav .=
4055 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4056 " &sdot; " .
4057 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4058 -accesskey => "p", -title => "Alt-p"}, "prev");
4059 } else {
4060 $paging_nav .= "first &sdot; prev";
4063 if ($has_next_link) {
4064 $paging_nav .= " &sdot; " .
4065 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4066 -accesskey => "n", -title => "Alt-n"}, "next");
4067 } else {
4068 $paging_nav .= " &sdot; next";
4071 return $paging_nav;
4074 ## ......................................................................
4075 ## functions printing or outputting HTML: div
4077 sub git_print_header_div {
4078 my ($action, $title, $hash, $hash_base) = @_;
4079 my %args = ();
4081 $args{'action'} = $action;
4082 $args{'hash'} = $hash if $hash;
4083 $args{'hash_base'} = $hash_base if $hash_base;
4085 print "<div class=\"header\">\n" .
4086 $cgi->a({-href => href(%args), -class => "title"},
4087 $title ? $title : $action) .
4088 "\n</div>\n";
4091 sub print_local_time {
4092 print format_local_time(@_);
4095 sub format_local_time {
4096 my $localtime = '';
4097 my %date = @_;
4098 if ($date{'hour_local'} < 6) {
4099 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4100 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4101 } else {
4102 $localtime .= sprintf(" (%02d:%02d %s)",
4103 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4106 return $localtime;
4109 # Outputs the author name and date in long form
4110 sub git_print_authorship {
4111 my $co = shift;
4112 my %opts = @_;
4113 my $tag = $opts{-tag} || 'div';
4114 my $author = $co->{'author_name'};
4116 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4117 print "<$tag class=\"author_date\">" .
4118 format_search_author($author, "author", esc_html($author)) .
4119 " [$ad{'rfc2822'}";
4120 print_local_time(%ad) if ($opts{-localtime});
4121 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
4122 . "</$tag>\n";
4125 # Outputs table rows containing the full author or committer information,
4126 # in the format expected for 'commit' view (& similar).
4127 # Parameters are a commit hash reference, followed by the list of people
4128 # to output information for. If the list is empty it defaults to both
4129 # author and committer.
4130 sub git_print_authorship_rows {
4131 my $co = shift;
4132 # too bad we can't use @people = @_ || ('author', 'committer')
4133 my @people = @_;
4134 @people = ('author', 'committer') unless @people;
4135 foreach my $who (@people) {
4136 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4137 print "<tr><td>$who</td><td>" .
4138 format_search_author($co->{"${who}_name"}, $who,
4139 esc_html($co->{"${who}_name"})) . " " .
4140 format_search_author($co->{"${who}_email"}, $who,
4141 esc_html("<" . $co->{"${who}_email"} . ">")) .
4142 "</td><td rowspan=\"2\">" .
4143 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4144 "</td></tr>\n" .
4145 "<tr>" .
4146 "<td></td><td> $wd{'rfc2822'}";
4147 print_local_time(%wd);
4148 print "</td>" .
4149 "</tr>\n";
4153 sub git_print_page_path {
4154 my $name = shift;
4155 my $type = shift;
4156 my $hb = shift;
4159 print "<div class=\"page_path\">";
4160 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4161 -title => 'tree root'}, to_utf8("[$project]"));
4162 print " / ";
4163 if (defined $name) {
4164 my @dirname = split '/', $name;
4165 my $basename = pop @dirname;
4166 my $fullname = '';
4168 foreach my $dir (@dirname) {
4169 $fullname .= ($fullname ? '/' : '') . $dir;
4170 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4171 hash_base=>$hb),
4172 -title => $fullname}, esc_path($dir));
4173 print " / ";
4175 if (defined $type && $type eq 'blob') {
4176 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4177 hash_base=>$hb),
4178 -title => $name}, esc_path($basename));
4179 } elsif (defined $type && $type eq 'tree') {
4180 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4181 hash_base=>$hb),
4182 -title => $name}, esc_path($basename));
4183 print " / ";
4184 } else {
4185 print esc_path($basename);
4188 print "<br/></div>\n";
4191 sub git_print_log {
4192 my $log = shift;
4193 my %opts = @_;
4195 if ($opts{'-remove_title'}) {
4196 # remove title, i.e. first line of log
4197 shift @$log;
4199 # remove leading empty lines
4200 while (defined $log->[0] && $log->[0] eq "") {
4201 shift @$log;
4204 # print log
4205 my $signoff = 0;
4206 my $empty = 0;
4207 foreach my $line (@$log) {
4208 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4209 $signoff = 1;
4210 $empty = 0;
4211 if (! $opts{'-remove_signoff'}) {
4212 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4213 next;
4214 } else {
4215 # remove signoff lines
4216 next;
4218 } else {
4219 $signoff = 0;
4222 # print only one empty line
4223 # do not print empty line after signoff
4224 if ($line eq "") {
4225 next if ($empty || $signoff);
4226 $empty = 1;
4227 } else {
4228 $empty = 0;
4231 print format_log_line_html($line) . "<br/>\n";
4234 if ($opts{'-final_empty_line'}) {
4235 # end with single empty line
4236 print "<br/>\n" unless $empty;
4240 # return link target (what link points to)
4241 sub git_get_link_target {
4242 my $hash = shift;
4243 my $link_target;
4245 # read link
4246 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4247 or return;
4249 local $/ = undef;
4250 $link_target = <$fd>;
4252 close $fd
4253 or return;
4255 return $link_target;
4258 # given link target, and the directory (basedir) the link is in,
4259 # return target of link relative to top directory (top tree);
4260 # return undef if it is not possible (including absolute links).
4261 sub normalize_link_target {
4262 my ($link_target, $basedir) = @_;
4264 # absolute symlinks (beginning with '/') cannot be normalized
4265 return if (substr($link_target, 0, 1) eq '/');
4267 # normalize link target to path from top (root) tree (dir)
4268 my $path;
4269 if ($basedir) {
4270 $path = $basedir . '/' . $link_target;
4271 } else {
4272 # we are in top (root) tree (dir)
4273 $path = $link_target;
4276 # remove //, /./, and /../
4277 my @path_parts;
4278 foreach my $part (split('/', $path)) {
4279 # discard '.' and ''
4280 next if (!$part || $part eq '.');
4281 # handle '..'
4282 if ($part eq '..') {
4283 if (@path_parts) {
4284 pop @path_parts;
4285 } else {
4286 # link leads outside repository (outside top dir)
4287 return;
4289 } else {
4290 push @path_parts, $part;
4293 $path = join('/', @path_parts);
4295 return $path;
4298 # print tree entry (row of git_tree), but without encompassing <tr> element
4299 sub git_print_tree_entry {
4300 my ($t, $basedir, $hash_base, $have_blame) = @_;
4302 my %base_key = ();
4303 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4305 # The format of a table row is: mode list link. Where mode is
4306 # the mode of the entry, list is the name of the entry, an href,
4307 # and link is the action links of the entry.
4309 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4310 if (exists $t->{'size'}) {
4311 print "<td class=\"size\">$t->{'size'}</td>\n";
4313 if ($t->{'type'} eq "blob") {
4314 print "<td class=\"list\">" .
4315 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4316 file_name=>"$basedir$t->{'name'}", %base_key),
4317 -class => "list"}, esc_path($t->{'name'}));
4318 if (S_ISLNK(oct $t->{'mode'})) {
4319 my $link_target = git_get_link_target($t->{'hash'});
4320 if ($link_target) {
4321 my $norm_target = normalize_link_target($link_target, $basedir);
4322 if (defined $norm_target) {
4323 print " -> " .
4324 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4325 file_name=>$norm_target),
4326 -title => $norm_target}, esc_path($link_target));
4327 } else {
4328 print " -> " . esc_path($link_target);
4332 print "</td>\n";
4333 print "<td class=\"link\">";
4334 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4335 file_name=>"$basedir$t->{'name'}", %base_key)},
4336 "blob");
4337 if ($have_blame) {
4338 print " | " .
4339 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4340 file_name=>"$basedir$t->{'name'}", %base_key)},
4341 "blame");
4343 if (defined $hash_base) {
4344 print " | " .
4345 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4346 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4347 "history");
4349 print " | " .
4350 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4351 file_name=>"$basedir$t->{'name'}")},
4352 "raw");
4353 print "</td>\n";
4355 } elsif ($t->{'type'} eq "tree") {
4356 print "<td class=\"list\">";
4357 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4358 file_name=>"$basedir$t->{'name'}",
4359 %base_key)},
4360 esc_path($t->{'name'}));
4361 print "</td>\n";
4362 print "<td class=\"link\">";
4363 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4364 file_name=>"$basedir$t->{'name'}",
4365 %base_key)},
4366 "tree");
4367 if (defined $hash_base) {
4368 print " | " .
4369 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4370 file_name=>"$basedir$t->{'name'}")},
4371 "history");
4373 print "</td>\n";
4374 } else {
4375 # unknown object: we can only present history for it
4376 # (this includes 'commit' object, i.e. submodule support)
4377 print "<td class=\"list\">" .
4378 esc_path($t->{'name'}) .
4379 "</td>\n";
4380 print "<td class=\"link\">";
4381 if (defined $hash_base) {
4382 print $cgi->a({-href => href(action=>"history",
4383 hash_base=>$hash_base,
4384 file_name=>"$basedir$t->{'name'}")},
4385 "history");
4387 print "</td>\n";
4391 ## ......................................................................
4392 ## functions printing large fragments of HTML
4394 # get pre-image filenames for merge (combined) diff
4395 sub fill_from_file_info {
4396 my ($diff, @parents) = @_;
4398 $diff->{'from_file'} = [ ];
4399 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4400 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4401 if ($diff->{'status'}[$i] eq 'R' ||
4402 $diff->{'status'}[$i] eq 'C') {
4403 $diff->{'from_file'}[$i] =
4404 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4408 return $diff;
4411 # is current raw difftree line of file deletion
4412 sub is_deleted {
4413 my $diffinfo = shift;
4415 return $diffinfo->{'to_id'} eq ('0' x 40);
4418 # does patch correspond to [previous] difftree raw line
4419 # $diffinfo - hashref of parsed raw diff format
4420 # $patchinfo - hashref of parsed patch diff format
4421 # (the same keys as in $diffinfo)
4422 sub is_patch_split {
4423 my ($diffinfo, $patchinfo) = @_;
4425 return defined $diffinfo && defined $patchinfo
4426 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4430 sub git_difftree_body {
4431 my ($difftree, $hash, @parents) = @_;
4432 my ($parent) = $parents[0];
4433 my $have_blame = gitweb_check_feature('blame');
4434 print "<div class=\"list_head\">\n";
4435 if ($#{$difftree} > 10) {
4436 print(($#{$difftree} + 1) . " files changed:\n");
4438 print "</div>\n";
4440 print "<table class=\"" .
4441 (@parents > 1 ? "combined " : "") .
4442 "diff_tree\">\n";
4444 # header only for combined diff in 'commitdiff' view
4445 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4446 if ($has_header) {
4447 # table header
4448 print "<thead><tr>\n" .
4449 "<th></th><th></th>\n"; # filename, patchN link
4450 for (my $i = 0; $i < @parents; $i++) {
4451 my $par = $parents[$i];
4452 print "<th>" .
4453 $cgi->a({-href => href(action=>"commitdiff",
4454 hash=>$hash, hash_parent=>$par),
4455 -title => 'commitdiff to parent number ' .
4456 ($i+1) . ': ' . substr($par,0,7)},
4457 $i+1) .
4458 "&nbsp;</th>\n";
4460 print "</tr></thead>\n<tbody>\n";
4463 my $alternate = 1;
4464 my $patchno = 0;
4465 foreach my $line (@{$difftree}) {
4466 my $diff = parsed_difftree_line($line);
4468 if ($alternate) {
4469 print "<tr class=\"dark\">\n";
4470 } else {
4471 print "<tr class=\"light\">\n";
4473 $alternate ^= 1;
4475 if (exists $diff->{'nparents'}) { # combined diff
4477 fill_from_file_info($diff, @parents)
4478 unless exists $diff->{'from_file'};
4480 if (!is_deleted($diff)) {
4481 # file exists in the result (child) commit
4482 print "<td>" .
4483 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4484 file_name=>$diff->{'to_file'},
4485 hash_base=>$hash),
4486 -class => "list"}, esc_path($diff->{'to_file'})) .
4487 "</td>\n";
4488 } else {
4489 print "<td>" .
4490 esc_path($diff->{'to_file'}) .
4491 "</td>\n";
4494 if ($action eq 'commitdiff') {
4495 # link to patch
4496 $patchno++;
4497 print "<td class=\"link\">" .
4498 $cgi->a({-href => "#patch$patchno"}, "patch") .
4499 " | " .
4500 "</td>\n";
4503 my $has_history = 0;
4504 my $not_deleted = 0;
4505 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4506 my $hash_parent = $parents[$i];
4507 my $from_hash = $diff->{'from_id'}[$i];
4508 my $from_path = $diff->{'from_file'}[$i];
4509 my $status = $diff->{'status'}[$i];
4511 $has_history ||= ($status ne 'A');
4512 $not_deleted ||= ($status ne 'D');
4514 if ($status eq 'A') {
4515 print "<td class=\"link\" align=\"right\"> | </td>\n";
4516 } elsif ($status eq 'D') {
4517 print "<td class=\"link\">" .
4518 $cgi->a({-href => href(action=>"blob",
4519 hash_base=>$hash,
4520 hash=>$from_hash,
4521 file_name=>$from_path)},
4522 "blob" . ($i+1)) .
4523 " | </td>\n";
4524 } else {
4525 if ($diff->{'to_id'} eq $from_hash) {
4526 print "<td class=\"link nochange\">";
4527 } else {
4528 print "<td class=\"link\">";
4530 print $cgi->a({-href => href(action=>"blobdiff",
4531 hash=>$diff->{'to_id'},
4532 hash_parent=>$from_hash,
4533 hash_base=>$hash,
4534 hash_parent_base=>$hash_parent,
4535 file_name=>$diff->{'to_file'},
4536 file_parent=>$from_path)},
4537 "diff" . ($i+1)) .
4538 " | </td>\n";
4542 print "<td class=\"link\">";
4543 if ($not_deleted) {
4544 print $cgi->a({-href => href(action=>"blob",
4545 hash=>$diff->{'to_id'},
4546 file_name=>$diff->{'to_file'},
4547 hash_base=>$hash)},
4548 "blob");
4549 print " | " if ($has_history);
4551 if ($has_history) {
4552 print $cgi->a({-href => href(action=>"history",
4553 file_name=>$diff->{'to_file'},
4554 hash_base=>$hash)},
4555 "history");
4557 print "</td>\n";
4559 print "</tr>\n";
4560 next; # instead of 'else' clause, to avoid extra indent
4562 # else ordinary diff
4564 my ($to_mode_oct, $to_mode_str, $to_file_type);
4565 my ($from_mode_oct, $from_mode_str, $from_file_type);
4566 if ($diff->{'to_mode'} ne ('0' x 6)) {
4567 $to_mode_oct = oct $diff->{'to_mode'};
4568 if (S_ISREG($to_mode_oct)) { # only for regular file
4569 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4571 $to_file_type = file_type($diff->{'to_mode'});
4573 if ($diff->{'from_mode'} ne ('0' x 6)) {
4574 $from_mode_oct = oct $diff->{'from_mode'};
4575 if (S_ISREG($to_mode_oct)) { # only for regular file
4576 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4578 $from_file_type = file_type($diff->{'from_mode'});
4581 if ($diff->{'status'} eq "A") { # created
4582 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4583 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4584 $mode_chng .= "]</span>";
4585 print "<td>";
4586 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4587 hash_base=>$hash, file_name=>$diff->{'file'}),
4588 -class => "list"}, esc_path($diff->{'file'}));
4589 print "</td>\n";
4590 print "<td>$mode_chng</td>\n";
4591 print "<td class=\"link\">";
4592 if ($action eq 'commitdiff') {
4593 # link to patch
4594 $patchno++;
4595 print $cgi->a({-href => "#patch$patchno"}, "patch");
4596 print " | ";
4598 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4599 hash_base=>$hash, file_name=>$diff->{'file'})},
4600 "blob");
4601 print "</td>\n";
4603 } elsif ($diff->{'status'} eq "D") { # deleted
4604 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4605 print "<td>";
4606 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4607 hash_base=>$parent, file_name=>$diff->{'file'}),
4608 -class => "list"}, esc_path($diff->{'file'}));
4609 print "</td>\n";
4610 print "<td>$mode_chng</td>\n";
4611 print "<td class=\"link\">";
4612 if ($action eq 'commitdiff') {
4613 # link to patch
4614 $patchno++;
4615 print $cgi->a({-href => "#patch$patchno"}, "patch");
4616 print " | ";
4618 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4619 hash_base=>$parent, file_name=>$diff->{'file'})},
4620 "blob") . " | ";
4621 if ($have_blame) {
4622 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4623 file_name=>$diff->{'file'})},
4624 "blame") . " | ";
4626 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4627 file_name=>$diff->{'file'})},
4628 "history");
4629 print "</td>\n";
4631 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4632 my $mode_chnge = "";
4633 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4634 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4635 if ($from_file_type ne $to_file_type) {
4636 $mode_chnge .= " from $from_file_type to $to_file_type";
4638 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4639 if ($from_mode_str && $to_mode_str) {
4640 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4641 } elsif ($to_mode_str) {
4642 $mode_chnge .= " mode: $to_mode_str";
4645 $mode_chnge .= "]</span>\n";
4647 print "<td>";
4648 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4649 hash_base=>$hash, file_name=>$diff->{'file'}),
4650 -class => "list"}, esc_path($diff->{'file'}));
4651 print "</td>\n";
4652 print "<td>$mode_chnge</td>\n";
4653 print "<td class=\"link\">";
4654 if ($action eq 'commitdiff') {
4655 # link to patch
4656 $patchno++;
4657 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4658 " | ";
4659 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4660 # "commit" view and modified file (not onlu mode changed)
4661 print $cgi->a({-href => href(action=>"blobdiff",
4662 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4663 hash_base=>$hash, hash_parent_base=>$parent,
4664 file_name=>$diff->{'file'})},
4665 "diff") .
4666 " | ";
4668 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4669 hash_base=>$hash, file_name=>$diff->{'file'})},
4670 "blob") . " | ";
4671 if ($have_blame) {
4672 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4673 file_name=>$diff->{'file'})},
4674 "blame") . " | ";
4676 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4677 file_name=>$diff->{'file'})},
4678 "history");
4679 print "</td>\n";
4681 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4682 my %status_name = ('R' => 'moved', 'C' => 'copied');
4683 my $nstatus = $status_name{$diff->{'status'}};
4684 my $mode_chng = "";
4685 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4686 # mode also for directories, so we cannot use $to_mode_str
4687 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4689 print "<td>" .
4690 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4691 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4692 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4693 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4694 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4695 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4696 -class => "list"}, esc_path($diff->{'from_file'})) .
4697 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4698 "<td class=\"link\">";
4699 if ($action eq 'commitdiff') {
4700 # link to patch
4701 $patchno++;
4702 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4703 " | ";
4704 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4705 # "commit" view and modified file (not only pure rename or copy)
4706 print $cgi->a({-href => href(action=>"blobdiff",
4707 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4708 hash_base=>$hash, hash_parent_base=>$parent,
4709 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4710 "diff") .
4711 " | ";
4713 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4714 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4715 "blob") . " | ";
4716 if ($have_blame) {
4717 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4718 file_name=>$diff->{'to_file'})},
4719 "blame") . " | ";
4721 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4722 file_name=>$diff->{'to_file'})},
4723 "history");
4724 print "</td>\n";
4726 } # we should not encounter Unmerged (U) or Unknown (X) status
4727 print "</tr>\n";
4729 print "</tbody>" if $has_header;
4730 print "</table>\n";
4733 sub git_patchset_body {
4734 my ($fd, $difftree, $hash, @hash_parents) = @_;
4735 my ($hash_parent) = $hash_parents[0];
4737 my $is_combined = (@hash_parents > 1);
4738 my $patch_idx = 0;
4739 my $patch_number = 0;
4740 my $patch_line;
4741 my $diffinfo;
4742 my $to_name;
4743 my (%from, %to);
4745 print "<div class=\"patchset\">\n";
4747 # skip to first patch
4748 while ($patch_line = <$fd>) {
4749 chomp $patch_line;
4751 last if ($patch_line =~ m/^diff /);
4754 PATCH:
4755 while ($patch_line) {
4757 # parse "git diff" header line
4758 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4759 # $1 is from_name, which we do not use
4760 $to_name = unquote($2);
4761 $to_name =~ s!^b/!!;
4762 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4763 # $1 is 'cc' or 'combined', which we do not use
4764 $to_name = unquote($2);
4765 } else {
4766 $to_name = undef;
4769 # check if current patch belong to current raw line
4770 # and parse raw git-diff line if needed
4771 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4772 # this is continuation of a split patch
4773 print "<div class=\"patch cont\">\n";
4774 } else {
4775 # advance raw git-diff output if needed
4776 $patch_idx++ if defined $diffinfo;
4778 # read and prepare patch information
4779 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4781 # compact combined diff output can have some patches skipped
4782 # find which patch (using pathname of result) we are at now;
4783 if ($is_combined) {
4784 while ($to_name ne $diffinfo->{'to_file'}) {
4785 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4786 format_diff_cc_simplified($diffinfo, @hash_parents) .
4787 "</div>\n"; # class="patch"
4789 $patch_idx++;
4790 $patch_number++;
4792 last if $patch_idx > $#$difftree;
4793 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4797 # modifies %from, %to hashes
4798 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4800 # this is first patch for raw difftree line with $patch_idx index
4801 # we index @$difftree array from 0, but number patches from 1
4802 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4805 # git diff header
4806 #assert($patch_line =~ m/^diff /) if DEBUG;
4807 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4808 $patch_number++;
4809 # print "git diff" header
4810 print format_git_diff_header_line($patch_line, $diffinfo,
4811 \%from, \%to);
4813 # print extended diff header
4814 print "<div class=\"diff extended_header\">\n";
4815 EXTENDED_HEADER:
4816 while ($patch_line = <$fd>) {
4817 chomp $patch_line;
4819 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4821 print format_extended_diff_header_line($patch_line, $diffinfo,
4822 \%from, \%to);
4824 print "</div>\n"; # class="diff extended_header"
4826 # from-file/to-file diff header
4827 if (! $patch_line) {
4828 print "</div>\n"; # class="patch"
4829 last PATCH;
4831 next PATCH if ($patch_line =~ m/^diff /);
4832 #assert($patch_line =~ m/^---/) if DEBUG;
4834 my $last_patch_line = $patch_line;
4835 $patch_line = <$fd>;
4836 chomp $patch_line;
4837 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4839 print format_diff_from_to_header($last_patch_line, $patch_line,
4840 $diffinfo, \%from, \%to,
4841 @hash_parents);
4843 # the patch itself
4844 LINE:
4845 while ($patch_line = <$fd>) {
4846 chomp $patch_line;
4848 next PATCH if ($patch_line =~ m/^diff /);
4850 print format_diff_line($patch_line, \%from, \%to);
4853 } continue {
4854 print "</div>\n"; # class="patch"
4857 # for compact combined (--cc) format, with chunk and patch simplification
4858 # the patchset might be empty, but there might be unprocessed raw lines
4859 for (++$patch_idx if $patch_number > 0;
4860 $patch_idx < @$difftree;
4861 ++$patch_idx) {
4862 # read and prepare patch information
4863 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4865 # generate anchor for "patch" links in difftree / whatchanged part
4866 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4867 format_diff_cc_simplified($diffinfo, @hash_parents) .
4868 "</div>\n"; # class="patch"
4870 $patch_number++;
4873 if ($patch_number == 0) {
4874 if (@hash_parents > 1) {
4875 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4876 } else {
4877 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4881 print "</div>\n"; # class="patchset"
4884 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4886 # fills project list info (age, description, owner, forks) for each
4887 # project in the list, removing invalid projects from returned list
4888 # NOTE: modifies $projlist, but does not remove entries from it
4889 sub fill_project_list_info {
4890 my ($projlist, $check_forks) = @_;
4891 my @projects;
4893 my $show_ctags = gitweb_check_feature('ctags');
4894 PROJECT:
4895 foreach my $pr (@$projlist) {
4896 my (@activity) = git_get_last_activity($pr->{'path'});
4897 unless (@activity) {
4898 next PROJECT;
4900 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4901 if (!defined $pr->{'descr'}) {
4902 my $descr = git_get_project_description($pr->{'path'}) || "";
4903 $descr = to_utf8($descr);
4904 $pr->{'descr_long'} = $descr;
4905 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4907 if (!defined $pr->{'owner'}) {
4908 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4910 if ($check_forks) {
4911 my $pname = $pr->{'path'};
4912 if (($pname =~ s/\.git$//) &&
4913 ($pname !~ /\/$/) &&
4914 (-d "$projectroot/$pname")) {
4915 $pr->{'forks'} = "-d $projectroot/$pname";
4916 } else {
4917 $pr->{'forks'} = 0;
4920 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4921 push @projects, $pr;
4924 return @projects;
4927 # print 'sort by' <th> element, generating 'sort by $name' replay link
4928 # if that order is not selected
4929 sub print_sort_th {
4930 print format_sort_th(@_);
4933 sub format_sort_th {
4934 my ($name, $order, $header) = @_;
4935 my $sort_th = "";
4936 $header ||= ucfirst($name);
4938 if ($order eq $name) {
4939 $sort_th .= "<th>$header</th>\n";
4940 } else {
4941 $sort_th .= "<th>" .
4942 $cgi->a({-href => href(-replay=>1, order=>$name),
4943 -class => "header"}, $header) .
4944 "</th>\n";
4947 return $sort_th;
4950 sub git_project_list_body {
4951 # actually uses global variable $project
4952 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4954 my $check_forks = gitweb_check_feature('forks');
4955 my @projects = fill_project_list_info($projlist, $check_forks);
4957 $order ||= $default_projects_order;
4958 $from = 0 unless defined $from;
4959 $to = $#projects if (!defined $to || $#projects < $to);
4961 my %order_info = (
4962 project => { key => 'path', type => 'str' },
4963 descr => { key => 'descr_long', type => 'str' },
4964 owner => { key => 'owner', type => 'str' },
4965 age => { key => 'age', type => 'num' }
4967 my $oi = $order_info{$order};
4968 if ($oi->{'type'} eq 'str') {
4969 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4970 } else {
4971 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4974 my $show_ctags = gitweb_check_feature('ctags');
4975 if ($show_ctags) {
4976 my %ctags;
4977 foreach my $p (@projects) {
4978 foreach my $ct (keys %{$p->{'ctags'}}) {
4979 $ctags{$ct} += $p->{'ctags'}->{$ct};
4982 my $cloud = git_populate_project_tagcloud(\%ctags);
4983 print git_show_project_tagcloud($cloud, 64);
4986 print "<table class=\"project_list\">\n";
4987 unless ($no_header) {
4988 print "<tr>\n";
4989 if ($check_forks) {
4990 print "<th></th>\n";
4992 print_sort_th('project', $order, 'Project');
4993 print_sort_th('descr', $order, 'Description');
4994 print_sort_th('owner', $order, 'Owner');
4995 print_sort_th('age', $order, 'Last Change');
4996 print "<th></th>\n" . # for links
4997 "</tr>\n";
4999 my $alternate = 1;
5000 my $tagfilter = $cgi->param('by_tag');
5001 for (my $i = $from; $i <= $to; $i++) {
5002 my $pr = $projects[$i];
5004 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
5005 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
5006 and not $pr->{'descr_long'} =~ /$searchtext/;
5007 # Weed out forks or non-matching entries of search
5008 if ($check_forks) {
5009 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
5010 $forkbase="^$forkbase" if $forkbase;
5011 next if not $searchtext and not $tagfilter and $show_ctags
5012 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
5015 if ($alternate) {
5016 print "<tr class=\"dark\">\n";
5017 } else {
5018 print "<tr class=\"light\">\n";
5020 $alternate ^= 1;
5021 if ($check_forks) {
5022 print "<td>";
5023 if ($pr->{'forks'}) {
5024 print "<!-- $pr->{'forks'} -->\n";
5025 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
5027 print "</td>\n";
5029 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5030 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
5031 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5032 -class => "list", -title => $pr->{'descr_long'}},
5033 esc_html($pr->{'descr'})) . "</td>\n" .
5034 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5035 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5036 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
5037 "<td class=\"link\">" .
5038 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5039 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5040 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5041 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5042 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5043 "</td>\n" .
5044 "</tr>\n";
5046 if (defined $extra) {
5047 print "<tr>\n";
5048 if ($check_forks) {
5049 print "<td></td>\n";
5051 print "<td colspan=\"5\">$extra</td>\n" .
5052 "</tr>\n";
5054 print "</table>\n";
5057 sub git_log_body {
5058 # uses global variable $project
5059 my ($commitlist, $from, $to, $refs, $extra) = @_;
5061 $from = 0 unless defined $from;
5062 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5064 for (my $i = 0; $i <= $to; $i++) {
5065 my %co = %{$commitlist->[$i]};
5066 next if !%co;
5067 my $commit = $co{'id'};
5068 my $ref = format_ref_marker($refs, $commit);
5069 my %ad = parse_date($co{'author_epoch'});
5070 git_print_header_div('commit',
5071 "<span class=\"age\">$co{'age_string'}</span>" .
5072 esc_html($co{'title'}) . $ref,
5073 $commit);
5074 print "<div class=\"title_text\">\n" .
5075 "<div class=\"log_link\">\n" .
5076 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5077 " | " .
5078 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5079 " | " .
5080 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5081 "<br/>\n" .
5082 "</div>\n";
5083 git_print_authorship(\%co, -tag => 'span');
5084 print "<br/>\n</div>\n";
5086 print "<div class=\"log_body\">\n";
5087 git_print_log($co{'comment'}, -final_empty_line=> 1);
5088 print "</div>\n";
5090 if ($extra) {
5091 print "<div class=\"page_nav\">\n";
5092 print "$extra\n";
5093 print "</div>\n";
5097 sub git_shortlog_body {
5098 # uses global variable $project
5099 my ($commitlist, $from, $to, $refs, $extra) = @_;
5101 $from = 0 unless defined $from;
5102 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5104 print "<table class=\"shortlog\">\n";
5105 my $alternate = 1;
5106 for (my $i = $from; $i <= $to; $i++) {
5107 my %co = %{$commitlist->[$i]};
5108 my $commit = $co{'id'};
5109 my $ref = format_ref_marker($refs, $commit);
5110 if ($alternate) {
5111 print "<tr class=\"dark\">\n";
5112 } else {
5113 print "<tr class=\"light\">\n";
5115 $alternate ^= 1;
5116 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5117 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5118 format_author_html('td', \%co, 10) . "<td>";
5119 print format_subject_html($co{'title'}, $co{'title_short'},
5120 href(action=>"commit", hash=>$commit), $ref);
5121 print "</td>\n" .
5122 "<td class=\"link\">" .
5123 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5124 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5125 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5126 my $snapshot_links = format_snapshot_links($commit);
5127 if (defined $snapshot_links) {
5128 print " | " . $snapshot_links;
5130 print "</td>\n" .
5131 "</tr>\n";
5133 if (defined $extra) {
5134 print "<tr>\n" .
5135 "<td colspan=\"4\">$extra</td>\n" .
5136 "</tr>\n";
5138 print "</table>\n";
5141 sub git_history_body {
5142 # Warning: assumes constant type (blob or tree) during history
5143 my ($commitlist, $from, $to, $refs, $extra,
5144 $file_name, $file_hash, $ftype) = @_;
5146 $from = 0 unless defined $from;
5147 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5149 print "<table class=\"history\">\n";
5150 my $alternate = 1;
5151 for (my $i = $from; $i <= $to; $i++) {
5152 my %co = %{$commitlist->[$i]};
5153 if (!%co) {
5154 next;
5156 my $commit = $co{'id'};
5158 my $ref = format_ref_marker($refs, $commit);
5160 if ($alternate) {
5161 print "<tr class=\"dark\">\n";
5162 } else {
5163 print "<tr class=\"light\">\n";
5165 $alternate ^= 1;
5166 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5167 # shortlog: format_author_html('td', \%co, 10)
5168 format_author_html('td', \%co, 15, 3) . "<td>";
5169 # originally git_history used chop_str($co{'title'}, 50)
5170 print format_subject_html($co{'title'}, $co{'title_short'},
5171 href(action=>"commit", hash=>$commit), $ref);
5172 print "</td>\n" .
5173 "<td class=\"link\">" .
5174 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5175 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5177 if ($ftype eq 'blob') {
5178 my $blob_current = $file_hash;
5179 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5180 if (defined $blob_current && defined $blob_parent &&
5181 $blob_current ne $blob_parent) {
5182 print " | " .
5183 $cgi->a({-href => href(action=>"blobdiff",
5184 hash=>$blob_current, hash_parent=>$blob_parent,
5185 hash_base=>$hash_base, hash_parent_base=>$commit,
5186 file_name=>$file_name)},
5187 "diff to current");
5190 print "</td>\n" .
5191 "</tr>\n";
5193 if (defined $extra) {
5194 print "<tr>\n" .
5195 "<td colspan=\"4\">$extra</td>\n" .
5196 "</tr>\n";
5198 print "</table>\n";
5201 sub git_tags_body {
5202 # uses global variable $project
5203 my ($taglist, $from, $to, $extra) = @_;
5204 $from = 0 unless defined $from;
5205 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5207 print "<table class=\"tags\">\n";
5208 my $alternate = 1;
5209 for (my $i = $from; $i <= $to; $i++) {
5210 my $entry = $taglist->[$i];
5211 my %tag = %$entry;
5212 my $comment = $tag{'subject'};
5213 my $comment_short;
5214 if (defined $comment) {
5215 $comment_short = chop_str($comment, 30, 5);
5217 if ($alternate) {
5218 print "<tr class=\"dark\">\n";
5219 } else {
5220 print "<tr class=\"light\">\n";
5222 $alternate ^= 1;
5223 if (defined $tag{'age'}) {
5224 print "<td><i>$tag{'age'}</i></td>\n";
5225 } else {
5226 print "<td></td>\n";
5228 print "<td>" .
5229 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5230 -class => "list name"}, esc_html($tag{'name'})) .
5231 "</td>\n" .
5232 "<td>";
5233 if (defined $comment) {
5234 print format_subject_html($comment, $comment_short,
5235 href(action=>"tag", hash=>$tag{'id'}));
5237 print "</td>\n" .
5238 "<td class=\"selflink\">";
5239 if ($tag{'type'} eq "tag") {
5240 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5241 } else {
5242 print "&nbsp;";
5244 print "</td>\n" .
5245 "<td class=\"link\">" . " | " .
5246 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5247 if ($tag{'reftype'} eq "commit") {
5248 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5249 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5250 } elsif ($tag{'reftype'} eq "blob") {
5251 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5253 print "</td>\n" .
5254 "</tr>";
5256 if (defined $extra) {
5257 print "<tr>\n" .
5258 "<td colspan=\"5\">$extra</td>\n" .
5259 "</tr>\n";
5261 print "</table>\n";
5264 sub git_heads_body {
5265 # uses global variable $project
5266 my ($headlist, $head, $from, $to, $extra) = @_;
5267 $from = 0 unless defined $from;
5268 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5270 print "<table class=\"heads\">\n";
5271 my $alternate = 1;
5272 for (my $i = $from; $i <= $to; $i++) {
5273 my $entry = $headlist->[$i];
5274 my %ref = %$entry;
5275 my $curr = $ref{'id'} eq $head;
5276 if ($alternate) {
5277 print "<tr class=\"dark\">\n";
5278 } else {
5279 print "<tr class=\"light\">\n";
5281 $alternate ^= 1;
5282 print "<td><i>$ref{'age'}</i></td>\n" .
5283 ($curr ? "<td class=\"current_head\">" : "<td>") .
5284 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5285 -class => "list name"},esc_html($ref{'name'})) .
5286 "</td>\n" .
5287 "<td class=\"link\">" .
5288 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5289 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5290 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
5291 "</td>\n" .
5292 "</tr>";
5294 if (defined $extra) {
5295 print "<tr>\n" .
5296 "<td colspan=\"3\">$extra</td>\n" .
5297 "</tr>\n";
5299 print "</table>\n";
5302 sub git_search_grep_body {
5303 my ($commitlist, $from, $to, $extra) = @_;
5304 $from = 0 unless defined $from;
5305 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5307 print "<table class=\"commit_search\">\n";
5308 my $alternate = 1;
5309 for (my $i = $from; $i <= $to; $i++) {
5310 my %co = %{$commitlist->[$i]};
5311 if (!%co) {
5312 next;
5314 my $commit = $co{'id'};
5315 if ($alternate) {
5316 print "<tr class=\"dark\">\n";
5317 } else {
5318 print "<tr class=\"light\">\n";
5320 $alternate ^= 1;
5321 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5322 format_author_html('td', \%co, 15, 5) .
5323 "<td>" .
5324 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5325 -class => "list subject"},
5326 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5327 my $comment = $co{'comment'};
5328 foreach my $line (@$comment) {
5329 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5330 my ($lead, $match, $trail) = ($1, $2, $3);
5331 $match = chop_str($match, 70, 5, 'center');
5332 my $contextlen = int((80 - length($match))/2);
5333 $contextlen = 30 if ($contextlen > 30);
5334 $lead = chop_str($lead, $contextlen, 10, 'left');
5335 $trail = chop_str($trail, $contextlen, 10, 'right');
5337 $lead = esc_html($lead);
5338 $match = esc_html($match);
5339 $trail = esc_html($trail);
5341 print "$lead<span class=\"match\">$match</span>$trail<br />";
5344 print "</td>\n" .
5345 "<td class=\"link\">" .
5346 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5347 " | " .
5348 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5349 " | " .
5350 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5351 print "</td>\n" .
5352 "</tr>\n";
5354 if (defined $extra) {
5355 print "<tr>\n" .
5356 "<td colspan=\"3\">$extra</td>\n" .
5357 "</tr>\n";
5359 print "</table>\n";
5362 ## ======================================================================
5363 ## ======================================================================
5364 ## actions
5366 sub git_project_list {
5367 my $order = $input_params{'order'};
5368 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5369 die_error(400, "Unknown order parameter");
5372 my @list = git_get_projects_list();
5373 if (!@list) {
5374 die_error(404, "No projects found");
5377 git_header_html();
5378 if (defined $home_text && -f $home_text) {
5379 print "<div class=\"index_include\">\n";
5380 insert_file($home_text);
5381 print "</div>\n";
5383 print $cgi->startform(-method => "get") .
5384 "<p class=\"projsearch\">Search:\n" .
5385 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5386 "</p>" .
5387 $cgi->end_form() . "\n";
5388 git_project_list_body(\@list, $order);
5389 git_footer_html();
5392 sub git_forks {
5393 my $order = $input_params{'order'};
5394 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5395 die_error(400, "Unknown order parameter");
5398 my @list = git_get_projects_list($project);
5399 if (!@list) {
5400 die_error(404, "No forks found");
5403 git_header_html();
5404 git_print_page_nav('','');
5405 git_print_header_div('summary', "$project forks");
5406 git_project_list_body(\@list, $order);
5407 git_footer_html();
5410 sub git_project_index {
5411 my @projects = git_get_projects_list($project);
5413 print $cgi->header(
5414 -type => 'text/plain',
5415 -charset => 'utf-8',
5416 -content_disposition => 'inline; filename="index.aux"');
5418 foreach my $pr (@projects) {
5419 if (!exists $pr->{'owner'}) {
5420 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5423 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5424 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5425 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5426 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5427 $path =~ s/ /\+/g;
5428 $owner =~ s/ /\+/g;
5430 print "$path $owner\n";
5434 sub git_summary {
5435 my $descr = git_get_project_description($project) || "none";
5436 my %co = parse_commit("HEAD");
5437 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5438 my $head = $co{'id'};
5440 my $owner = git_get_project_owner($project);
5442 my $refs = git_get_references();
5443 # These get_*_list functions return one more to allow us to see if
5444 # there are more ...
5445 my @taglist = git_get_tags_list(16);
5446 my @headlist = git_get_heads_list(16);
5447 my @forklist;
5448 my $check_forks = gitweb_check_feature('forks');
5450 if ($check_forks) {
5451 @forklist = git_get_projects_list($project);
5454 git_header_html();
5455 git_print_page_nav('summary','', $head);
5457 print "<div class=\"title\">&nbsp;</div>\n";
5458 print "<table class=\"projects_list\">\n" .
5459 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5460 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5461 if (defined $cd{'rfc2822'}) {
5462 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5465 # use per project git URL list in $projectroot/$project/cloneurl
5466 # or make project git URL from git base URL and project name
5467 my $url_tag = "URL";
5468 my @url_list = git_get_project_url_list($project);
5469 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5470 foreach my $git_url (@url_list) {
5471 next unless $git_url;
5472 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5473 $url_tag = "";
5476 # Tag cloud
5477 my $show_ctags = gitweb_check_feature('ctags');
5478 if ($show_ctags) {
5479 my $ctags = git_get_project_ctags($project);
5480 my $cloud = git_populate_project_tagcloud($ctags);
5481 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5482 print "</td>\n<td>" unless %$ctags;
5483 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5484 print "</td>\n<td>" if %$ctags;
5485 print git_show_project_tagcloud($cloud, 48);
5486 print "</td></tr>";
5489 print "</table>\n";
5491 # If XSS prevention is on, we don't include README.html.
5492 # TODO: Allow a readme in some safe format.
5493 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5494 print "<div class=\"title\">readme</div>\n" .
5495 "<div class=\"readme\">\n";
5496 insert_file("$projectroot/$project/README.html");
5497 print "\n</div>\n"; # class="readme"
5500 # we need to request one more than 16 (0..15) to check if
5501 # those 16 are all
5502 my @commitlist = $head ? parse_commits($head, 17) : ();
5503 if (@commitlist) {
5504 git_print_header_div('shortlog');
5505 git_shortlog_body(\@commitlist, 0, 15, $refs,
5506 $#commitlist <= 15 ? undef :
5507 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5510 if (@taglist) {
5511 git_print_header_div('tags');
5512 git_tags_body(\@taglist, 0, 15,
5513 $#taglist <= 15 ? undef :
5514 $cgi->a({-href => href(action=>"tags")}, "..."));
5517 if (@headlist) {
5518 git_print_header_div('heads');
5519 git_heads_body(\@headlist, $head, 0, 15,
5520 $#headlist <= 15 ? undef :
5521 $cgi->a({-href => href(action=>"heads")}, "..."));
5524 if (@forklist) {
5525 git_print_header_div('forks');
5526 git_project_list_body(\@forklist, 'age', 0, 15,
5527 $#forklist <= 15 ? undef :
5528 $cgi->a({-href => href(action=>"forks")}, "..."),
5529 'no_header');
5532 git_footer_html();
5535 sub git_tag {
5536 my %tag = parse_tag($hash);
5538 if (! %tag) {
5539 die_error(404, "Unknown tag object");
5542 my $head = git_get_head_hash($project);
5543 git_header_html();
5544 git_print_page_nav('','', $head,undef,$head);
5545 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5546 print "<div class=\"title_text\">\n" .
5547 "<table class=\"object_header\">\n" .
5548 "<tr>\n" .
5549 "<td>object</td>\n" .
5550 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5551 $tag{'object'}) . "</td>\n" .
5552 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5553 $tag{'type'}) . "</td>\n" .
5554 "</tr>\n";
5555 if (defined($tag{'author'})) {
5556 git_print_authorship_rows(\%tag, 'author');
5558 print "</table>\n\n" .
5559 "</div>\n";
5560 print "<div class=\"page_body\">";
5561 my $comment = $tag{'comment'};
5562 foreach my $line (@$comment) {
5563 chomp $line;
5564 print esc_html($line, -nbsp=>1) . "<br/>\n";
5566 print "</div>\n";
5567 git_footer_html();
5570 sub git_blame_common {
5571 my $format = shift || 'porcelain';
5572 if ($format eq 'porcelain' && $cgi->param('js') &&
5573 !$caching_enabled) {
5574 $format = 'incremental';
5575 $action = 'blame_incremental'; # for page title etc
5578 # permissions
5579 gitweb_check_feature('blame')
5580 or die_error(403, "Blame view not allowed");
5582 # error checking
5583 die_error(400, "No file name given") unless $file_name;
5584 $hash_base ||= git_get_head_hash($project);
5585 die_error(404, "Couldn't find base commit") unless $hash_base;
5586 my %co = parse_commit($hash_base)
5587 or die_error(404, "Commit not found");
5588 my $ftype = "blob";
5589 if (!defined $hash) {
5590 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5591 or die_error(404, "Error looking up file");
5592 } else {
5593 $ftype = git_get_type($hash);
5594 if ($ftype !~ "blob") {
5595 die_error(400, "Object is not a blob");
5599 my $fd;
5600 if ($format eq 'incremental') {
5601 # get file contents (as base)
5602 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5603 or die_error(500, "Open git-cat-file failed");
5604 } elsif ($format eq 'data') {
5605 # run git-blame --incremental
5606 open $fd, "-|", git_cmd(), "blame", "--incremental",
5607 $hash_base, "--", $file_name
5608 or die_error(500, "Open git-blame --incremental failed");
5609 } else {
5610 # run git-blame --porcelain
5611 open $fd, "-|", git_cmd(), "blame", '-p',
5612 $hash_base, '--', $file_name
5613 or die_error(500, "Open git-blame --porcelain failed");
5616 # incremental blame data returns early
5617 if ($format eq 'data') {
5618 print $cgi->header(
5619 -type=>"text/plain", -charset => "utf-8",
5620 -status=> "200 OK");
5621 local $| = 1; # output autoflush
5622 print while <$fd>;
5623 close $fd
5624 or print "ERROR $!\n";
5626 print 'END';
5627 if (!$caching_enabled &&
5628 defined $t0 && gitweb_check_feature('timed')) {
5629 print ' '.
5630 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5631 ' '.$number_of_git_cmds;
5633 print "\n";
5635 return;
5638 # page header
5639 git_header_html();
5640 my $formats_nav =
5641 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5642 "blob") .
5643 " | ";
5644 if ($format eq 'incremental') {
5645 $formats_nav .=
5646 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5647 "blame") . " (non-incremental)";
5648 } elsif (!$caching_enabled) {
5649 $formats_nav .=
5650 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5651 "blame") . " (incremental)";
5653 $formats_nav .=
5654 " | " .
5655 $cgi->a({-href => href(action=>"history", -replay=>1)},
5656 "history") .
5657 " | " .
5658 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5659 "HEAD");
5660 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5661 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5662 git_print_page_path($file_name, $ftype, $hash_base);
5664 # page body
5665 if ($format eq 'incremental') {
5666 print "<noscript>\n<div class=\"error\"><center><b>\n".
5667 "This page requires JavaScript to run.\n Use ".
5668 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5669 'this page').
5670 " instead.\n".
5671 "</b></center></div>\n</noscript>\n";
5673 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5676 print qq!<div class="page_body">\n!;
5677 print qq!<div id="progress_info">... / ...</div>\n!
5678 if ($format eq 'incremental');
5679 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5680 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5681 qq!<thead>\n!.
5682 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5683 qq!</thead>\n!.
5684 qq!<tbody>\n!;
5686 my @rev_color = qw(light dark);
5687 my $num_colors = scalar(@rev_color);
5688 my $current_color = 0;
5690 if ($format eq 'incremental') {
5691 my $color_class = $rev_color[$current_color];
5693 #contents of a file
5694 my $linenr = 0;
5695 LINE:
5696 while (my $line = <$fd>) {
5697 chomp $line;
5698 $linenr++;
5700 print qq!<tr id="l$linenr" class="$color_class">!.
5701 qq!<td class="sha1"><a href=""> </a></td>!.
5702 qq!<td class="linenr">!.
5703 qq!<a class="linenr" href="">$linenr</a></td>!;
5704 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5705 print qq!</tr>\n!;
5708 } else { # porcelain, i.e. ordinary blame
5709 my %metainfo = (); # saves information about commits
5711 # blame data
5712 LINE:
5713 while (my $line = <$fd>) {
5714 chomp $line;
5715 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5716 # no <lines in group> for subsequent lines in group of lines
5717 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5718 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5719 if (!exists $metainfo{$full_rev}) {
5720 $metainfo{$full_rev} = { 'nprevious' => 0 };
5722 my $meta = $metainfo{$full_rev};
5723 my $data;
5724 while ($data = <$fd>) {
5725 chomp $data;
5726 last if ($data =~ s/^\t//); # contents of line
5727 if ($data =~ /^(\S+)(?: (.*))?$/) {
5728 $meta->{$1} = $2 unless exists $meta->{$1};
5730 if ($data =~ /^previous /) {
5731 $meta->{'nprevious'}++;
5734 my $short_rev = substr($full_rev, 0, 8);
5735 my $author = $meta->{'author'};
5736 my %date =
5737 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5738 my $date = $date{'iso-tz'};
5739 if ($group_size) {
5740 $current_color = ($current_color + 1) % $num_colors;
5742 my $tr_class = $rev_color[$current_color];
5743 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5744 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5745 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5746 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5747 if ($group_size) {
5748 print "<td class=\"sha1\"";
5749 print " title=\"". esc_html($author) . ", $date\"";
5750 print " rowspan=\"$group_size\"" if ($group_size > 1);
5751 print ">";
5752 print $cgi->a({-href => href(action=>"commit",
5753 hash=>$full_rev,
5754 file_name=>$file_name)},
5755 esc_html($short_rev));
5756 if ($group_size >= 2) {
5757 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5758 if (@author_initials) {
5759 print "<br />" .
5760 esc_html(join('', @author_initials));
5761 # or join('.', ...)
5764 print "</td>\n";
5766 # 'previous' <sha1 of parent commit> <filename at commit>
5767 if (exists $meta->{'previous'} &&
5768 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5769 $meta->{'parent'} = $1;
5770 $meta->{'file_parent'} = unquote($2);
5772 my $linenr_commit =
5773 exists($meta->{'parent'}) ?
5774 $meta->{'parent'} : $full_rev;
5775 my $linenr_filename =
5776 exists($meta->{'file_parent'}) ?
5777 $meta->{'file_parent'} : unquote($meta->{'filename'});
5778 my $blamed = href(action => 'blame',
5779 file_name => $linenr_filename,
5780 hash_base => $linenr_commit);
5781 print "<td class=\"linenr\">";
5782 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5783 -class => "linenr" },
5784 esc_html($lineno));
5785 print "</td>";
5786 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5787 print "</tr>\n";
5788 } # end while
5792 # footer
5793 print "</tbody>\n".
5794 "</table>\n"; # class="blame"
5795 print "</div>\n"; # class="blame_body"
5796 close $fd
5797 or print "Reading blob failed\n";
5799 git_footer_html();
5802 sub git_blame {
5803 git_blame_common();
5806 sub git_blame_incremental {
5807 git_blame_common(!$caching_enabled ? 'incremental' : undef);
5810 sub git_blame_data {
5811 git_blame_common('data');
5814 sub git_tags {
5815 my $head = git_get_head_hash($project);
5816 git_header_html();
5817 git_print_page_nav('','', $head,undef,$head);
5818 git_print_header_div('summary', $project);
5820 my @tagslist = git_get_tags_list();
5821 if (@tagslist) {
5822 git_tags_body(\@tagslist);
5824 git_footer_html();
5827 sub git_heads {
5828 my $head = git_get_head_hash($project);
5829 git_header_html();
5830 git_print_page_nav('','', $head,undef,$head);
5831 git_print_header_div('summary', $project);
5833 my @headslist = git_get_heads_list();
5834 if (@headslist) {
5835 git_heads_body(\@headslist, $head);
5837 git_footer_html();
5840 sub git_blob_plain {
5841 my $type = shift;
5842 my $expires;
5844 if (!defined $hash) {
5845 if (defined $file_name) {
5846 my $base = $hash_base || git_get_head_hash($project);
5847 $hash = git_get_hash_by_path($base, $file_name, "blob")
5848 or die_error(404, "Cannot find file");
5849 } else {
5850 die_error(400, "No file name defined");
5852 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5853 # blobs defined by non-textual hash id's can be cached
5854 $expires = "+1d";
5857 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5858 or die_error(500, "Open git-cat-file blob '$hash' failed");
5860 # content-type (can include charset)
5861 $type = blob_contenttype($fd, $file_name, $type);
5863 # "save as" filename, even when no $file_name is given
5864 my $save_as = "$hash";
5865 if (defined $file_name) {
5866 $save_as = $file_name;
5867 } elsif ($type =~ m/^text\//) {
5868 $save_as .= '.txt';
5871 # With XSS prevention on, blobs of all types except a few known safe
5872 # ones are served with "Content-Disposition: attachment" to make sure
5873 # they don't run in our security domain. For certain image types,
5874 # blob view writes an <img> tag referring to blob_plain view, and we
5875 # want to be sure not to break that by serving the image as an
5876 # attachment (though Firefox 3 doesn't seem to care).
5877 my $sandbox = $prevent_xss &&
5878 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5880 print $cgi->header(
5881 -type => $type,
5882 -expires => $expires,
5883 -content_disposition =>
5884 ($sandbox ? 'attachment' : 'inline')
5885 . '; filename="' . $save_as . '"');
5886 local $/ = undef;
5887 binmode STDOUT, ':raw';
5888 print <$fd>;
5889 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5890 close $fd;
5893 sub git_blob {
5894 my $expires;
5896 if (!defined $hash) {
5897 if (defined $file_name) {
5898 my $base = $hash_base || git_get_head_hash($project);
5899 $hash = git_get_hash_by_path($base, $file_name, "blob")
5900 or die_error(404, "Cannot find file");
5901 } else {
5902 die_error(400, "No file name defined");
5904 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5905 # blobs defined by non-textual hash id's can be cached
5906 $expires = "+1d";
5909 my $have_blame = gitweb_check_feature('blame');
5910 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5911 or die_error(500, "Couldn't cat $file_name, $hash");
5912 my $mimetype = blob_mimetype($fd, $file_name);
5913 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5914 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5915 close $fd;
5916 return git_blob_plain($mimetype);
5918 # we can have blame only for text/* mimetype
5919 $have_blame &&= ($mimetype =~ m!^text/!);
5921 my $highlight = gitweb_check_feature('highlight');
5922 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5923 $fd = run_highlighter($fd, $highlight, $syntax)
5924 if $syntax;
5926 git_header_html(undef, $expires);
5927 my $formats_nav = '';
5928 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5929 if (defined $file_name) {
5930 if ($have_blame) {
5931 $formats_nav .=
5932 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5933 "blame") .
5934 " | ";
5936 $formats_nav .=
5937 $cgi->a({-href => href(action=>"history", -replay=>1)},
5938 "history") .
5939 " | " .
5940 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5941 "raw") .
5942 " | " .
5943 $cgi->a({-href => href(action=>"blob",
5944 hash_base=>"HEAD", file_name=>$file_name)},
5945 "HEAD");
5946 } else {
5947 $formats_nav .=
5948 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5949 "raw");
5951 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5952 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5953 } else {
5954 print "<div class=\"page_nav\">\n" .
5955 "<br/><br/></div>\n" .
5956 "<div class=\"title\">$hash</div>\n";
5958 git_print_page_path($file_name, "blob", $hash_base);
5959 print "<div class=\"page_body\">\n";
5960 if ($mimetype =~ m!^image/!) {
5961 print qq!<img type="$mimetype"!;
5962 if ($file_name) {
5963 print qq! alt="$file_name" title="$file_name"!;
5965 print qq! src="! .
5966 href(action=>"blob_plain", hash=>$hash,
5967 hash_base=>$hash_base, file_name=>$file_name) .
5968 qq!" />\n!;
5969 } else {
5970 my $nr;
5971 while (my $line = <$fd>) {
5972 chomp $line;
5973 $nr++;
5974 $line = untabify($line);
5975 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5976 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5979 close $fd
5980 or print "Reading blob failed.\n";
5981 print "</div>";
5982 git_footer_html();
5985 sub git_tree {
5986 if (!defined $hash_base) {
5987 $hash_base = "HEAD";
5989 if (!defined $hash) {
5990 if (defined $file_name) {
5991 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5992 } else {
5993 $hash = $hash_base;
5996 die_error(404, "No such tree") unless defined($hash);
5998 my $show_sizes = gitweb_check_feature('show-sizes');
5999 my $have_blame = gitweb_check_feature('blame');
6001 my @entries = ();
6003 local $/ = "\0";
6004 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
6005 ($show_sizes ? '-l' : ()), @extra_options, $hash
6006 or die_error(500, "Open git-ls-tree failed");
6007 @entries = map { chomp; $_ } <$fd>;
6008 close $fd
6009 or die_error(404, "Reading tree failed");
6012 my $refs = git_get_references();
6013 my $ref = format_ref_marker($refs, $hash_base);
6014 git_header_html();
6015 my $basedir = '';
6016 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6017 my @views_nav = ();
6018 if (defined $file_name) {
6019 push @views_nav,
6020 $cgi->a({-href => href(action=>"history", -replay=>1)},
6021 "history"),
6022 $cgi->a({-href => href(action=>"tree",
6023 hash_base=>"HEAD", file_name=>$file_name)},
6024 "HEAD"),
6026 my $snapshot_links = format_snapshot_links($hash);
6027 if (defined $snapshot_links) {
6028 # FIXME: Should be available when we have no hash base as well.
6029 push @views_nav, $snapshot_links;
6031 git_print_page_nav('tree','', $hash_base, undef, undef,
6032 join(' | ', @views_nav));
6033 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
6034 } else {
6035 undef $hash_base;
6036 print "<div class=\"page_nav\">\n";
6037 print "<br/><br/></div>\n";
6038 print "<div class=\"title\">$hash</div>\n";
6040 if (defined $file_name) {
6041 $basedir = $file_name;
6042 if ($basedir ne '' && substr($basedir, -1) ne '/') {
6043 $basedir .= '/';
6045 git_print_page_path($file_name, 'tree', $hash_base);
6047 print "<div class=\"page_body\">\n";
6048 print "<table class=\"tree\">\n";
6049 my $alternate = 1;
6050 # '..' (top directory) link if possible
6051 if (defined $hash_base &&
6052 defined $file_name && $file_name =~ m![^/]+$!) {
6053 if ($alternate) {
6054 print "<tr class=\"dark\">\n";
6055 } else {
6056 print "<tr class=\"light\">\n";
6058 $alternate ^= 1;
6060 my $up = $file_name;
6061 $up =~ s!/?[^/]+$!!;
6062 undef $up unless $up;
6063 # based on git_print_tree_entry
6064 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6065 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
6066 print '<td class="list">';
6067 print $cgi->a({-href => href(action=>"tree",
6068 hash_base=>$hash_base,
6069 file_name=>$up)},
6070 "..");
6071 print "</td>\n";
6072 print "<td class=\"link\"></td>\n";
6074 print "</tr>\n";
6076 foreach my $line (@entries) {
6077 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6079 if ($alternate) {
6080 print "<tr class=\"dark\">\n";
6081 } else {
6082 print "<tr class=\"light\">\n";
6084 $alternate ^= 1;
6086 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6088 print "</tr>\n";
6090 print "</table>\n" .
6091 "</div>";
6092 git_footer_html();
6095 sub snapshot_name {
6096 my ($project, $hash) = @_;
6098 # path/to/project.git -> project
6099 # path/to/project/.git -> project
6100 my $name = to_utf8($project);
6101 $name =~ s,([^/])/*\.git$,$1,;
6102 $name = basename($name);
6103 # sanitize name
6104 $name =~ s/[[:cntrl:]]/?/g;
6106 my $ver = $hash;
6107 if ($hash =~ /^[0-9a-fA-F]+$/) {
6108 # shorten SHA-1 hash
6109 my $full_hash = git_get_full_hash($project, $hash);
6110 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6111 $ver = git_get_short_hash($project, $hash);
6113 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6114 # tags don't need shortened SHA-1 hash
6115 $ver = $1;
6116 } else {
6117 # branches and other need shortened SHA-1 hash
6118 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6119 $ver = $1;
6121 $ver .= '-' . git_get_short_hash($project, $hash);
6123 # in case of hierarchical branch names
6124 $ver =~ s!/!.!g;
6126 # name = project-version_string
6127 $name = "$name-$ver";
6129 return wantarray ? ($name, $name) : $name;
6132 sub git_snapshot {
6133 my $format = $input_params{'snapshot_format'};
6134 if (!@snapshot_fmts) {
6135 die_error(403, "Snapshots not allowed");
6137 # default to first supported snapshot format
6138 $format ||= $snapshot_fmts[0];
6139 if ($format !~ m/^[a-z0-9]+$/) {
6140 die_error(400, "Invalid snapshot format parameter");
6141 } elsif (!exists($known_snapshot_formats{$format})) {
6142 die_error(400, "Unknown snapshot format");
6143 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6144 die_error(403, "Snapshot format not allowed");
6145 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6146 die_error(403, "Unsupported snapshot format");
6149 my $type = git_get_type("$hash^{}");
6150 if (!$type) {
6151 die_error(404, 'Object does not exist');
6152 } elsif ($type eq 'blob') {
6153 die_error(400, 'Object is not a tree-ish');
6156 my ($name, $prefix) = snapshot_name($project, $hash);
6157 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6158 my $cmd = quote_command(
6159 git_cmd(), 'archive',
6160 "--format=$known_snapshot_formats{$format}{'format'}",
6161 "--prefix=$prefix/", $hash);
6162 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6163 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6166 $filename =~ s/(["\\])/\\$1/g;
6167 print $cgi->header(
6168 -type => $known_snapshot_formats{$format}{'type'},
6169 -content_disposition => 'inline; filename="' . $filename . '"',
6170 -status => '200 OK');
6172 open my $fd, "-|", $cmd
6173 or die_error(500, "Execute git-archive failed");
6174 binmode STDOUT, ':raw';
6175 print <$fd>;
6176 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6177 close $fd;
6180 sub git_log_generic {
6181 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6183 my $head = git_get_head_hash($project);
6184 if (!defined $base) {
6185 $base = $head;
6187 if (!defined $page) {
6188 $page = 0;
6190 my $refs = git_get_references();
6192 my $commit_hash = $base;
6193 if (defined $parent) {
6194 $commit_hash = "$parent..$base";
6196 my @commitlist =
6197 parse_commits($commit_hash, 101, (100 * $page),
6198 defined $file_name ? ($file_name, "--full-history") : ());
6200 my $ftype;
6201 if (!defined $file_hash && defined $file_name) {
6202 # some commits could have deleted file in question,
6203 # and not have it in tree, but one of them has to have it
6204 for (my $i = 0; $i < @commitlist; $i++) {
6205 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6206 last if defined $file_hash;
6209 if (defined $file_hash) {
6210 $ftype = git_get_type($file_hash);
6212 if (defined $file_name && !defined $ftype) {
6213 die_error(500, "Unknown type of object");
6215 my %co;
6216 if (defined $file_name) {
6217 %co = parse_commit($base)
6218 or die_error(404, "Unknown commit object");
6222 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6223 my $next_link = '';
6224 if ($#commitlist >= 100) {
6225 $next_link =
6226 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6227 -accesskey => "n", -title => "Alt-n"}, "next");
6229 my $patch_max = gitweb_get_feature('patches');
6230 if ($patch_max && !defined $file_name) {
6231 if ($patch_max < 0 || @commitlist <= $patch_max) {
6232 $paging_nav .= " &sdot; " .
6233 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6234 "patches");
6238 git_header_html();
6239 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6240 if (defined $file_name) {
6241 git_print_header_div('commit', esc_html($co{'title'}), $base);
6242 } else {
6243 git_print_header_div('summary', $project)
6245 git_print_page_path($file_name, $ftype, $hash_base)
6246 if (defined $file_name);
6248 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6249 $file_name, $file_hash, $ftype);
6251 git_footer_html();
6254 sub git_log {
6255 git_log_generic('log', \&git_log_body,
6256 $hash, $hash_parent);
6259 sub git_commit {
6260 $hash ||= $hash_base || "HEAD";
6261 my %co = parse_commit($hash)
6262 or die_error(404, "Unknown commit object");
6264 my $parent = $co{'parent'};
6265 my $parents = $co{'parents'}; # listref
6267 # we need to prepare $formats_nav before any parameter munging
6268 my $formats_nav;
6269 if (!defined $parent) {
6270 # --root commitdiff
6271 $formats_nav .= '(initial)';
6272 } elsif (@$parents == 1) {
6273 # single parent commit
6274 $formats_nav .=
6275 '(parent: ' .
6276 $cgi->a({-href => href(action=>"commit",
6277 hash=>$parent)},
6278 esc_html(substr($parent, 0, 7))) .
6279 ')';
6280 } else {
6281 # merge commit
6282 $formats_nav .=
6283 '(merge: ' .
6284 join(' ', map {
6285 $cgi->a({-href => href(action=>"commit",
6286 hash=>$_)},
6287 esc_html(substr($_, 0, 7)));
6288 } @$parents ) .
6289 ')';
6291 if (gitweb_check_feature('patches') && @$parents <= 1) {
6292 $formats_nav .= " | " .
6293 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6294 "patch");
6297 if (!defined $parent) {
6298 $parent = "--root";
6300 my @difftree;
6301 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6302 @diff_opts,
6303 (@$parents <= 1 ? $parent : '-c'),
6304 $hash, "--"
6305 or die_error(500, "Open git-diff-tree failed");
6306 @difftree = map { chomp; $_ } <$fd>;
6307 close $fd or die_error(404, "Reading git-diff-tree failed");
6309 # non-textual hash id's can be cached
6310 my $expires;
6311 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6312 $expires = "+1d";
6314 my $refs = git_get_references();
6315 my $ref = format_ref_marker($refs, $co{'id'});
6317 git_header_html(undef, $expires);
6318 git_print_page_nav('commit', '',
6319 $hash, $co{'tree'}, $hash,
6320 $formats_nav);
6322 if (defined $co{'parent'}) {
6323 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6324 } else {
6325 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6327 print "<div class=\"title_text\">\n" .
6328 "<table class=\"object_header\">\n";
6329 git_print_authorship_rows(\%co);
6330 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6331 print "<tr>" .
6332 "<td>tree</td>" .
6333 "<td class=\"sha1\">" .
6334 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6335 class => "list"}, $co{'tree'}) .
6336 "</td>" .
6337 "<td class=\"link\">" .
6338 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6339 "tree");
6340 my $snapshot_links = format_snapshot_links($hash);
6341 if (defined $snapshot_links) {
6342 print " | " . $snapshot_links;
6344 print "</td>" .
6345 "</tr>\n";
6347 foreach my $par (@$parents) {
6348 print "<tr>" .
6349 "<td>parent</td>" .
6350 "<td class=\"sha1\">" .
6351 $cgi->a({-href => href(action=>"commit", hash=>$par),
6352 class => "list"}, $par) .
6353 "</td>" .
6354 "<td class=\"link\">" .
6355 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6356 " | " .
6357 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6358 "</td>" .
6359 "</tr>\n";
6361 print "</table>".
6362 "</div>\n";
6364 print "<div class=\"page_body\">\n";
6365 git_print_log($co{'comment'});
6366 print "</div>\n";
6368 git_difftree_body(\@difftree, $hash, @$parents);
6370 git_footer_html();
6373 sub git_object {
6374 # object is defined by:
6375 # - hash or hash_base alone
6376 # - hash_base and file_name
6377 my $type;
6379 # - hash or hash_base alone
6380 if ($hash || ($hash_base && !defined $file_name)) {
6381 my $object_id = $hash || $hash_base;
6383 open my $fd, "-|", quote_command(
6384 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6385 or die_error(404, "Object does not exist");
6386 $type = <$fd>;
6387 chomp $type;
6388 close $fd
6389 or die_error(404, "Object does not exist");
6391 # - hash_base and file_name
6392 } elsif ($hash_base && defined $file_name) {
6393 $file_name =~ s,/+$,,;
6395 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6396 or die_error(404, "Base object does not exist");
6398 # here errors should not hapen
6399 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6400 or die_error(500, "Open git-ls-tree failed");
6401 my $line = <$fd>;
6402 close $fd;
6404 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6405 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6406 die_error(404, "File or directory for given base does not exist");
6408 $type = $2;
6409 $hash = $3;
6410 } else {
6411 die_error(400, "Not enough information to find object");
6414 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6415 hash=>$hash, hash_base=>$hash_base,
6416 file_name=>$file_name),
6417 -status => '302 Found');
6420 sub git_blobdiff {
6421 my $format = shift || 'html';
6423 my $fd;
6424 my @difftree;
6425 my %diffinfo;
6426 my $expires;
6428 # preparing $fd and %diffinfo for git_patchset_body
6429 # new style URI
6430 if (defined $hash_base && defined $hash_parent_base) {
6431 if (defined $file_name) {
6432 # read raw output
6433 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6434 $hash_parent_base, $hash_base,
6435 "--", (defined $file_parent ? $file_parent : ()), $file_name
6436 or die_error(500, "Open git-diff-tree failed");
6437 @difftree = map { chomp; $_ } <$fd>;
6438 close $fd
6439 or die_error(404, "Reading git-diff-tree failed");
6440 @difftree
6441 or die_error(404, "Blob diff not found");
6443 } elsif (defined $hash &&
6444 $hash =~ /[0-9a-fA-F]{40}/) {
6445 # try to find filename from $hash
6447 # read filtered raw output
6448 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6449 $hash_parent_base, $hash_base, "--"
6450 or die_error(500, "Open git-diff-tree failed");
6451 @difftree =
6452 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6453 # $hash == to_id
6454 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6455 map { chomp; $_ } <$fd>;
6456 close $fd
6457 or die_error(404, "Reading git-diff-tree failed");
6458 @difftree
6459 or die_error(404, "Blob diff not found");
6461 } else {
6462 die_error(400, "Missing one of the blob diff parameters");
6465 if (@difftree > 1) {
6466 die_error(400, "Ambiguous blob diff specification");
6469 %diffinfo = parse_difftree_raw_line($difftree[0]);
6470 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6471 $file_name ||= $diffinfo{'to_file'};
6473 $hash_parent ||= $diffinfo{'from_id'};
6474 $hash ||= $diffinfo{'to_id'};
6476 # non-textual hash id's can be cached
6477 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6478 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6479 $expires = '+1d';
6482 # open patch output
6483 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6484 '-p', ($format eq 'html' ? "--full-index" : ()),
6485 $hash_parent_base, $hash_base,
6486 "--", (defined $file_parent ? $file_parent : ()), $file_name
6487 or die_error(500, "Open git-diff-tree failed");
6490 # old/legacy style URI -- not generated anymore since 1.4.3.
6491 if (!%diffinfo) {
6492 die_error('404 Not Found', "Missing one of the blob diff parameters")
6495 # header
6496 if ($format eq 'html') {
6497 my $formats_nav =
6498 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6499 "raw");
6500 git_header_html(undef, $expires);
6501 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6502 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6503 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6504 } else {
6505 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6506 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6508 if (defined $file_name) {
6509 git_print_page_path($file_name, "blob", $hash_base);
6510 } else {
6511 print "<div class=\"page_path\"></div>\n";
6514 } elsif ($format eq 'plain') {
6515 print $cgi->header(
6516 -type => 'text/plain',
6517 -charset => 'utf-8',
6518 -expires => $expires,
6519 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6521 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6523 } else {
6524 die_error(400, "Unknown blobdiff format");
6527 # patch
6528 if ($format eq 'html') {
6529 print "<div class=\"page_body\">\n";
6531 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6532 close $fd;
6534 print "</div>\n"; # class="page_body"
6535 git_footer_html();
6537 } else {
6538 while (my $line = <$fd>) {
6539 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6540 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6542 print $line;
6544 last if $line =~ m!^\+\+\+!;
6546 local $/ = undef;
6547 print <$fd>;
6548 close $fd;
6552 sub git_blobdiff_plain {
6553 git_blobdiff('plain');
6556 sub git_commitdiff {
6557 my %params = @_;
6558 my $format = $params{-format} || 'html';
6560 my ($patch_max) = gitweb_get_feature('patches');
6561 if ($format eq 'patch') {
6562 die_error(403, "Patch view not allowed") unless $patch_max;
6565 $hash ||= $hash_base || "HEAD";
6566 my %co = parse_commit($hash)
6567 or die_error(404, "Unknown commit object");
6569 # choose format for commitdiff for merge
6570 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6571 $hash_parent = '--cc';
6573 # we need to prepare $formats_nav before almost any parameter munging
6574 my $formats_nav;
6575 if ($format eq 'html') {
6576 $formats_nav =
6577 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6578 "raw");
6579 if ($patch_max && @{$co{'parents'}} <= 1) {
6580 $formats_nav .= " | " .
6581 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6582 "patch");
6585 if (defined $hash_parent &&
6586 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6587 # commitdiff with two commits given
6588 my $hash_parent_short = $hash_parent;
6589 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6590 $hash_parent_short = substr($hash_parent, 0, 7);
6592 $formats_nav .=
6593 ' (from';
6594 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6595 if ($co{'parents'}[$i] eq $hash_parent) {
6596 $formats_nav .= ' parent ' . ($i+1);
6597 last;
6600 $formats_nav .= ': ' .
6601 $cgi->a({-href => href(action=>"commitdiff",
6602 hash=>$hash_parent)},
6603 esc_html($hash_parent_short)) .
6604 ')';
6605 } elsif (!$co{'parent'}) {
6606 # --root commitdiff
6607 $formats_nav .= ' (initial)';
6608 } elsif (scalar @{$co{'parents'}} == 1) {
6609 # single parent commit
6610 $formats_nav .=
6611 ' (parent: ' .
6612 $cgi->a({-href => href(action=>"commitdiff",
6613 hash=>$co{'parent'})},
6614 esc_html(substr($co{'parent'}, 0, 7))) .
6615 ')';
6616 } else {
6617 # merge commit
6618 if ($hash_parent eq '--cc') {
6619 $formats_nav .= ' | ' .
6620 $cgi->a({-href => href(action=>"commitdiff",
6621 hash=>$hash, hash_parent=>'-c')},
6622 'combined');
6623 } else { # $hash_parent eq '-c'
6624 $formats_nav .= ' | ' .
6625 $cgi->a({-href => href(action=>"commitdiff",
6626 hash=>$hash, hash_parent=>'--cc')},
6627 'compact');
6629 $formats_nav .=
6630 ' (merge: ' .
6631 join(' ', map {
6632 $cgi->a({-href => href(action=>"commitdiff",
6633 hash=>$_)},
6634 esc_html(substr($_, 0, 7)));
6635 } @{$co{'parents'}} ) .
6636 ')';
6640 my $hash_parent_param = $hash_parent;
6641 if (!defined $hash_parent_param) {
6642 # --cc for multiple parents, --root for parentless
6643 $hash_parent_param =
6644 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6647 # read commitdiff
6648 my $fd;
6649 my @difftree;
6650 if ($format eq 'html') {
6651 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6652 "--no-commit-id", "--patch-with-raw", "--full-index",
6653 $hash_parent_param, $hash, "--"
6654 or die_error(500, "Open git-diff-tree failed");
6656 while (my $line = <$fd>) {
6657 chomp $line;
6658 # empty line ends raw part of diff-tree output
6659 last unless $line;
6660 push @difftree, scalar parse_difftree_raw_line($line);
6663 } elsif ($format eq 'plain') {
6664 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6665 '-p', $hash_parent_param, $hash, "--"
6666 or die_error(500, "Open git-diff-tree failed");
6667 } elsif ($format eq 'patch') {
6668 # For commit ranges, we limit the output to the number of
6669 # patches specified in the 'patches' feature.
6670 # For single commits, we limit the output to a single patch,
6671 # diverging from the git-format-patch default.
6672 my @commit_spec = ();
6673 if ($hash_parent) {
6674 if ($patch_max > 0) {
6675 push @commit_spec, "-$patch_max";
6677 push @commit_spec, '-n', "$hash_parent..$hash";
6678 } else {
6679 if ($params{-single}) {
6680 push @commit_spec, '-1';
6681 } else {
6682 if ($patch_max > 0) {
6683 push @commit_spec, "-$patch_max";
6685 push @commit_spec, "-n";
6687 push @commit_spec, '--root', $hash;
6689 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6690 '--encoding=utf8', '--stdout', @commit_spec
6691 or die_error(500, "Open git-format-patch failed");
6692 } else {
6693 die_error(400, "Unknown commitdiff format");
6696 # non-textual hash id's can be cached
6697 my $expires;
6698 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6699 $expires = "+1d";
6702 # write commit message
6703 if ($format eq 'html') {
6704 my $refs = git_get_references();
6705 my $ref = format_ref_marker($refs, $co{'id'});
6707 git_header_html(undef, $expires);
6708 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6709 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6710 print "<div class=\"title_text\">\n" .
6711 "<table class=\"object_header\">\n";
6712 git_print_authorship_rows(\%co);
6713 print "</table>".
6714 "</div>\n";
6715 print "<div class=\"page_body\">\n";
6716 if (@{$co{'comment'}} > 1) {
6717 print "<div class=\"log\">\n";
6718 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6719 print "</div>\n"; # class="log"
6722 } elsif ($format eq 'plain') {
6723 my $refs = git_get_references("tags");
6724 my $tagname = git_get_rev_name_tags($hash);
6725 my $filename = basename($project) . "-$hash.patch";
6727 print $cgi->header(
6728 -type => 'text/plain',
6729 -charset => 'utf-8',
6730 -expires => $expires,
6731 -content_disposition => 'inline; filename="' . "$filename" . '"');
6732 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6733 print "From: " . to_utf8($co{'author'}) . "\n";
6734 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6735 print "Subject: " . to_utf8($co{'title'}) . "\n";
6737 print "X-Git-Tag: $tagname\n" if $tagname;
6738 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6740 foreach my $line (@{$co{'comment'}}) {
6741 print to_utf8($line) . "\n";
6743 print "---\n\n";
6744 } elsif ($format eq 'patch') {
6745 my $filename = basename($project) . "-$hash.patch";
6747 print $cgi->header(
6748 -type => 'text/plain',
6749 -charset => 'utf-8',
6750 -expires => $expires,
6751 -content_disposition => 'inline; filename="' . "$filename" . '"');
6754 # write patch
6755 if ($format eq 'html') {
6756 my $use_parents = !defined $hash_parent ||
6757 $hash_parent eq '-c' || $hash_parent eq '--cc';
6758 git_difftree_body(\@difftree, $hash,
6759 $use_parents ? @{$co{'parents'}} : $hash_parent);
6760 print "<br/>\n";
6762 git_patchset_body($fd, \@difftree, $hash,
6763 $use_parents ? @{$co{'parents'}} : $hash_parent);
6764 close $fd;
6765 print "</div>\n"; # class="page_body"
6766 git_footer_html();
6768 } elsif ($format eq 'plain') {
6769 local $/ = undef;
6770 print <$fd>;
6771 close $fd
6772 or print "Reading git-diff-tree failed\n";
6773 } elsif ($format eq 'patch') {
6774 local $/ = undef;
6775 print <$fd>;
6776 close $fd
6777 or print "Reading git-format-patch failed\n";
6781 sub git_commitdiff_plain {
6782 git_commitdiff(-format => 'plain');
6785 # format-patch-style patches
6786 sub git_patch {
6787 git_commitdiff(-format => 'patch', -single => 1);
6790 sub git_patches {
6791 git_commitdiff(-format => 'patch');
6794 sub git_history {
6795 git_log_generic('history', \&git_history_body,
6796 $hash_base, $hash_parent_base,
6797 $file_name, $hash);
6800 sub git_search {
6801 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6802 if (!defined $searchtext) {
6803 die_error(400, "Text field is empty");
6805 if (!defined $hash) {
6806 $hash = git_get_head_hash($project);
6808 my %co = parse_commit($hash);
6809 if (!%co) {
6810 die_error(404, "Unknown commit object");
6812 if (!defined $page) {
6813 $page = 0;
6816 $searchtype ||= 'commit';
6817 if ($searchtype eq 'pickaxe') {
6818 # pickaxe may take all resources of your box and run for several minutes
6819 # with every query - so decide by yourself how public you make this feature
6820 gitweb_check_feature('pickaxe')
6821 or die_error(403, "Pickaxe is disabled");
6823 if ($searchtype eq 'grep') {
6824 gitweb_check_feature('grep')
6825 or die_error(403, "Grep is disabled");
6828 git_header_html();
6830 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6831 my $greptype;
6832 if ($searchtype eq 'commit') {
6833 $greptype = "--grep=";
6834 } elsif ($searchtype eq 'author') {
6835 $greptype = "--author=";
6836 } elsif ($searchtype eq 'committer') {
6837 $greptype = "--committer=";
6839 $greptype .= $searchtext;
6840 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6841 $greptype, '--regexp-ignore-case',
6842 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6844 my $paging_nav = '';
6845 if ($page > 0) {
6846 $paging_nav .=
6847 $cgi->a({-href => href(action=>"search", hash=>$hash,
6848 searchtext=>$searchtext,
6849 searchtype=>$searchtype)},
6850 "first");
6851 $paging_nav .= " &sdot; " .
6852 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6853 -accesskey => "p", -title => "Alt-p"}, "prev");
6854 } else {
6855 $paging_nav .= "first";
6856 $paging_nav .= " &sdot; prev";
6858 my $next_link = '';
6859 if ($#commitlist >= 100) {
6860 $next_link =
6861 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6862 -accesskey => "n", -title => "Alt-n"}, "next");
6863 $paging_nav .= " &sdot; $next_link";
6864 } else {
6865 $paging_nav .= " &sdot; next";
6868 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6869 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6870 if ($page == 0 && !@commitlist) {
6871 print "<p>No match.</p>\n";
6872 } else {
6873 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6877 if ($searchtype eq 'pickaxe') {
6878 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6879 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6881 print "<table class=\"pickaxe search\">\n";
6882 my $alternate = 1;
6883 local $/ = "\n";
6884 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6885 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6886 ($search_use_regexp ? '--pickaxe-regex' : ());
6887 undef %co;
6888 my @files;
6889 while (my $line = <$fd>) {
6890 chomp $line;
6891 next unless $line;
6893 my %set = parse_difftree_raw_line($line);
6894 if (defined $set{'commit'}) {
6895 # finish previous commit
6896 if (%co) {
6897 print "</td>\n" .
6898 "<td class=\"link\">" .
6899 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6900 " | " .
6901 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6902 print "</td>\n" .
6903 "</tr>\n";
6906 if ($alternate) {
6907 print "<tr class=\"dark\">\n";
6908 } else {
6909 print "<tr class=\"light\">\n";
6911 $alternate ^= 1;
6912 %co = parse_commit($set{'commit'});
6913 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6914 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6915 "<td><i>$author</i></td>\n" .
6916 "<td>" .
6917 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6918 -class => "list subject"},
6919 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6920 } elsif (defined $set{'to_id'}) {
6921 next if ($set{'to_id'} =~ m/^0{40}$/);
6923 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6924 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6925 -class => "list"},
6926 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6927 "<br/>\n";
6930 close $fd;
6932 # finish last commit (warning: repetition!)
6933 if (%co) {
6934 print "</td>\n" .
6935 "<td class=\"link\">" .
6936 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6937 " | " .
6938 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6939 print "</td>\n" .
6940 "</tr>\n";
6943 print "</table>\n";
6946 if ($searchtype eq 'grep') {
6947 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6948 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6950 print "<table class=\"grep_search\">\n";
6951 my $alternate = 1;
6952 my $matches = 0;
6953 local $/ = "\n";
6954 open my $fd, "-|", git_cmd(), 'grep', '-n',
6955 $search_use_regexp ? ('-E', '-i') : '-F',
6956 $searchtext, $co{'tree'};
6957 my $lastfile = '';
6958 while (my $line = <$fd>) {
6959 chomp $line;
6960 my ($file, $lno, $ltext, $binary);
6961 last if ($matches++ > 1000);
6962 if ($line =~ /^Binary file (.+) matches$/) {
6963 $file = $1;
6964 $binary = 1;
6965 } else {
6966 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6968 if ($file ne $lastfile) {
6969 $lastfile and print "</td></tr>\n";
6970 if ($alternate++) {
6971 print "<tr class=\"dark\">\n";
6972 } else {
6973 print "<tr class=\"light\">\n";
6975 print "<td class=\"list\">".
6976 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6977 file_name=>"$file"),
6978 -class => "list"}, esc_path($file));
6979 print "</td><td>\n";
6980 $lastfile = $file;
6982 if ($binary) {
6983 print "<div class=\"binary\">Binary file</div>\n";
6984 } else {
6985 $ltext = untabify($ltext);
6986 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6987 $ltext = esc_html($1, -nbsp=>1);
6988 $ltext .= '<span class="match">';
6989 $ltext .= esc_html($2, -nbsp=>1);
6990 $ltext .= '</span>';
6991 $ltext .= esc_html($3, -nbsp=>1);
6992 } else {
6993 $ltext = esc_html($ltext, -nbsp=>1);
6995 print "<div class=\"pre\">" .
6996 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6997 file_name=>"$file").'#l'.$lno,
6998 -class => "linenr"}, sprintf('%4i', $lno))
6999 . ' ' . $ltext . "</div>\n";
7002 if ($lastfile) {
7003 print "</td></tr>\n";
7004 if ($matches > 1000) {
7005 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
7007 } else {
7008 print "<div class=\"diff nodifferences\">No matches found</div>\n";
7010 close $fd;
7012 print "</table>\n";
7014 git_footer_html();
7017 sub git_search_help {
7018 git_header_html();
7019 git_print_page_nav('','', $hash,$hash,$hash);
7020 print <<EOT;
7021 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7022 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7023 the pattern entered is recognized as the POSIX extended
7024 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7025 insensitive).</p>
7026 <dl>
7027 <dt><b>commit</b></dt>
7028 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7030 my $have_grep = gitweb_check_feature('grep');
7031 if ($have_grep) {
7032 print <<EOT;
7033 <dt><b>grep</b></dt>
7034 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7035 a different one) are searched for the given pattern. On large trees, this search can take
7036 a while and put some strain on the server, so please use it with some consideration. Note that
7037 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7038 case-sensitive.</dd>
7041 print <<EOT;
7042 <dt><b>author</b></dt>
7043 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7044 <dt><b>committer</b></dt>
7045 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7047 my $have_pickaxe = gitweb_check_feature('pickaxe');
7048 if ($have_pickaxe) {
7049 print <<EOT;
7050 <dt><b>pickaxe</b></dt>
7051 <dd>All commits that caused the string to appear or disappear from any file (changes that
7052 added, removed or "modified" the string) will be listed. This search can take a while and
7053 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7054 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7057 print "</dl>\n";
7058 git_footer_html();
7061 sub git_shortlog {
7062 git_log_generic('shortlog', \&git_shortlog_body,
7063 $hash, $hash_parent);
7066 ## ......................................................................
7067 ## feeds (RSS, Atom; OPML)
7069 sub git_feed {
7070 my $format = shift || 'atom';
7071 my $have_blame = gitweb_check_feature('blame');
7073 # Atom: http://www.atomenabled.org/developers/syndication/
7074 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7075 if ($format ne 'rss' && $format ne 'atom') {
7076 die_error(400, "Unknown web feed format");
7079 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7080 my $head = $hash || 'HEAD';
7081 my @commitlist = parse_commits($head, 150, 0, $file_name);
7083 my %latest_commit;
7084 my %latest_date;
7085 my $content_type = "application/$format+xml";
7086 if (defined $cgi->http('HTTP_ACCEPT') &&
7087 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7088 # browser (feed reader) prefers text/xml
7089 $content_type = 'text/xml';
7091 if (defined($commitlist[0])) {
7092 %latest_commit = %{$commitlist[0]};
7093 my $latest_epoch = $latest_commit{'committer_epoch'};
7094 %latest_date = parse_date($latest_epoch);
7095 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7096 if (defined $if_modified) {
7097 my $since;
7098 if (eval { require HTTP::Date; 1; }) {
7099 $since = HTTP::Date::str2time($if_modified);
7100 } elsif (eval { require Time::ParseDate; 1; }) {
7101 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7103 if (defined $since && $latest_epoch <= $since) {
7104 print $cgi->header(
7105 -type => $content_type,
7106 -charset => 'utf-8',
7107 -last_modified => $latest_date{'rfc2822'},
7108 -status => '304 Not Modified');
7109 return;
7112 print $cgi->header(
7113 -type => $content_type,
7114 -charset => 'utf-8',
7115 -last_modified => $latest_date{'rfc2822'});
7116 } else {
7117 print $cgi->header(
7118 -type => $content_type,
7119 -charset => 'utf-8');
7122 # Optimization: skip generating the body if client asks only
7123 # for Last-Modified date.
7124 return if ($cgi->request_method() eq 'HEAD');
7126 # header variables
7127 my $title = "$site_name - $project/$action";
7128 my $feed_type = 'log';
7129 if (defined $hash) {
7130 $title .= " - '$hash'";
7131 $feed_type = 'branch log';
7132 if (defined $file_name) {
7133 $title .= " :: $file_name";
7134 $feed_type = 'history';
7136 } elsif (defined $file_name) {
7137 $title .= " - $file_name";
7138 $feed_type = 'history';
7140 $title .= " $feed_type";
7141 my $descr = git_get_project_description($project);
7142 if (defined $descr) {
7143 $descr = esc_html($descr);
7144 } else {
7145 $descr = "$project " .
7146 ($format eq 'rss' ? 'RSS' : 'Atom') .
7147 " feed";
7149 my $owner = git_get_project_owner($project);
7150 $owner = esc_html($owner);
7152 #header
7153 my $alt_url;
7154 if (defined $file_name) {
7155 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7156 } elsif (defined $hash) {
7157 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7158 } else {
7159 $alt_url = href(-full=>1, action=>"summary");
7161 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7162 if ($format eq 'rss') {
7163 print <<XML;
7164 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7165 <channel>
7167 print "<title>$title</title>\n" .
7168 "<link>$alt_url</link>\n" .
7169 "<description>$descr</description>\n" .
7170 "<language>en</language>\n" .
7171 # project owner is responsible for 'editorial' content
7172 "<managingEditor>$owner</managingEditor>\n";
7173 if (defined $logo || defined $favicon) {
7174 # prefer the logo to the favicon, since RSS
7175 # doesn't allow both
7176 my $img = esc_url($logo || $favicon);
7177 print "<image>\n" .
7178 "<url>$img</url>\n" .
7179 "<title>$title</title>\n" .
7180 "<link>$alt_url</link>\n" .
7181 "</image>\n";
7183 if (%latest_date) {
7184 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7185 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7187 print "<generator>gitweb v.$version/$git_version</generator>\n";
7188 } elsif ($format eq 'atom') {
7189 print <<XML;
7190 <feed xmlns="http://www.w3.org/2005/Atom">
7192 print "<title>$title</title>\n" .
7193 "<subtitle>$descr</subtitle>\n" .
7194 '<link rel="alternate" type="text/html" href="' .
7195 $alt_url . '" />' . "\n" .
7196 '<link rel="self" type="' . $content_type . '" href="' .
7197 $cgi->self_url() . '" />' . "\n" .
7198 "<id>" . href(-full=>1) . "</id>\n" .
7199 # use project owner for feed author
7200 "<author><name>$owner</name></author>\n";
7201 if (defined $favicon) {
7202 print "<icon>" . esc_url($favicon) . "</icon>\n";
7204 if (defined $logo_url) {
7205 # not twice as wide as tall: 72 x 27 pixels
7206 print "<logo>" . esc_url($logo) . "</logo>\n";
7208 if (! %latest_date) {
7209 # dummy date to keep the feed valid until commits trickle in:
7210 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7211 } else {
7212 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7214 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7217 # contents
7218 for (my $i = 0; $i <= $#commitlist; $i++) {
7219 my %co = %{$commitlist[$i]};
7220 my $commit = $co{'id'};
7221 # we read 150, we always show 30 and the ones more recent than 48 hours
7222 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7223 last;
7225 my %cd = parse_date($co{'author_epoch'});
7227 # get list of changed files
7228 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7229 $co{'parent'} || "--root",
7230 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7231 or next;
7232 my @difftree = map { chomp; $_ } <$fd>;
7233 close $fd
7234 or next;
7236 # print element (entry, item)
7237 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7238 if ($format eq 'rss') {
7239 print "<item>\n" .
7240 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7241 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7242 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7243 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7244 "<link>$co_url</link>\n" .
7245 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7246 "<content:encoded>" .
7247 "<![CDATA[\n";
7248 } elsif ($format eq 'atom') {
7249 print "<entry>\n" .
7250 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7251 "<updated>$cd{'iso-8601'}</updated>\n" .
7252 "<author>\n" .
7253 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7254 if ($co{'author_email'}) {
7255 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7257 print "</author>\n" .
7258 # use committer for contributor
7259 "<contributor>\n" .
7260 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7261 if ($co{'committer_email'}) {
7262 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7264 print "</contributor>\n" .
7265 "<published>$cd{'iso-8601'}</published>\n" .
7266 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7267 "<id>$co_url</id>\n" .
7268 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7269 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7271 my $comment = $co{'comment'};
7272 print "<pre>\n";
7273 foreach my $line (@$comment) {
7274 $line = esc_html($line);
7275 print "$line\n";
7277 print "</pre><ul>\n";
7278 foreach my $difftree_line (@difftree) {
7279 my %difftree = parse_difftree_raw_line($difftree_line);
7280 next if !$difftree{'from_id'};
7282 my $file = $difftree{'file'} || $difftree{'to_file'};
7284 print "<li>" .
7285 "[" .
7286 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7287 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7288 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7289 file_name=>$file, file_parent=>$difftree{'from_file'}),
7290 -title => "diff"}, 'D');
7291 if ($have_blame) {
7292 print $cgi->a({-href => href(-full=>1, action=>"blame",
7293 file_name=>$file, hash_base=>$commit),
7294 -title => "blame"}, 'B');
7296 # if this is not a feed of a file history
7297 if (!defined $file_name || $file_name ne $file) {
7298 print $cgi->a({-href => href(-full=>1, action=>"history",
7299 file_name=>$file, hash=>$commit),
7300 -title => "history"}, 'H');
7302 $file = esc_path($file);
7303 print "] ".
7304 "$file</li>\n";
7306 if ($format eq 'rss') {
7307 print "</ul>]]>\n" .
7308 "</content:encoded>\n" .
7309 "</item>\n";
7310 } elsif ($format eq 'atom') {
7311 print "</ul>\n</div>\n" .
7312 "</content>\n" .
7313 "</entry>\n";
7317 # end of feed
7318 if ($format eq 'rss') {
7319 print "</channel>\n</rss>\n";
7320 } elsif ($format eq 'atom') {
7321 print "</feed>\n";
7325 sub git_rss {
7326 git_feed('rss');
7329 sub git_atom {
7330 git_feed('atom');
7333 sub git_opml {
7334 my @list = git_get_projects_list();
7336 print $cgi->header(
7337 -type => 'text/xml',
7338 -charset => 'utf-8',
7339 -content_disposition => 'inline; filename="opml.xml"');
7341 print <<XML;
7342 <?xml version="1.0" encoding="utf-8"?>
7343 <opml version="1.0">
7344 <head>
7345 <title>$site_name OPML Export</title>
7346 </head>
7347 <body>
7348 <outline text="git RSS feeds">
7351 foreach my $pr (@list) {
7352 my %proj = %$pr;
7353 my $head = git_get_head_hash($proj{'path'});
7354 if (!defined $head) {
7355 next;
7357 $git_dir = "$projectroot/$proj{'path'}";
7358 my %co = parse_commit($head);
7359 if (!%co) {
7360 next;
7363 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7364 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7365 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7366 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7368 print <<XML;
7369 </outline>
7370 </body>
7371 </opml>