gitweb: Show appropriate "Generating..." page when regenerating cache
[git/jnareb-git.git] / gitweb / gitweb.perl
blobefaa69b5e1dcdb2b7375baeafa9cdd68f6df75e4
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 # You define site-wide options for "Generating..." page (if enabled) here
362 # (which means that $cache_options{'generating_info'} is set to coderef);
363 # override them with $GITWEB_CONFIG as necessary.
364 our %generating_options = (
365 # The time between generating new piece of output to prevent from
366 # redirection before data is ready, i.e. time between printing each
367 # dot in activity indicator / progress info, in seconds.
368 'print_interval' => 2,
369 # Maximum time "Generating..." page would be present, waiting for data,
370 # before unconditional redirect, in seconds.
371 'timeout' => $cache_options{'expires_min'},
373 # Set to _initialized_ instance of GitwebCache::Capture compatibile capturing
374 # engine, i.e. one implementing ->new() constructor, and ->capture($code)
375 # method. If unset (default), the GitwebCache::Capture::Simple would be used.
376 our $capture;
378 # You define site-wide feature defaults here; override them with
379 # $GITWEB_CONFIG as necessary.
380 our %feature = (
381 # feature => {
382 # 'sub' => feature-sub (subroutine),
383 # 'override' => allow-override (boolean),
384 # 'default' => [ default options...] (array reference)}
386 # if feature is overridable (it means that allow-override has true value),
387 # then feature-sub will be called with default options as parameters;
388 # return value of feature-sub indicates if to enable specified feature
390 # if there is no 'sub' key (no feature-sub), then feature cannot be
391 # overridden
393 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
394 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
395 # is enabled
397 # Enable the 'blame' blob view, showing the last commit that modified
398 # each line in the file. This can be very CPU-intensive.
400 # To enable system wide have in $GITWEB_CONFIG
401 # $feature{'blame'}{'default'} = [1];
402 # To have project specific config enable override in $GITWEB_CONFIG
403 # $feature{'blame'}{'override'} = 1;
404 # and in project config gitweb.blame = 0|1;
405 'blame' => {
406 'sub' => sub { feature_bool('blame', @_) },
407 'override' => 0,
408 'default' => [0]},
410 # Enable the 'snapshot' link, providing a compressed archive of any
411 # tree. This can potentially generate high traffic if you have large
412 # project.
414 # Value is a list of formats defined in %known_snapshot_formats that
415 # you wish to offer.
416 # To disable system wide have in $GITWEB_CONFIG
417 # $feature{'snapshot'}{'default'} = [];
418 # To have project specific config enable override in $GITWEB_CONFIG
419 # $feature{'snapshot'}{'override'} = 1;
420 # and in project config, a comma-separated list of formats or "none"
421 # to disable. Example: gitweb.snapshot = tbz2,zip;
422 'snapshot' => {
423 'sub' => \&feature_snapshot,
424 'override' => 0,
425 'default' => ['tgz']},
427 # Enable text search, which will list the commits which match author,
428 # committer or commit text to a given string. Enabled by default.
429 # Project specific override is not supported.
430 'search' => {
431 'override' => 0,
432 'default' => [1]},
434 # Enable grep search, which will list the files in currently selected
435 # tree containing the given string. Enabled by default. This can be
436 # potentially CPU-intensive, of course.
438 # To enable system wide have in $GITWEB_CONFIG
439 # $feature{'grep'}{'default'} = [1];
440 # To have project specific config enable override in $GITWEB_CONFIG
441 # $feature{'grep'}{'override'} = 1;
442 # and in project config gitweb.grep = 0|1;
443 'grep' => {
444 'sub' => sub { feature_bool('grep', @_) },
445 'override' => 0,
446 'default' => [1]},
448 # Enable the pickaxe search, which will list the commits that modified
449 # a given string in a file. This can be practical and quite faster
450 # alternative to 'blame', but still potentially CPU-intensive.
452 # To enable system wide have in $GITWEB_CONFIG
453 # $feature{'pickaxe'}{'default'} = [1];
454 # To have project specific config enable override in $GITWEB_CONFIG
455 # $feature{'pickaxe'}{'override'} = 1;
456 # and in project config gitweb.pickaxe = 0|1;
457 'pickaxe' => {
458 'sub' => sub { feature_bool('pickaxe', @_) },
459 'override' => 0,
460 'default' => [1]},
462 # Enable showing size of blobs in a 'tree' view, in a separate
463 # column, similar to what 'ls -l' does. This cost a bit of IO.
465 # To disable system wide have in $GITWEB_CONFIG
466 # $feature{'show-sizes'}{'default'} = [0];
467 # To have project specific config enable override in $GITWEB_CONFIG
468 # $feature{'show-sizes'}{'override'} = 1;
469 # and in project config gitweb.showsizes = 0|1;
470 'show-sizes' => {
471 'sub' => sub { feature_bool('showsizes', @_) },
472 'override' => 0,
473 'default' => [1]},
475 # Make gitweb use an alternative format of the URLs which can be
476 # more readable and natural-looking: project name is embedded
477 # directly in the path and the query string contains other
478 # auxiliary information. All gitweb installations recognize
479 # URL in either format; this configures in which formats gitweb
480 # generates links.
482 # To enable system wide have in $GITWEB_CONFIG
483 # $feature{'pathinfo'}{'default'} = [1];
484 # Project specific override is not supported.
486 # Note that you will need to change the default location of CSS,
487 # favicon, logo and possibly other files to an absolute URL. Also,
488 # if gitweb.cgi serves as your indexfile, you will need to force
489 # $my_uri to contain the script name in your $GITWEB_CONFIG.
490 'pathinfo' => {
491 'override' => 0,
492 'default' => [0]},
494 # Make gitweb consider projects in project root subdirectories
495 # to be forks of existing projects. Given project $projname.git,
496 # projects matching $projname/*.git will not be shown in the main
497 # projects list, instead a '+' mark will be added to $projname
498 # there and a 'forks' view will be enabled for the project, listing
499 # all the forks. If project list is taken from a file, forks have
500 # to be listed after the main project.
502 # To enable system wide have in $GITWEB_CONFIG
503 # $feature{'forks'}{'default'} = [1];
504 # Project specific override is not supported.
505 'forks' => {
506 'override' => 0,
507 'default' => [0]},
509 # Insert custom links to the action bar of all project pages.
510 # This enables you mainly to link to third-party scripts integrating
511 # into gitweb; e.g. git-browser for graphical history representation
512 # or custom web-based repository administration interface.
514 # The 'default' value consists of a list of triplets in the form
515 # (label, link, position) where position is the label after which
516 # to insert the link and link is a format string where %n expands
517 # to the project name, %f to the project path within the filesystem,
518 # %h to the current hash (h gitweb parameter) and %b to the current
519 # hash base (hb gitweb parameter); %% expands to %.
521 # To enable system wide have in $GITWEB_CONFIG e.g.
522 # $feature{'actions'}{'default'} = [('graphiclog',
523 # '/git-browser/by-commit.html?r=%n', 'summary')];
524 # Project specific override is not supported.
525 'actions' => {
526 'override' => 0,
527 'default' => []},
529 # Allow gitweb scan project content tags described in ctags/
530 # of project repository, and display the popular Web 2.0-ish
531 # "tag cloud" near the project list. Note that this is something
532 # COMPLETELY different from the normal Git tags.
534 # gitweb by itself can show existing tags, but it does not handle
535 # tagging itself; you need an external application for that.
536 # For an example script, check Girocco's cgi/tagproj.cgi.
537 # You may want to install the HTML::TagCloud Perl module to get
538 # a pretty tag cloud instead of just a list of tags.
540 # To enable system wide have in $GITWEB_CONFIG
541 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
542 # Project specific override is not supported.
543 'ctags' => {
544 'override' => 0,
545 'default' => [0]},
547 # The maximum number of patches in a patchset generated in patch
548 # view. Set this to 0 or undef to disable patch view, or to a
549 # negative number to remove any limit.
551 # To disable system wide have in $GITWEB_CONFIG
552 # $feature{'patches'}{'default'} = [0];
553 # To have project specific config enable override in $GITWEB_CONFIG
554 # $feature{'patches'}{'override'} = 1;
555 # and in project config gitweb.patches = 0|n;
556 # where n is the maximum number of patches allowed in a patchset.
557 'patches' => {
558 'sub' => \&feature_patches,
559 'override' => 0,
560 'default' => [16]},
562 # Avatar support. When this feature is enabled, views such as
563 # shortlog or commit will display an avatar associated with
564 # the email of the committer(s) and/or author(s).
566 # Currently available providers are gravatar and picon.
567 # If an unknown provider is specified, the feature is disabled.
569 # Gravatar depends on Digest::MD5.
570 # Picon currently relies on the indiana.edu database.
572 # To enable system wide have in $GITWEB_CONFIG
573 # $feature{'avatar'}{'default'} = ['<provider>'];
574 # where <provider> is either gravatar or picon.
575 # To have project specific config enable override in $GITWEB_CONFIG
576 # $feature{'avatar'}{'override'} = 1;
577 # and in project config gitweb.avatar = <provider>;
578 'avatar' => {
579 'sub' => \&feature_avatar,
580 'override' => 0,
581 'default' => ['']},
583 # Enable displaying how much time and how many git commands
584 # it took to generate and display page. Disabled by default.
585 # Project specific override is not supported.
586 'timed' => {
587 'override' => 0,
588 'default' => [0]},
590 # Enable turning some links into links to actions which require
591 # JavaScript to run (like 'blame_incremental'). Not enabled by
592 # default. Project specific override is currently not supported.
593 'javascript-actions' => {
594 'override' => 0,
595 'default' => [0]},
597 # Syntax highlighting support. This is based on Daniel Svensson's
598 # and Sham Chukoury's work in gitweb-xmms2.git.
599 # It requires the 'highlight' program present in $PATH,
600 # and therefore is disabled by default.
602 # To enable system wide have in $GITWEB_CONFIG
603 # $feature{'highlight'}{'default'} = [1];
605 'highlight' => {
606 'sub' => sub { feature_bool('highlight', @_) },
607 'override' => 0,
608 'default' => [0]},
611 sub gitweb_get_feature {
612 my ($name) = @_;
613 return unless exists $feature{$name};
614 my ($sub, $override, @defaults) = (
615 $feature{$name}{'sub'},
616 $feature{$name}{'override'},
617 @{$feature{$name}{'default'}});
618 # project specific override is possible only if we have project
619 our $git_dir; # global variable, declared later
620 if (!$override || !defined $git_dir) {
621 return @defaults;
623 if (!defined $sub) {
624 warn "feature $name is not overridable";
625 return @defaults;
627 return $sub->(@defaults);
630 # A wrapper to check if a given feature is enabled.
631 # With this, you can say
633 # my $bool_feat = gitweb_check_feature('bool_feat');
634 # gitweb_check_feature('bool_feat') or somecode;
636 # instead of
638 # my ($bool_feat) = gitweb_get_feature('bool_feat');
639 # (gitweb_get_feature('bool_feat'))[0] or somecode;
641 sub gitweb_check_feature {
642 return (gitweb_get_feature(@_))[0];
646 sub feature_bool {
647 my $key = shift;
648 my ($val) = git_get_project_config($key, '--bool');
650 if (!defined $val) {
651 return ($_[0]);
652 } elsif ($val eq 'true') {
653 return (1);
654 } elsif ($val eq 'false') {
655 return (0);
659 sub feature_snapshot {
660 my (@fmts) = @_;
662 my ($val) = git_get_project_config('snapshot');
664 if ($val) {
665 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
668 return @fmts;
671 sub feature_patches {
672 my @val = (git_get_project_config('patches', '--int'));
674 if (@val) {
675 return @val;
678 return ($_[0]);
681 sub feature_avatar {
682 my @val = (git_get_project_config('avatar'));
684 return @val ? @val : @_;
687 # checking HEAD file with -e is fragile if the repository was
688 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
689 # and then pruned.
690 sub check_head_link {
691 my ($dir) = @_;
692 my $headfile = "$dir/HEAD";
693 return ((-e $headfile) ||
694 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
697 sub check_export_ok {
698 my ($dir) = @_;
699 return (check_head_link($dir) &&
700 (!$export_ok || -e "$dir/$export_ok") &&
701 (!$export_auth_hook || $export_auth_hook->($dir)));
704 # process alternate names for backward compatibility
705 # filter out unsupported (unknown) snapshot formats
706 sub filter_snapshot_fmts {
707 my @fmts = @_;
709 @fmts = map {
710 exists $known_snapshot_format_aliases{$_} ?
711 $known_snapshot_format_aliases{$_} : $_} @fmts;
712 @fmts = grep {
713 exists $known_snapshot_formats{$_} &&
714 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
717 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
718 sub evaluate_gitweb_config {
719 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
720 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
721 # die if there are errors parsing config file
722 if (-e $GITWEB_CONFIG) {
723 do $GITWEB_CONFIG;
724 die $@ if $@;
725 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
726 do $GITWEB_CONFIG_SYSTEM;
727 die $@ if $@;
731 # Get loadavg of system, to compare against $maxload.
732 # Currently it requires '/proc/loadavg' present to get loadavg;
733 # if it is not present it returns 0, which means no load checking.
734 sub get_loadavg {
735 if( -e '/proc/loadavg' ){
736 open my $fd, '<', '/proc/loadavg'
737 or return 0;
738 my @load = split(/\s+/, scalar <$fd>);
739 close $fd;
741 # The first three columns measure CPU and IO utilization of the last one,
742 # five, and 10 minute periods. The fourth column shows the number of
743 # currently running processes and the total number of processes in the m/n
744 # format. The last column displays the last process ID used.
745 return $load[0] || 0;
747 # additional checks for load average should go here for things that don't export
748 # /proc/loadavg
750 return 0;
753 # version of the core git binary
754 our $git_version;
755 sub evaluate_git_version {
756 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
757 $number_of_git_cmds++;
760 sub check_loadavg {
761 if (defined $maxload && get_loadavg() > $maxload) {
762 die_error(503, "The load average on the server is too high");
766 # ======================================================================
767 # input validation and dispatch
769 # input parameters can be collected from a variety of sources (presently, CGI
770 # and PATH_INFO), so we define an %input_params hash that collects them all
771 # together during validation: this allows subsequent uses (e.g. href()) to be
772 # agnostic of the parameter origin
774 our %input_params = ();
776 # input parameters are stored with the long parameter name as key. This will
777 # also be used in the href subroutine to convert parameters to their CGI
778 # equivalent, and since the href() usage is the most frequent one, we store
779 # the name -> CGI key mapping here, instead of the reverse.
781 # XXX: Warning: If you touch this, check the search form for updating,
782 # too.
784 our @cgi_param_mapping = (
785 project => "p",
786 action => "a",
787 file_name => "f",
788 file_parent => "fp",
789 hash => "h",
790 hash_parent => "hp",
791 hash_base => "hb",
792 hash_parent_base => "hpb",
793 page => "pg",
794 order => "o",
795 searchtext => "s",
796 searchtype => "st",
797 snapshot_format => "sf",
798 extra_options => "opt",
799 search_use_regexp => "sr",
800 # this must be last entry (for manipulation from JavaScript)
801 javascript => "js"
803 our %cgi_param_mapping = @cgi_param_mapping;
805 # we will also need to know the possible actions, for validation
806 our %actions = (
807 "blame" => \&git_blame,
808 "blame_incremental" => \&git_blame_incremental,
809 "blame_data" => \&git_blame_data,
810 "blobdiff" => \&git_blobdiff,
811 "blobdiff_plain" => \&git_blobdiff_plain,
812 "blob" => \&git_blob,
813 "blob_plain" => \&git_blob_plain,
814 "commitdiff" => \&git_commitdiff,
815 "commitdiff_plain" => \&git_commitdiff_plain,
816 "commit" => \&git_commit,
817 "forks" => \&git_forks,
818 "heads" => \&git_heads,
819 "history" => \&git_history,
820 "log" => \&git_log,
821 "patch" => \&git_patch,
822 "patches" => \&git_patches,
823 "rss" => \&git_rss,
824 "atom" => \&git_atom,
825 "search" => \&git_search,
826 "search_help" => \&git_search_help,
827 "shortlog" => \&git_shortlog,
828 "summary" => \&git_summary,
829 "tag" => \&git_tag,
830 "tags" => \&git_tags,
831 "tree" => \&git_tree,
832 "snapshot" => \&git_snapshot,
833 "object" => \&git_object,
834 # those below don't need $project
835 "opml" => \&git_opml,
836 "project_list" => \&git_project_list,
837 "project_index" => \&git_project_index,
840 # finally, we have the hash of allowed extra_options for the commands that
841 # allow them
842 our %allowed_options = (
843 "--no-merges" => [ qw(rss atom log shortlog history) ],
846 our %actions_info = ();
847 sub evaluate_actions_info {
848 our %actions_info;
849 our (%actions);
851 # unless explicitely stated otherwise, default output format is html
852 foreach my $action (keys %actions) {
853 $actions_info{$action}{'output_format'} = 'html';
855 # list all exceptions; undef means variable (no definite format)
856 map { $actions_info{$_}{'output_format'} = 'text' }
857 qw(commitdiff_plain patch patches project_index blame_data);
858 map { $actions_info{$_}{'output_format'} = 'xml' }
859 qw(rss atom opml); # there are different types (document formats) of XML
860 map { $actions_info{$_}{'output_format'} = undef }
861 qw(blob_plain object);
862 $actions_info{'snapshot'}{'output_format'} = 'binary';
865 sub action_outputs_html {
866 my $action = shift;
867 return $actions_info{$action}{'output_format'} eq 'html';
870 sub browser_is_robot {
871 return 1 if !exists $ENV{'HTTP_USER_AGENT'}; # gitweb run as script
872 if (eval { require HTTP::BrowserDetect; }) {
873 my $browser = HTTP::BrowserDetect->new();
874 return $browser->robot();
876 # fallback on detecting known web browsers
877 return 0 if ($ENV{'HTTP_USER_AGENT'} =~ /\b(?:Mozilla|Opera|Safari|IE)\b/);
878 # be conservative; if not sure, assume non-interactive
879 return 1;
882 # fill %input_params with the CGI parameters. All values except for 'opt'
883 # should be single values, but opt can be an array. We should probably
884 # build an array of parameters that can be multi-valued, but since for the time
885 # being it's only this one, we just single it out
886 sub evaluate_query_params {
887 our $cgi;
889 while (my ($name, $symbol) = each %cgi_param_mapping) {
890 if ($symbol eq 'opt') {
891 $input_params{$name} = [ $cgi->param($symbol) ];
892 } else {
893 $input_params{$name} = $cgi->param($symbol);
898 # now read PATH_INFO and update the parameter list for missing parameters
899 sub evaluate_path_info {
900 return if defined $input_params{'project'};
901 return if !$path_info;
902 $path_info =~ s,^/+,,;
903 return if !$path_info;
905 # find which part of PATH_INFO is project
906 my $project = $path_info;
907 $project =~ s,/+$,,;
908 while ($project && !check_head_link("$projectroot/$project")) {
909 $project =~ s,/*[^/]*$,,;
911 return unless $project;
912 $input_params{'project'} = $project;
914 # do not change any parameters if an action is given using the query string
915 return if $input_params{'action'};
916 $path_info =~ s,^\Q$project\E/*,,;
918 # next, check if we have an action
919 my $action = $path_info;
920 $action =~ s,/.*$,,;
921 if (exists $actions{$action}) {
922 $path_info =~ s,^$action/*,,;
923 $input_params{'action'} = $action;
926 # list of actions that want hash_base instead of hash, but can have no
927 # pathname (f) parameter
928 my @wants_base = (
929 'tree',
930 'history',
933 # we want to catch, among others
934 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
935 my ($parentrefname, $parentpathname, $refname, $pathname) =
936 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
938 # first, analyze the 'current' part
939 if (defined $pathname) {
940 # we got "branch:filename" or "branch:dir/"
941 # we could use git_get_type(branch:pathname), but:
942 # - it needs $git_dir
943 # - it does a git() call
944 # - the convention of terminating directories with a slash
945 # makes it superfluous
946 # - embedding the action in the PATH_INFO would make it even
947 # more superfluous
948 $pathname =~ s,^/+,,;
949 if (!$pathname || substr($pathname, -1) eq "/") {
950 $input_params{'action'} ||= "tree";
951 $pathname =~ s,/$,,;
952 } else {
953 # the default action depends on whether we had parent info
954 # or not
955 if ($parentrefname) {
956 $input_params{'action'} ||= "blobdiff_plain";
957 } else {
958 $input_params{'action'} ||= "blob_plain";
961 $input_params{'hash_base'} ||= $refname;
962 $input_params{'file_name'} ||= $pathname;
963 } elsif (defined $refname) {
964 # we got "branch". In this case we have to choose if we have to
965 # set hash or hash_base.
967 # Most of the actions without a pathname only want hash to be
968 # set, except for the ones specified in @wants_base that want
969 # hash_base instead. It should also be noted that hand-crafted
970 # links having 'history' as an action and no pathname or hash
971 # set will fail, but that happens regardless of PATH_INFO.
972 if (defined $parentrefname) {
973 # if there is parent let the default be 'shortlog' action
974 # (for http://git.example.com/repo.git/A..B links); if there
975 # is no parent, dispatch will detect type of object and set
976 # action appropriately if required (if action is not set)
977 $input_params{'action'} ||= "shortlog";
979 if ($input_params{'action'} &&
980 grep { $_ eq $input_params{'action'} } @wants_base) {
981 $input_params{'hash_base'} ||= $refname;
982 } else {
983 $input_params{'hash'} ||= $refname;
987 # next, handle the 'parent' part, if present
988 if (defined $parentrefname) {
989 # a missing pathspec defaults to the 'current' filename, allowing e.g.
990 # someproject/blobdiff/oldrev..newrev:/filename
991 if ($parentpathname) {
992 $parentpathname =~ s,^/+,,;
993 $parentpathname =~ s,/$,,;
994 $input_params{'file_parent'} ||= $parentpathname;
995 } else {
996 $input_params{'file_parent'} ||= $input_params{'file_name'};
998 # we assume that hash_parent_base is wanted if a path was specified,
999 # or if the action wants hash_base instead of hash
1000 if (defined $input_params{'file_parent'} ||
1001 grep { $_ eq $input_params{'action'} } @wants_base) {
1002 $input_params{'hash_parent_base'} ||= $parentrefname;
1003 } else {
1004 $input_params{'hash_parent'} ||= $parentrefname;
1008 # for the snapshot action, we allow URLs in the form
1009 # $project/snapshot/$hash.ext
1010 # where .ext determines the snapshot and gets removed from the
1011 # passed $refname to provide the $hash.
1013 # To be able to tell that $refname includes the format extension, we
1014 # require the following two conditions to be satisfied:
1015 # - the hash input parameter MUST have been set from the $refname part
1016 # of the URL (i.e. they must be equal)
1017 # - the snapshot format MUST NOT have been defined already (e.g. from
1018 # CGI parameter sf)
1019 # It's also useless to try any matching unless $refname has a dot,
1020 # so we check for that too
1021 if (defined $input_params{'action'} &&
1022 $input_params{'action'} eq 'snapshot' &&
1023 defined $refname && index($refname, '.') != -1 &&
1024 $refname eq $input_params{'hash'} &&
1025 !defined $input_params{'snapshot_format'}) {
1026 # We loop over the known snapshot formats, checking for
1027 # extensions. Allowed extensions are both the defined suffix
1028 # (which includes the initial dot already) and the snapshot
1029 # format key itself, with a prepended dot
1030 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1031 my $hash = $refname;
1032 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1033 next;
1035 my $sfx = $1;
1036 # a valid suffix was found, so set the snapshot format
1037 # and reset the hash parameter
1038 $input_params{'snapshot_format'} = $fmt;
1039 $input_params{'hash'} = $hash;
1040 # we also set the format suffix to the one requested
1041 # in the URL: this way a request for e.g. .tgz returns
1042 # a .tgz instead of a .tar.gz
1043 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1044 last;
1049 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1050 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1051 $searchtext, $search_regexp);
1052 sub evaluate_and_validate_params {
1053 our $action = $input_params{'action'};
1054 if (defined $action) {
1055 if (!validate_action($action)) {
1056 die_error(400, "Invalid action parameter");
1060 # parameters which are pathnames
1061 our $project = $input_params{'project'};
1062 if (defined $project) {
1063 if (!validate_project($project)) {
1064 undef $project;
1065 die_error(404, "No such project");
1069 our $file_name = $input_params{'file_name'};
1070 if (defined $file_name) {
1071 if (!validate_pathname($file_name)) {
1072 die_error(400, "Invalid file parameter");
1076 our $file_parent = $input_params{'file_parent'};
1077 if (defined $file_parent) {
1078 if (!validate_pathname($file_parent)) {
1079 die_error(400, "Invalid file parent parameter");
1083 # parameters which are refnames
1084 our $hash = $input_params{'hash'};
1085 if (defined $hash) {
1086 if (!validate_refname($hash)) {
1087 die_error(400, "Invalid hash parameter");
1091 our $hash_parent = $input_params{'hash_parent'};
1092 if (defined $hash_parent) {
1093 if (!validate_refname($hash_parent)) {
1094 die_error(400, "Invalid hash parent parameter");
1098 our $hash_base = $input_params{'hash_base'};
1099 if (defined $hash_base) {
1100 if (!validate_refname($hash_base)) {
1101 die_error(400, "Invalid hash base parameter");
1105 our @extra_options = @{$input_params{'extra_options'}};
1106 # @extra_options is always defined, since it can only be (currently) set from
1107 # CGI, and $cgi->param() returns the empty array in array context if the param
1108 # is not set
1109 foreach my $opt (@extra_options) {
1110 if (not exists $allowed_options{$opt}) {
1111 die_error(400, "Invalid option parameter");
1113 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1114 die_error(400, "Invalid option parameter for this action");
1118 our $hash_parent_base = $input_params{'hash_parent_base'};
1119 if (defined $hash_parent_base) {
1120 if (!validate_refname($hash_parent_base)) {
1121 die_error(400, "Invalid hash parent base parameter");
1125 # other parameters
1126 our $page = $input_params{'page'};
1127 if (defined $page) {
1128 if ($page =~ m/[^0-9]/) {
1129 die_error(400, "Invalid page parameter");
1133 our $searchtype = $input_params{'searchtype'};
1134 if (defined $searchtype) {
1135 if ($searchtype =~ m/[^a-z]/) {
1136 die_error(400, "Invalid searchtype parameter");
1140 our $search_use_regexp = $input_params{'search_use_regexp'};
1142 our $searchtext = $input_params{'searchtext'};
1143 our $search_regexp;
1144 if (defined $searchtext) {
1145 if (length($searchtext) < 2) {
1146 die_error(403, "At least two characters are required for search parameter");
1148 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1152 # path to the current git repository
1153 our $git_dir;
1154 sub evaluate_git_dir {
1155 our $git_dir = "$projectroot/$project" if $project;
1158 our (@snapshot_fmts, $git_avatar);
1159 sub configure_gitweb_features {
1160 # list of supported snapshot formats
1161 our @snapshot_fmts = gitweb_get_feature('snapshot');
1162 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1164 # check that the avatar feature is set to a known provider name,
1165 # and for each provider check if the dependencies are satisfied.
1166 # if the provider name is invalid or the dependencies are not met,
1167 # reset $git_avatar to the empty string.
1168 our ($git_avatar) = gitweb_get_feature('avatar');
1169 if ($git_avatar eq 'gravatar') {
1170 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1171 } elsif ($git_avatar eq 'picon') {
1172 # no dependencies
1173 } else {
1174 $git_avatar = '';
1178 # custom error handler: 'die <message>' is Internal Server Error
1179 sub handle_errors_html {
1180 my $msg = shift; # it is already HTML escaped
1182 # to avoid infinite loop where error occurs in die_error,
1183 # change handler to default handler, disabling handle_errors_html
1184 set_message("Error occured when inside die_error:\n$msg");
1186 # you cannot jump out of die_error when called as error handler;
1187 # the subroutine set via CGI::Carp::set_message is called _after_
1188 # HTTP headers are already written, so it cannot write them itself
1189 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1191 set_message(\&handle_errors_html);
1193 # dispatch
1194 sub dispatch {
1195 if (!defined $action) {
1196 if (defined $hash) {
1197 $action = git_get_type($hash);
1198 } elsif (defined $hash_base && defined $file_name) {
1199 $action = git_get_type("$hash_base:$file_name");
1200 } elsif (defined $project) {
1201 $action = 'summary';
1202 } else {
1203 $action = 'project_list';
1206 if (!defined($actions{$action})) {
1207 die_error(400, "Unknown action");
1209 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1210 !$project) {
1211 die_error(400, "Project needed");
1214 if ($caching_enabled) {
1215 # human readable key identifying gitweb output
1216 my $output_key = href(-replay => 1, -full => 1, -path_info => 0);
1218 cache_output($cache, $capture, $output_key, $actions{$action});
1219 } else {
1220 $actions{$action}->();
1224 sub reset_timer {
1225 our $t0 = [Time::HiRes::gettimeofday()]
1226 if defined $t0;
1227 our $number_of_git_cmds = 0;
1230 sub run_request {
1231 reset_timer();
1233 evaluate_uri();
1234 evaluate_gitweb_config();
1235 evaluate_git_version();
1236 check_loadavg();
1237 configure_caching()
1238 if ($caching_enabled);
1240 # $projectroot and $projects_list might be set in gitweb config file
1241 $projects_list ||= $projectroot;
1243 evaluate_query_params();
1244 evaluate_path_info();
1245 evaluate_and_validate_params();
1246 evaluate_git_dir();
1248 configure_gitweb_features();
1250 dispatch();
1253 our $is_last_request = sub { 1 };
1254 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1255 our $CGI = 'CGI';
1256 our $cgi;
1257 sub configure_as_fcgi {
1258 require CGI::Fast;
1259 our $CGI = 'CGI::Fast';
1261 my $request_number = 0;
1262 # let each child service 100 requests
1263 our $is_last_request = sub { ++$request_number > 100 };
1265 sub evaluate_argv {
1266 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1267 configure_as_fcgi()
1268 if $script_name =~ /\.fcgi$/;
1270 return unless (@ARGV);
1272 require Getopt::Long;
1273 Getopt::Long::GetOptions(
1274 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1275 'nproc|n=i' => sub {
1276 my ($arg, $val) = @_;
1277 return unless eval { require FCGI::ProcManager; 1; };
1278 my $proc_manager = FCGI::ProcManager->new({
1279 n_processes => $val,
1281 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1282 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1283 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1288 sub run {
1289 evaluate_argv();
1290 evaluate_actions_info();
1292 $pre_listen_hook->()
1293 if $pre_listen_hook;
1295 REQUEST:
1296 while ($cgi = $CGI->new()) {
1297 $pre_dispatch_hook->()
1298 if $pre_dispatch_hook;
1300 run_request();
1302 $post_dispatch_hook->()
1303 if $post_dispatch_hook;
1305 last REQUEST if ($is_last_request->());
1308 DONE_GITWEB:
1312 sub configure_caching {
1313 if (!eval { require GitwebCache::CacheOutput; 1; }) {
1314 # cache is configured _before_ handling request, so $cgi is not defined,
1315 # so we can't just "die" with sending error message to web browser
1316 #die_error(500, "Caching enabled and GitwebCache::CacheOutput not found");
1318 # turn off caching and warn instead
1319 $caching_enabled = 0;
1320 warn "Caching enabled and GitwebCache::CacheOutput not found";
1322 GitwebCache::CacheOutput->import();
1324 # $cache might be initialized (instantiated) cache, i.e. cache object,
1325 # or it might be name of class, or it might be undefined
1326 unless (defined $cache && ref($cache)) {
1327 $cache ||= 'GitwebCache::FileCacheWithLocking';
1328 eval "require $cache";
1329 die $@ if $@;
1330 $cache = $cache->new({
1331 %cache_options,
1332 #'cache_root' => '/tmp/cache',
1333 #'cache_depth' => 2,
1334 #'expires_in' => 20, # in seconds (CHI compatibile)
1335 # (Cache::Cache compatibile initialization)
1336 'default_expires_in' => $cache_options{'expires_in'},
1337 # (CHI compatibile initialization)
1338 'root_dir' => $cache_options{'cache_root'},
1339 'depth' => $cache_options{'cache_depth'},
1342 unless (defined $capture && ref($capture)) {
1343 require GitwebCache::Capture::Simple;
1344 $capture = GitwebCache::Capture::Simple->new();
1348 run();
1350 if (defined caller) {
1351 # wrapped in a subroutine processing requests,
1352 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1353 return;
1354 } else {
1355 # pure CGI script, serving single request
1356 exit;
1359 ## ======================================================================
1360 ## action links
1362 # possible values of extra options
1363 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1364 # -replay => 1 - start from a current view (replay with modifications)
1365 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1366 sub href {
1367 my %params = @_;
1368 # default is to use -absolute url() i.e. $my_uri
1369 my $href = $params{-full} ? $my_url : $my_uri;
1371 $params{'project'} = $project unless exists $params{'project'};
1373 if ($params{-replay}) {
1374 while (my ($name, $symbol) = each %cgi_param_mapping) {
1375 if (!exists $params{$name}) {
1376 $params{$name} = $input_params{$name};
1381 my $use_pathinfo = gitweb_check_feature('pathinfo');
1382 if (defined $params{'project'} &&
1383 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1384 # try to put as many parameters as possible in PATH_INFO:
1385 # - project name
1386 # - action
1387 # - hash_parent or hash_parent_base:/file_parent
1388 # - hash or hash_base:/filename
1389 # - the snapshot_format as an appropriate suffix
1391 # When the script is the root DirectoryIndex for the domain,
1392 # $href here would be something like http://gitweb.example.com/
1393 # Thus, we strip any trailing / from $href, to spare us double
1394 # slashes in the final URL
1395 $href =~ s,/$,,;
1397 # Then add the project name, if present
1398 $href .= "/".esc_url($params{'project'});
1399 delete $params{'project'};
1401 # since we destructively absorb parameters, we keep this
1402 # boolean that remembers if we're handling a snapshot
1403 my $is_snapshot = $params{'action'} eq 'snapshot';
1405 # Summary just uses the project path URL, any other action is
1406 # added to the URL
1407 if (defined $params{'action'}) {
1408 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1409 delete $params{'action'};
1412 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1413 # stripping nonexistent or useless pieces
1414 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1415 || $params{'hash_parent'} || $params{'hash'});
1416 if (defined $params{'hash_base'}) {
1417 if (defined $params{'hash_parent_base'}) {
1418 $href .= esc_url($params{'hash_parent_base'});
1419 # skip the file_parent if it's the same as the file_name
1420 if (defined $params{'file_parent'}) {
1421 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1422 delete $params{'file_parent'};
1423 } elsif ($params{'file_parent'} !~ /\.\./) {
1424 $href .= ":/".esc_url($params{'file_parent'});
1425 delete $params{'file_parent'};
1428 $href .= "..";
1429 delete $params{'hash_parent'};
1430 delete $params{'hash_parent_base'};
1431 } elsif (defined $params{'hash_parent'}) {
1432 $href .= esc_url($params{'hash_parent'}). "..";
1433 delete $params{'hash_parent'};
1436 $href .= esc_url($params{'hash_base'});
1437 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1438 $href .= ":/".esc_url($params{'file_name'});
1439 delete $params{'file_name'};
1441 delete $params{'hash'};
1442 delete $params{'hash_base'};
1443 } elsif (defined $params{'hash'}) {
1444 $href .= esc_url($params{'hash'});
1445 delete $params{'hash'};
1448 # If the action was a snapshot, we can absorb the
1449 # snapshot_format parameter too
1450 if ($is_snapshot) {
1451 my $fmt = $params{'snapshot_format'};
1452 # snapshot_format should always be defined when href()
1453 # is called, but just in case some code forgets, we
1454 # fall back to the default
1455 $fmt ||= $snapshot_fmts[0];
1456 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1457 delete $params{'snapshot_format'};
1461 # now encode the parameters explicitly
1462 my @result = ();
1463 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1464 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1465 if (defined $params{$name}) {
1466 if (ref($params{$name}) eq "ARRAY") {
1467 foreach my $par (@{$params{$name}}) {
1468 push @result, $symbol . "=" . esc_param($par);
1470 } else {
1471 push @result, $symbol . "=" . esc_param($params{$name});
1475 $href .= "?" . join(';', @result) if scalar @result;
1477 return $href;
1481 ## ======================================================================
1482 ## validation, quoting/unquoting and escaping
1484 sub validate_action {
1485 my $input = shift || return undef;
1486 return undef unless exists $actions{$input};
1487 return $input;
1490 sub validate_project {
1491 my $input = shift || return undef;
1492 if (!validate_pathname($input) ||
1493 !(-d "$projectroot/$input") ||
1494 !check_export_ok("$projectroot/$input") ||
1495 ($strict_export && !project_in_list($input))) {
1496 return undef;
1497 } else {
1498 return $input;
1502 sub validate_pathname {
1503 my $input = shift || return undef;
1505 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1506 # at the beginning, at the end, and between slashes.
1507 # also this catches doubled slashes
1508 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1509 return undef;
1511 # no null characters
1512 if ($input =~ m!\0!) {
1513 return undef;
1515 return $input;
1518 sub validate_refname {
1519 my $input = shift || return undef;
1521 # textual hashes are O.K.
1522 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1523 return $input;
1525 # it must be correct pathname
1526 $input = validate_pathname($input)
1527 or return undef;
1528 # restrictions on ref name according to git-check-ref-format
1529 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1530 return undef;
1532 return $input;
1535 # decode sequences of octets in utf8 into Perl's internal form,
1536 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1537 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1538 sub to_utf8 {
1539 my $str = shift;
1540 return undef unless defined $str;
1541 if (utf8::valid($str)) {
1542 utf8::decode($str);
1543 return $str;
1544 } else {
1545 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1549 # quote unsafe chars, but keep the slash, even when it's not
1550 # correct, but quoted slashes look too horrible in bookmarks
1551 sub esc_param {
1552 my $str = shift;
1553 return undef unless defined $str;
1554 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1555 $str =~ s/ /\+/g;
1556 return $str;
1559 # quote unsafe chars in whole URL, so some characters cannot be quoted
1560 sub esc_url {
1561 my $str = shift;
1562 return undef unless defined $str;
1563 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1564 $str =~ s/ /\+/g;
1565 return $str;
1568 # replace invalid utf8 character with SUBSTITUTION sequence
1569 sub esc_html {
1570 my $str = shift;
1571 my %opts = @_;
1573 return undef unless defined $str;
1575 $str = to_utf8($str);
1576 $str = $cgi->escapeHTML($str);
1577 if ($opts{'-nbsp'}) {
1578 $str =~ s/ /&nbsp;/g;
1580 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1581 return $str;
1584 # quote control characters and escape filename to HTML
1585 sub esc_path {
1586 my $str = shift;
1587 my %opts = @_;
1589 return undef unless defined $str;
1591 $str = to_utf8($str);
1592 $str = $cgi->escapeHTML($str);
1593 if ($opts{'-nbsp'}) {
1594 $str =~ s/ /&nbsp;/g;
1596 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1597 return $str;
1600 # Make control characters "printable", using character escape codes (CEC)
1601 sub quot_cec {
1602 my $cntrl = shift;
1603 my %opts = @_;
1604 my %es = ( # character escape codes, aka escape sequences
1605 "\t" => '\t', # tab (HT)
1606 "\n" => '\n', # line feed (LF)
1607 "\r" => '\r', # carrige return (CR)
1608 "\f" => '\f', # form feed (FF)
1609 "\b" => '\b', # backspace (BS)
1610 "\a" => '\a', # alarm (bell) (BEL)
1611 "\e" => '\e', # escape (ESC)
1612 "\013" => '\v', # vertical tab (VT)
1613 "\000" => '\0', # nul character (NUL)
1615 my $chr = ( (exists $es{$cntrl})
1616 ? $es{$cntrl}
1617 : sprintf('\%2x', ord($cntrl)) );
1618 if ($opts{-nohtml}) {
1619 return $chr;
1620 } else {
1621 return "<span class=\"cntrl\">$chr</span>";
1625 # Alternatively use unicode control pictures codepoints,
1626 # Unicode "printable representation" (PR)
1627 sub quot_upr {
1628 my $cntrl = shift;
1629 my %opts = @_;
1631 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1632 if ($opts{-nohtml}) {
1633 return $chr;
1634 } else {
1635 return "<span class=\"cntrl\">$chr</span>";
1639 # git may return quoted and escaped filenames
1640 sub unquote {
1641 my $str = shift;
1643 sub unq {
1644 my $seq = shift;
1645 my %es = ( # character escape codes, aka escape sequences
1646 't' => "\t", # tab (HT, TAB)
1647 'n' => "\n", # newline (NL)
1648 'r' => "\r", # return (CR)
1649 'f' => "\f", # form feed (FF)
1650 'b' => "\b", # backspace (BS)
1651 'a' => "\a", # alarm (bell) (BEL)
1652 'e' => "\e", # escape (ESC)
1653 'v' => "\013", # vertical tab (VT)
1656 if ($seq =~ m/^[0-7]{1,3}$/) {
1657 # octal char sequence
1658 return chr(oct($seq));
1659 } elsif (exists $es{$seq}) {
1660 # C escape sequence, aka character escape code
1661 return $es{$seq};
1663 # quoted ordinary character
1664 return $seq;
1667 if ($str =~ m/^"(.*)"$/) {
1668 # needs unquoting
1669 $str = $1;
1670 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1672 return $str;
1675 # escape tabs (convert tabs to spaces)
1676 sub untabify {
1677 my $line = shift;
1679 while ((my $pos = index($line, "\t")) != -1) {
1680 if (my $count = (8 - ($pos % 8))) {
1681 my $spaces = ' ' x $count;
1682 $line =~ s/\t/$spaces/;
1686 return $line;
1689 sub project_in_list {
1690 my $project = shift;
1691 my @list = git_get_projects_list();
1692 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1695 ## ----------------------------------------------------------------------
1696 ## HTML aware string manipulation
1698 # Try to chop given string on a word boundary between position
1699 # $len and $len+$add_len. If there is no word boundary there,
1700 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1701 # (marking chopped part) would be longer than given string.
1702 sub chop_str {
1703 my $str = shift;
1704 my $len = shift;
1705 my $add_len = shift || 10;
1706 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1708 # Make sure perl knows it is utf8 encoded so we don't
1709 # cut in the middle of a utf8 multibyte char.
1710 $str = to_utf8($str);
1712 # allow only $len chars, but don't cut a word if it would fit in $add_len
1713 # if it doesn't fit, cut it if it's still longer than the dots we would add
1714 # remove chopped character entities entirely
1716 # when chopping in the middle, distribute $len into left and right part
1717 # return early if chopping wouldn't make string shorter
1718 if ($where eq 'center') {
1719 return $str if ($len + 5 >= length($str)); # filler is length 5
1720 $len = int($len/2);
1721 } else {
1722 return $str if ($len + 4 >= length($str)); # filler is length 4
1725 # regexps: ending and beginning with word part up to $add_len
1726 my $endre = qr/.{$len}\w{0,$add_len}/;
1727 my $begre = qr/\w{0,$add_len}.{$len}/;
1729 if ($where eq 'left') {
1730 $str =~ m/^(.*?)($begre)$/;
1731 my ($lead, $body) = ($1, $2);
1732 if (length($lead) > 4) {
1733 $lead = " ...";
1735 return "$lead$body";
1737 } elsif ($where eq 'center') {
1738 $str =~ m/^($endre)(.*)$/;
1739 my ($left, $str) = ($1, $2);
1740 $str =~ m/^(.*?)($begre)$/;
1741 my ($mid, $right) = ($1, $2);
1742 if (length($mid) > 5) {
1743 $mid = " ... ";
1745 return "$left$mid$right";
1747 } else {
1748 $str =~ m/^($endre)(.*)$/;
1749 my $body = $1;
1750 my $tail = $2;
1751 if (length($tail) > 4) {
1752 $tail = "... ";
1754 return "$body$tail";
1758 # takes the same arguments as chop_str, but also wraps a <span> around the
1759 # result with a title attribute if it does get chopped. Additionally, the
1760 # string is HTML-escaped.
1761 sub chop_and_escape_str {
1762 my ($str) = @_;
1764 my $chopped = chop_str(@_);
1765 if ($chopped eq $str) {
1766 return esc_html($chopped);
1767 } else {
1768 $str =~ s/[[:cntrl:]]/?/g;
1769 return $cgi->span({-title=>$str}, esc_html($chopped));
1773 ## ----------------------------------------------------------------------
1774 ## functions returning short strings
1776 # CSS class for given age value (in seconds)
1777 sub age_class {
1778 my $age = shift;
1780 if (!defined $age) {
1781 return "noage";
1782 } elsif ($age < 60*60*2) {
1783 return "age0";
1784 } elsif ($age < 60*60*24*2) {
1785 return "age1";
1786 } else {
1787 return "age2";
1791 # convert age in seconds to "nn units ago" string
1792 sub age_string {
1793 my $age = shift;
1794 my $age_str;
1796 if ($age > 60*60*24*365*2) {
1797 $age_str = (int $age/60/60/24/365);
1798 $age_str .= " years ago";
1799 } elsif ($age > 60*60*24*(365/12)*2) {
1800 $age_str = int $age/60/60/24/(365/12);
1801 $age_str .= " months ago";
1802 } elsif ($age > 60*60*24*7*2) {
1803 $age_str = int $age/60/60/24/7;
1804 $age_str .= " weeks ago";
1805 } elsif ($age > 60*60*24*2) {
1806 $age_str = int $age/60/60/24;
1807 $age_str .= " days ago";
1808 } elsif ($age > 60*60*2) {
1809 $age_str = int $age/60/60;
1810 $age_str .= " hours ago";
1811 } elsif ($age > 60*2) {
1812 $age_str = int $age/60;
1813 $age_str .= " min ago";
1814 } elsif ($age > 2) {
1815 $age_str = int $age;
1816 $age_str .= " sec ago";
1817 } else {
1818 $age_str .= " right now";
1820 return $age_str;
1823 use constant {
1824 S_IFINVALID => 0030000,
1825 S_IFGITLINK => 0160000,
1828 # submodule/subproject, a commit object reference
1829 sub S_ISGITLINK {
1830 my $mode = shift;
1832 return (($mode & S_IFMT) == S_IFGITLINK)
1835 # convert file mode in octal to symbolic file mode string
1836 sub mode_str {
1837 my $mode = oct shift;
1839 if (S_ISGITLINK($mode)) {
1840 return 'm---------';
1841 } elsif (S_ISDIR($mode & S_IFMT)) {
1842 return 'drwxr-xr-x';
1843 } elsif (S_ISLNK($mode)) {
1844 return 'lrwxrwxrwx';
1845 } elsif (S_ISREG($mode)) {
1846 # git cares only about the executable bit
1847 if ($mode & S_IXUSR) {
1848 return '-rwxr-xr-x';
1849 } else {
1850 return '-rw-r--r--';
1852 } else {
1853 return '----------';
1857 # convert file mode in octal to file type string
1858 sub file_type {
1859 my $mode = shift;
1861 if ($mode !~ m/^[0-7]+$/) {
1862 return $mode;
1863 } else {
1864 $mode = oct $mode;
1867 if (S_ISGITLINK($mode)) {
1868 return "submodule";
1869 } elsif (S_ISDIR($mode & S_IFMT)) {
1870 return "directory";
1871 } elsif (S_ISLNK($mode)) {
1872 return "symlink";
1873 } elsif (S_ISREG($mode)) {
1874 return "file";
1875 } else {
1876 return "unknown";
1880 # convert file mode in octal to file type description string
1881 sub file_type_long {
1882 my $mode = shift;
1884 if ($mode !~ m/^[0-7]+$/) {
1885 return $mode;
1886 } else {
1887 $mode = oct $mode;
1890 if (S_ISGITLINK($mode)) {
1891 return "submodule";
1892 } elsif (S_ISDIR($mode & S_IFMT)) {
1893 return "directory";
1894 } elsif (S_ISLNK($mode)) {
1895 return "symlink";
1896 } elsif (S_ISREG($mode)) {
1897 if ($mode & S_IXUSR) {
1898 return "executable";
1899 } else {
1900 return "file";
1902 } else {
1903 return "unknown";
1908 ## ----------------------------------------------------------------------
1909 ## functions returning short HTML fragments, or transforming HTML fragments
1910 ## which don't belong to other sections
1912 # format line of commit message.
1913 sub format_log_line_html {
1914 my $line = shift;
1916 $line = esc_html($line, -nbsp=>1);
1917 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1918 $cgi->a({-href => href(action=>"object", hash=>$1),
1919 -class => "text"}, $1);
1920 }eg;
1922 return $line;
1925 # format marker of refs pointing to given object
1927 # the destination action is chosen based on object type and current context:
1928 # - for annotated tags, we choose the tag view unless it's the current view
1929 # already, in which case we go to shortlog view
1930 # - for other refs, we keep the current view if we're in history, shortlog or
1931 # log view, and select shortlog otherwise
1932 sub format_ref_marker {
1933 my ($refs, $id) = @_;
1934 my $markers = '';
1936 if (defined $refs->{$id}) {
1937 foreach my $ref (@{$refs->{$id}}) {
1938 # this code exploits the fact that non-lightweight tags are the
1939 # only indirect objects, and that they are the only objects for which
1940 # we want to use tag instead of shortlog as action
1941 my ($type, $name) = qw();
1942 my $indirect = ($ref =~ s/\^\{\}$//);
1943 # e.g. tags/v2.6.11 or heads/next
1944 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1945 $type = $1;
1946 $name = $2;
1947 } else {
1948 $type = "ref";
1949 $name = $ref;
1952 my $class = $type;
1953 $class .= " indirect" if $indirect;
1955 my $dest_action = "shortlog";
1957 if ($indirect) {
1958 $dest_action = "tag" unless $action eq "tag";
1959 } elsif ($action =~ /^(history|(short)?log)$/) {
1960 $dest_action = $action;
1963 my $dest = "";
1964 $dest .= "refs/" unless $ref =~ m!^refs/!;
1965 $dest .= $ref;
1967 my $link = $cgi->a({
1968 -href => href(
1969 action=>$dest_action,
1970 hash=>$dest
1971 )}, $name);
1973 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1974 $link . "</span>";
1978 if ($markers) {
1979 return ' <span class="refs">'. $markers . '</span>';
1980 } else {
1981 return "";
1985 # format, perhaps shortened and with markers, title line
1986 sub format_subject_html {
1987 my ($long, $short, $href, $extra) = @_;
1988 $extra = '' unless defined($extra);
1990 if (length($short) < length($long)) {
1991 $long =~ s/[[:cntrl:]]/?/g;
1992 return $cgi->a({-href => $href, -class => "list subject",
1993 -title => to_utf8($long)},
1994 esc_html($short)) . $extra;
1995 } else {
1996 return $cgi->a({-href => $href, -class => "list subject"},
1997 esc_html($long)) . $extra;
2001 # Rather than recomputing the url for an email multiple times, we cache it
2002 # after the first hit. This gives a visible benefit in views where the avatar
2003 # for the same email is used repeatedly (e.g. shortlog).
2004 # The cache is shared by all avatar engines (currently gravatar only), which
2005 # are free to use it as preferred. Since only one avatar engine is used for any
2006 # given page, there's no risk for cache conflicts.
2007 our %avatar_cache = ();
2009 # Compute the picon url for a given email, by using the picon search service over at
2010 # http://www.cs.indiana.edu/picons/search.html
2011 sub picon_url {
2012 my $email = lc shift;
2013 if (!$avatar_cache{$email}) {
2014 my ($user, $domain) = split('@', $email);
2015 $avatar_cache{$email} =
2016 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2017 "$domain/$user/" .
2018 "users+domains+unknown/up/single";
2020 return $avatar_cache{$email};
2023 # Compute the gravatar url for a given email, if it's not in the cache already.
2024 # Gravatar stores only the part of the URL before the size, since that's the
2025 # one computationally more expensive. This also allows reuse of the cache for
2026 # different sizes (for this particular engine).
2027 sub gravatar_url {
2028 my $email = lc shift;
2029 my $size = shift;
2030 $avatar_cache{$email} ||=
2031 "http://www.gravatar.com/avatar/" .
2032 Digest::MD5::md5_hex($email) . "?s=";
2033 return $avatar_cache{$email} . $size;
2036 # Insert an avatar for the given $email at the given $size if the feature
2037 # is enabled.
2038 sub git_get_avatar {
2039 my ($email, %opts) = @_;
2040 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2041 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2042 $opts{-size} ||= 'default';
2043 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2044 my $url = "";
2045 if ($git_avatar eq 'gravatar') {
2046 $url = gravatar_url($email, $size);
2047 } elsif ($git_avatar eq 'picon') {
2048 $url = picon_url($email);
2050 # Other providers can be added by extending the if chain, defining $url
2051 # as needed. If no variant puts something in $url, we assume avatars
2052 # are completely disabled/unavailable.
2053 if ($url) {
2054 return $pre_white .
2055 "<img width=\"$size\" " .
2056 "class=\"avatar\" " .
2057 "src=\"$url\" " .
2058 "alt=\"\" " .
2059 "/>" . $post_white;
2060 } else {
2061 return "";
2065 sub format_search_author {
2066 my ($author, $searchtype, $displaytext) = @_;
2067 my $have_search = gitweb_check_feature('search');
2069 if ($have_search) {
2070 my $performed = "";
2071 if ($searchtype eq 'author') {
2072 $performed = "authored";
2073 } elsif ($searchtype eq 'committer') {
2074 $performed = "committed";
2077 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2078 searchtext=>$author,
2079 searchtype=>$searchtype), class=>"list",
2080 title=>"Search for commits $performed by $author"},
2081 $displaytext);
2083 } else {
2084 return $displaytext;
2088 # format the author name of the given commit with the given tag
2089 # the author name is chopped and escaped according to the other
2090 # optional parameters (see chop_str).
2091 sub format_author_html {
2092 my $tag = shift;
2093 my $co = shift;
2094 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2095 return "<$tag class=\"author\">" .
2096 format_search_author($co->{'author_name'}, "author",
2097 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2098 $author) .
2099 "</$tag>";
2102 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2103 sub format_git_diff_header_line {
2104 my $line = shift;
2105 my $diffinfo = shift;
2106 my ($from, $to) = @_;
2108 if ($diffinfo->{'nparents'}) {
2109 # combined diff
2110 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2111 if ($to->{'href'}) {
2112 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2113 esc_path($to->{'file'}));
2114 } else { # file was deleted (no href)
2115 $line .= esc_path($to->{'file'});
2117 } else {
2118 # "ordinary" diff
2119 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2120 if ($from->{'href'}) {
2121 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2122 'a/' . esc_path($from->{'file'}));
2123 } else { # file was added (no href)
2124 $line .= 'a/' . esc_path($from->{'file'});
2126 $line .= ' ';
2127 if ($to->{'href'}) {
2128 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2129 'b/' . esc_path($to->{'file'}));
2130 } else { # file was deleted
2131 $line .= 'b/' . esc_path($to->{'file'});
2135 return "<div class=\"diff header\">$line</div>\n";
2138 # format extended diff header line, before patch itself
2139 sub format_extended_diff_header_line {
2140 my $line = shift;
2141 my $diffinfo = shift;
2142 my ($from, $to) = @_;
2144 # match <path>
2145 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2146 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2147 esc_path($from->{'file'}));
2149 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2150 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2151 esc_path($to->{'file'}));
2153 # match single <mode>
2154 if ($line =~ m/\s(\d{6})$/) {
2155 $line .= '<span class="info"> (' .
2156 file_type_long($1) .
2157 ')</span>';
2159 # match <hash>
2160 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2161 # can match only for combined diff
2162 $line = 'index ';
2163 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2164 if ($from->{'href'}[$i]) {
2165 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2166 -class=>"hash"},
2167 substr($diffinfo->{'from_id'}[$i],0,7));
2168 } else {
2169 $line .= '0' x 7;
2171 # separator
2172 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2174 $line .= '..';
2175 if ($to->{'href'}) {
2176 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2177 substr($diffinfo->{'to_id'},0,7));
2178 } else {
2179 $line .= '0' x 7;
2182 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2183 # can match only for ordinary diff
2184 my ($from_link, $to_link);
2185 if ($from->{'href'}) {
2186 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2187 substr($diffinfo->{'from_id'},0,7));
2188 } else {
2189 $from_link = '0' x 7;
2191 if ($to->{'href'}) {
2192 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2193 substr($diffinfo->{'to_id'},0,7));
2194 } else {
2195 $to_link = '0' x 7;
2197 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2198 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2201 return $line . "<br/>\n";
2204 # format from-file/to-file diff header
2205 sub format_diff_from_to_header {
2206 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2207 my $line;
2208 my $result = '';
2210 $line = $from_line;
2211 #assert($line =~ m/^---/) if DEBUG;
2212 # no extra formatting for "^--- /dev/null"
2213 if (! $diffinfo->{'nparents'}) {
2214 # ordinary (single parent) diff
2215 if ($line =~ m!^--- "?a/!) {
2216 if ($from->{'href'}) {
2217 $line = '--- a/' .
2218 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2219 esc_path($from->{'file'}));
2220 } else {
2221 $line = '--- a/' .
2222 esc_path($from->{'file'});
2225 $result .= qq!<div class="diff from_file">$line</div>\n!;
2227 } else {
2228 # combined diff (merge commit)
2229 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2230 if ($from->{'href'}[$i]) {
2231 $line = '--- ' .
2232 $cgi->a({-href=>href(action=>"blobdiff",
2233 hash_parent=>$diffinfo->{'from_id'}[$i],
2234 hash_parent_base=>$parents[$i],
2235 file_parent=>$from->{'file'}[$i],
2236 hash=>$diffinfo->{'to_id'},
2237 hash_base=>$hash,
2238 file_name=>$to->{'file'}),
2239 -class=>"path",
2240 -title=>"diff" . ($i+1)},
2241 $i+1) .
2242 '/' .
2243 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2244 esc_path($from->{'file'}[$i]));
2245 } else {
2246 $line = '--- /dev/null';
2248 $result .= qq!<div class="diff from_file">$line</div>\n!;
2252 $line = $to_line;
2253 #assert($line =~ m/^\+\+\+/) if DEBUG;
2254 # no extra formatting for "^+++ /dev/null"
2255 if ($line =~ m!^\+\+\+ "?b/!) {
2256 if ($to->{'href'}) {
2257 $line = '+++ b/' .
2258 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2259 esc_path($to->{'file'}));
2260 } else {
2261 $line = '+++ b/' .
2262 esc_path($to->{'file'});
2265 $result .= qq!<div class="diff to_file">$line</div>\n!;
2267 return $result;
2270 # create note for patch simplified by combined diff
2271 sub format_diff_cc_simplified {
2272 my ($diffinfo, @parents) = @_;
2273 my $result = '';
2275 $result .= "<div class=\"diff header\">" .
2276 "diff --cc ";
2277 if (!is_deleted($diffinfo)) {
2278 $result .= $cgi->a({-href => href(action=>"blob",
2279 hash_base=>$hash,
2280 hash=>$diffinfo->{'to_id'},
2281 file_name=>$diffinfo->{'to_file'}),
2282 -class => "path"},
2283 esc_path($diffinfo->{'to_file'}));
2284 } else {
2285 $result .= esc_path($diffinfo->{'to_file'});
2287 $result .= "</div>\n" . # class="diff header"
2288 "<div class=\"diff nodifferences\">" .
2289 "Simple merge" .
2290 "</div>\n"; # class="diff nodifferences"
2292 return $result;
2295 # format patch (diff) line (not to be used for diff headers)
2296 sub format_diff_line {
2297 my $line = shift;
2298 my ($from, $to) = @_;
2299 my $diff_class = "";
2301 chomp $line;
2303 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2304 # combined diff
2305 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2306 if ($line =~ m/^\@{3}/) {
2307 $diff_class = " chunk_header";
2308 } elsif ($line =~ m/^\\/) {
2309 $diff_class = " incomplete";
2310 } elsif ($prefix =~ tr/+/+/) {
2311 $diff_class = " add";
2312 } elsif ($prefix =~ tr/-/-/) {
2313 $diff_class = " rem";
2315 } else {
2316 # assume ordinary diff
2317 my $char = substr($line, 0, 1);
2318 if ($char eq '+') {
2319 $diff_class = " add";
2320 } elsif ($char eq '-') {
2321 $diff_class = " rem";
2322 } elsif ($char eq '@') {
2323 $diff_class = " chunk_header";
2324 } elsif ($char eq "\\") {
2325 $diff_class = " incomplete";
2328 $line = untabify($line);
2329 if ($from && $to && $line =~ m/^\@{2} /) {
2330 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2331 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2333 $from_lines = 0 unless defined $from_lines;
2334 $to_lines = 0 unless defined $to_lines;
2336 if ($from->{'href'}) {
2337 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2338 -class=>"list"}, $from_text);
2340 if ($to->{'href'}) {
2341 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2342 -class=>"list"}, $to_text);
2344 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2345 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2346 return "<div class=\"diff$diff_class\">$line</div>\n";
2347 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2348 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2349 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2351 @from_text = split(' ', $ranges);
2352 for (my $i = 0; $i < @from_text; ++$i) {
2353 ($from_start[$i], $from_nlines[$i]) =
2354 (split(',', substr($from_text[$i], 1)), 0);
2357 $to_text = pop @from_text;
2358 $to_start = pop @from_start;
2359 $to_nlines = pop @from_nlines;
2361 $line = "<span class=\"chunk_info\">$prefix ";
2362 for (my $i = 0; $i < @from_text; ++$i) {
2363 if ($from->{'href'}[$i]) {
2364 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2365 -class=>"list"}, $from_text[$i]);
2366 } else {
2367 $line .= $from_text[$i];
2369 $line .= " ";
2371 if ($to->{'href'}) {
2372 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2373 -class=>"list"}, $to_text);
2374 } else {
2375 $line .= $to_text;
2377 $line .= " $prefix</span>" .
2378 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2379 return "<div class=\"diff$diff_class\">$line</div>\n";
2381 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2384 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2385 # linked. Pass the hash of the tree/commit to snapshot.
2386 sub format_snapshot_links {
2387 my ($hash) = @_;
2388 my $num_fmts = @snapshot_fmts;
2389 if ($num_fmts > 1) {
2390 # A parenthesized list of links bearing format names.
2391 # e.g. "snapshot (_tar.gz_ _zip_)"
2392 return "snapshot (" . join(' ', map
2393 $cgi->a({
2394 -href => href(
2395 action=>"snapshot",
2396 hash=>$hash,
2397 snapshot_format=>$_
2399 }, $known_snapshot_formats{$_}{'display'})
2400 , @snapshot_fmts) . ")";
2401 } elsif ($num_fmts == 1) {
2402 # A single "snapshot" link whose tooltip bears the format name.
2403 # i.e. "_snapshot_"
2404 my ($fmt) = @snapshot_fmts;
2405 return
2406 $cgi->a({
2407 -href => href(
2408 action=>"snapshot",
2409 hash=>$hash,
2410 snapshot_format=>$fmt
2412 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2413 }, "snapshot");
2414 } else { # $num_fmts == 0
2415 return undef;
2419 ## ......................................................................
2420 ## functions returning values to be passed, perhaps after some
2421 ## transformation, to other functions; e.g. returning arguments to href()
2423 # returns hash to be passed to href to generate gitweb URL
2424 # in -title key it returns description of link
2425 sub get_feed_info {
2426 my $format = shift || 'Atom';
2427 my %res = (action => lc($format));
2429 # feed links are possible only for project views
2430 return unless (defined $project);
2431 # some views should link to OPML, or to generic project feed,
2432 # or don't have specific feed yet (so they should use generic)
2433 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2435 my $branch;
2436 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2437 # from tag links; this also makes possible to detect branch links
2438 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2439 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2440 $branch = $1;
2442 # find log type for feed description (title)
2443 my $type = 'log';
2444 if (defined $file_name) {
2445 $type = "history of $file_name";
2446 $type .= "/" if ($action eq 'tree');
2447 $type .= " on '$branch'" if (defined $branch);
2448 } else {
2449 $type = "log of $branch" if (defined $branch);
2452 $res{-title} = $type;
2453 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2454 $res{'file_name'} = $file_name;
2456 return %res;
2459 ## ----------------------------------------------------------------------
2460 ## git utility subroutines, invoking git commands
2462 # returns path to the core git executable and the --git-dir parameter as list
2463 sub git_cmd {
2464 $number_of_git_cmds++;
2465 return $GIT, '--git-dir='.$git_dir;
2468 # quote the given arguments for passing them to the shell
2469 # quote_command("command", "arg 1", "arg with ' and ! characters")
2470 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2471 # Try to avoid using this function wherever possible.
2472 sub quote_command {
2473 return join(' ',
2474 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2477 # get HEAD ref of given project as hash
2478 sub git_get_head_hash {
2479 return git_get_full_hash(shift, 'HEAD');
2482 sub git_get_full_hash {
2483 return git_get_hash(@_);
2486 sub git_get_short_hash {
2487 return git_get_hash(@_, '--short=7');
2490 sub git_get_hash {
2491 my ($project, $hash, @options) = @_;
2492 my $o_git_dir = $git_dir;
2493 my $retval = undef;
2494 $git_dir = "$projectroot/$project";
2495 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2496 '--verify', '-q', @options, $hash) {
2497 $retval = <$fd>;
2498 chomp $retval if defined $retval;
2499 close $fd;
2501 if (defined $o_git_dir) {
2502 $git_dir = $o_git_dir;
2504 return $retval;
2507 # get type of given object
2508 sub git_get_type {
2509 my $hash = shift;
2511 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2512 my $type = <$fd>;
2513 close $fd or return;
2514 chomp $type;
2515 return $type;
2518 # repository configuration
2519 our $config_file = '';
2520 our %config;
2522 # store multiple values for single key as anonymous array reference
2523 # single values stored directly in the hash, not as [ <value> ]
2524 sub hash_set_multi {
2525 my ($hash, $key, $value) = @_;
2527 if (!exists $hash->{$key}) {
2528 $hash->{$key} = $value;
2529 } elsif (!ref $hash->{$key}) {
2530 $hash->{$key} = [ $hash->{$key}, $value ];
2531 } else {
2532 push @{$hash->{$key}}, $value;
2536 # return hash of git project configuration
2537 # optionally limited to some section, e.g. 'gitweb'
2538 sub git_parse_project_config {
2539 my $section_regexp = shift;
2540 my %config;
2542 local $/ = "\0";
2544 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2545 or return;
2547 while (my $keyval = <$fh>) {
2548 chomp $keyval;
2549 my ($key, $value) = split(/\n/, $keyval, 2);
2551 hash_set_multi(\%config, $key, $value)
2552 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2554 close $fh;
2556 return %config;
2559 # convert config value to boolean: 'true' or 'false'
2560 # no value, number > 0, 'true' and 'yes' values are true
2561 # rest of values are treated as false (never as error)
2562 sub config_to_bool {
2563 my $val = shift;
2565 return 1 if !defined $val; # section.key
2567 # strip leading and trailing whitespace
2568 $val =~ s/^\s+//;
2569 $val =~ s/\s+$//;
2571 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2572 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2575 # convert config value to simple decimal number
2576 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2577 # to be multiplied by 1024, 1048576, or 1073741824
2578 sub config_to_int {
2579 my $val = shift;
2581 # strip leading and trailing whitespace
2582 $val =~ s/^\s+//;
2583 $val =~ s/\s+$//;
2585 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2586 $unit = lc($unit);
2587 # unknown unit is treated as 1
2588 return $num * ($unit eq 'g' ? 1073741824 :
2589 $unit eq 'm' ? 1048576 :
2590 $unit eq 'k' ? 1024 : 1);
2592 return $val;
2595 # convert config value to array reference, if needed
2596 sub config_to_multi {
2597 my $val = shift;
2599 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2602 sub git_get_project_config {
2603 my ($key, $type) = @_;
2605 return unless defined $git_dir;
2607 # key sanity check
2608 return unless ($key);
2609 $key =~ s/^gitweb\.//;
2610 return if ($key =~ m/\W/);
2612 # type sanity check
2613 if (defined $type) {
2614 $type =~ s/^--//;
2615 $type = undef
2616 unless ($type eq 'bool' || $type eq 'int');
2619 # get config
2620 if (!defined $config_file ||
2621 $config_file ne "$git_dir/config") {
2622 %config = git_parse_project_config('gitweb');
2623 $config_file = "$git_dir/config";
2626 # check if config variable (key) exists
2627 return unless exists $config{"gitweb.$key"};
2629 # ensure given type
2630 if (!defined $type) {
2631 return $config{"gitweb.$key"};
2632 } elsif ($type eq 'bool') {
2633 # backward compatibility: 'git config --bool' returns true/false
2634 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2635 } elsif ($type eq 'int') {
2636 return config_to_int($config{"gitweb.$key"});
2638 return $config{"gitweb.$key"};
2641 # get hash of given path at given ref
2642 sub git_get_hash_by_path {
2643 my $base = shift;
2644 my $path = shift || return undef;
2645 my $type = shift;
2647 $path =~ s,/+$,,;
2649 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2650 or die_error(500, "Open git-ls-tree failed");
2651 my $line = <$fd>;
2652 close $fd or return undef;
2654 if (!defined $line) {
2655 # there is no tree or hash given by $path at $base
2656 return undef;
2659 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2660 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2661 if (defined $type && $type ne $2) {
2662 # type doesn't match
2663 return undef;
2665 return $3;
2668 # get path of entry with given hash at given tree-ish (ref)
2669 # used to get 'from' filename for combined diff (merge commit) for renames
2670 sub git_get_path_by_hash {
2671 my $base = shift || return;
2672 my $hash = shift || return;
2674 local $/ = "\0";
2676 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2677 or return undef;
2678 while (my $line = <$fd>) {
2679 chomp $line;
2681 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2682 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2683 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2684 close $fd;
2685 return $1;
2688 close $fd;
2689 return undef;
2692 ## ......................................................................
2693 ## git utility functions, directly accessing git repository
2695 sub git_get_project_description {
2696 my $path = shift;
2698 $git_dir = "$projectroot/$path";
2699 open my $fd, '<', "$git_dir/description"
2700 or return git_get_project_config('description');
2701 my $descr = <$fd>;
2702 close $fd;
2703 if (defined $descr) {
2704 chomp $descr;
2706 return $descr;
2709 sub git_get_project_ctags {
2710 my $path = shift;
2711 my $ctags = {};
2713 $git_dir = "$projectroot/$path";
2714 opendir my $dh, "$git_dir/ctags"
2715 or return $ctags;
2716 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2717 open my $ct, '<', $_ or next;
2718 my $val = <$ct>;
2719 chomp $val;
2720 close $ct;
2721 my $ctag = $_; $ctag =~ s#.*/##;
2722 $ctags->{$ctag} = $val;
2724 closedir $dh;
2725 $ctags;
2728 sub git_populate_project_tagcloud {
2729 my $ctags = shift;
2731 # First, merge different-cased tags; tags vote on casing
2732 my %ctags_lc;
2733 foreach (keys %$ctags) {
2734 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2735 if (not $ctags_lc{lc $_}->{topcount}
2736 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2737 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2738 $ctags_lc{lc $_}->{topname} = $_;
2742 my $cloud;
2743 if (eval { require HTML::TagCloud; 1; }) {
2744 $cloud = HTML::TagCloud->new;
2745 foreach (sort keys %ctags_lc) {
2746 # Pad the title with spaces so that the cloud looks
2747 # less crammed.
2748 my $title = $ctags_lc{$_}->{topname};
2749 $title =~ s/ /&nbsp;/g;
2750 $title =~ s/^/&nbsp;/g;
2751 $title =~ s/$/&nbsp;/g;
2752 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2754 } else {
2755 $cloud = \%ctags_lc;
2757 $cloud;
2760 sub git_show_project_tagcloud {
2761 my ($cloud, $count) = @_;
2762 print STDERR ref($cloud)."..\n";
2763 if (ref $cloud eq 'HTML::TagCloud') {
2764 return $cloud->html_and_css($count);
2765 } else {
2766 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2767 return '<p align="center">' . join (', ', map {
2768 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2769 } splice(@tags, 0, $count)) . '</p>';
2773 sub git_get_project_url_list {
2774 my $path = shift;
2776 $git_dir = "$projectroot/$path";
2777 open my $fd, '<', "$git_dir/cloneurl"
2778 or return wantarray ?
2779 @{ config_to_multi(git_get_project_config('url')) } :
2780 config_to_multi(git_get_project_config('url'));
2781 my @git_project_url_list = map { chomp; $_ } <$fd>;
2782 close $fd;
2784 return wantarray ? @git_project_url_list : \@git_project_url_list;
2787 sub git_get_projects_list {
2788 my ($filter) = @_;
2789 my @list;
2791 $filter ||= '';
2792 $filter =~ s/\.git$//;
2794 my $check_forks = gitweb_check_feature('forks');
2796 if (-d $projects_list) {
2797 # search in directory
2798 my $dir = $projects_list . ($filter ? "/$filter" : '');
2799 # remove the trailing "/"
2800 $dir =~ s!/+$!!;
2801 my $pfxlen = length("$dir");
2802 my $pfxdepth = ($dir =~ tr!/!!);
2804 File::Find::find({
2805 follow_fast => 1, # follow symbolic links
2806 follow_skip => 2, # ignore duplicates
2807 dangling_symlinks => 0, # ignore dangling symlinks, silently
2808 wanted => sub {
2809 # global variables
2810 our $project_maxdepth;
2811 our $projectroot;
2812 # skip project-list toplevel, if we get it.
2813 return if (m!^[/.]$!);
2814 # only directories can be git repositories
2815 return unless (-d $_);
2816 # don't traverse too deep (Find is super slow on os x)
2817 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2818 $File::Find::prune = 1;
2819 return;
2822 my $subdir = substr($File::Find::name, $pfxlen + 1);
2823 # we check related file in $projectroot
2824 my $path = ($filter ? "$filter/" : '') . $subdir;
2825 if (check_export_ok("$projectroot/$path")) {
2826 push @list, { path => $path };
2827 $File::Find::prune = 1;
2830 }, "$dir");
2832 } elsif (-f $projects_list) {
2833 # read from file(url-encoded):
2834 # 'git%2Fgit.git Linus+Torvalds'
2835 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2836 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2837 my %paths;
2838 open my $fd, '<', $projects_list or return;
2839 PROJECT:
2840 while (my $line = <$fd>) {
2841 chomp $line;
2842 my ($path, $owner) = split ' ', $line;
2843 $path = unescape($path);
2844 $owner = unescape($owner);
2845 if (!defined $path) {
2846 next;
2848 if ($filter ne '') {
2849 # looking for forks;
2850 my $pfx = substr($path, 0, length($filter));
2851 if ($pfx ne $filter) {
2852 next PROJECT;
2854 my $sfx = substr($path, length($filter));
2855 if ($sfx !~ /^\/.*\.git$/) {
2856 next PROJECT;
2858 } elsif ($check_forks) {
2859 PATH:
2860 foreach my $filter (keys %paths) {
2861 # looking for forks;
2862 my $pfx = substr($path, 0, length($filter));
2863 if ($pfx ne $filter) {
2864 next PATH;
2866 my $sfx = substr($path, length($filter));
2867 if ($sfx !~ /^\/.*\.git$/) {
2868 next PATH;
2870 # is a fork, don't include it in
2871 # the list
2872 next PROJECT;
2875 if (check_export_ok("$projectroot/$path")) {
2876 my $pr = {
2877 path => $path,
2878 owner => to_utf8($owner),
2880 push @list, $pr;
2881 (my $forks_path = $path) =~ s/\.git$//;
2882 $paths{$forks_path}++;
2885 close $fd;
2887 return @list;
2890 our $gitweb_project_owner = undef;
2891 sub git_get_project_list_from_file {
2893 return if (defined $gitweb_project_owner);
2895 $gitweb_project_owner = {};
2896 # read from file (url-encoded):
2897 # 'git%2Fgit.git Linus+Torvalds'
2898 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2899 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2900 if (-f $projects_list) {
2901 open(my $fd, '<', $projects_list);
2902 while (my $line = <$fd>) {
2903 chomp $line;
2904 my ($pr, $ow) = split ' ', $line;
2905 $pr = unescape($pr);
2906 $ow = unescape($ow);
2907 $gitweb_project_owner->{$pr} = to_utf8($ow);
2909 close $fd;
2913 sub git_get_project_owner {
2914 my $project = shift;
2915 my $owner;
2917 return undef unless $project;
2918 $git_dir = "$projectroot/$project";
2920 if (!defined $gitweb_project_owner) {
2921 git_get_project_list_from_file();
2924 if (exists $gitweb_project_owner->{$project}) {
2925 $owner = $gitweb_project_owner->{$project};
2927 if (!defined $owner){
2928 $owner = git_get_project_config('owner');
2930 if (!defined $owner) {
2931 $owner = get_file_owner("$git_dir");
2934 return $owner;
2937 sub git_get_last_activity {
2938 my ($path) = @_;
2939 my $fd;
2941 $git_dir = "$projectroot/$path";
2942 open($fd, "-|", git_cmd(), 'for-each-ref',
2943 '--format=%(committer)',
2944 '--sort=-committerdate',
2945 '--count=1',
2946 'refs/heads') or return;
2947 my $most_recent = <$fd>;
2948 close $fd or return;
2949 if (defined $most_recent &&
2950 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2951 my $timestamp = $1;
2952 my $age = time - $timestamp;
2953 return ($age, age_string($age));
2955 return (undef, undef);
2958 sub git_get_references {
2959 my $type = shift || "";
2960 my %refs;
2961 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2962 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2963 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2964 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2965 or return;
2967 while (my $line = <$fd>) {
2968 chomp $line;
2969 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2970 if (defined $refs{$1}) {
2971 push @{$refs{$1}}, $2;
2972 } else {
2973 $refs{$1} = [ $2 ];
2977 close $fd or return;
2978 return \%refs;
2981 sub git_get_rev_name_tags {
2982 my $hash = shift || return undef;
2984 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2985 or return;
2986 my $name_rev = <$fd>;
2987 close $fd;
2989 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2990 return $1;
2991 } else {
2992 # catches also '$hash undefined' output
2993 return undef;
2997 ## ----------------------------------------------------------------------
2998 ## parse to hash functions
3000 sub parse_date {
3001 my $epoch = shift;
3002 my $tz = shift || "-0000";
3004 my %date;
3005 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3006 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3007 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3008 $date{'hour'} = $hour;
3009 $date{'minute'} = $min;
3010 $date{'mday'} = $mday;
3011 $date{'day'} = $days[$wday];
3012 $date{'month'} = $months[$mon];
3013 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3014 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3015 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3016 $mday, $months[$mon], $hour ,$min;
3017 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3018 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3020 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
3021 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
3022 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3023 $date{'hour_local'} = $hour;
3024 $date{'minute_local'} = $min;
3025 $date{'tz_local'} = $tz;
3026 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3027 1900+$year, $mon+1, $mday,
3028 $hour, $min, $sec, $tz);
3029 return %date;
3032 sub parse_tag {
3033 my $tag_id = shift;
3034 my %tag;
3035 my @comment;
3037 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3038 $tag{'id'} = $tag_id;
3039 while (my $line = <$fd>) {
3040 chomp $line;
3041 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3042 $tag{'object'} = $1;
3043 } elsif ($line =~ m/^type (.+)$/) {
3044 $tag{'type'} = $1;
3045 } elsif ($line =~ m/^tag (.+)$/) {
3046 $tag{'name'} = $1;
3047 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3048 $tag{'author'} = $1;
3049 $tag{'author_epoch'} = $2;
3050 $tag{'author_tz'} = $3;
3051 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3052 $tag{'author_name'} = $1;
3053 $tag{'author_email'} = $2;
3054 } else {
3055 $tag{'author_name'} = $tag{'author'};
3057 } elsif ($line =~ m/--BEGIN/) {
3058 push @comment, $line;
3059 last;
3060 } elsif ($line eq "") {
3061 last;
3064 push @comment, <$fd>;
3065 $tag{'comment'} = \@comment;
3066 close $fd or return;
3067 if (!defined $tag{'name'}) {
3068 return
3070 return %tag
3073 sub parse_commit_text {
3074 my ($commit_text, $withparents) = @_;
3075 my @commit_lines = split '\n', $commit_text;
3076 my %co;
3078 pop @commit_lines; # Remove '\0'
3080 if (! @commit_lines) {
3081 return;
3084 my $header = shift @commit_lines;
3085 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3086 return;
3088 ($co{'id'}, my @parents) = split ' ', $header;
3089 while (my $line = shift @commit_lines) {
3090 last if $line eq "\n";
3091 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3092 $co{'tree'} = $1;
3093 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3094 push @parents, $1;
3095 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3096 $co{'author'} = to_utf8($1);
3097 $co{'author_epoch'} = $2;
3098 $co{'author_tz'} = $3;
3099 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3100 $co{'author_name'} = $1;
3101 $co{'author_email'} = $2;
3102 } else {
3103 $co{'author_name'} = $co{'author'};
3105 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3106 $co{'committer'} = to_utf8($1);
3107 $co{'committer_epoch'} = $2;
3108 $co{'committer_tz'} = $3;
3109 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3110 $co{'committer_name'} = $1;
3111 $co{'committer_email'} = $2;
3112 } else {
3113 $co{'committer_name'} = $co{'committer'};
3117 if (!defined $co{'tree'}) {
3118 return;
3120 $co{'parents'} = \@parents;
3121 $co{'parent'} = $parents[0];
3123 foreach my $title (@commit_lines) {
3124 $title =~ s/^ //;
3125 if ($title ne "") {
3126 $co{'title'} = chop_str($title, 80, 5);
3127 # remove leading stuff of merges to make the interesting part visible
3128 if (length($title) > 50) {
3129 $title =~ s/^Automatic //;
3130 $title =~ s/^merge (of|with) /Merge ... /i;
3131 if (length($title) > 50) {
3132 $title =~ s/(http|rsync):\/\///;
3134 if (length($title) > 50) {
3135 $title =~ s/(master|www|rsync)\.//;
3137 if (length($title) > 50) {
3138 $title =~ s/kernel.org:?//;
3140 if (length($title) > 50) {
3141 $title =~ s/\/pub\/scm//;
3144 $co{'title_short'} = chop_str($title, 50, 5);
3145 last;
3148 if (! defined $co{'title'} || $co{'title'} eq "") {
3149 $co{'title'} = $co{'title_short'} = '(no commit message)';
3151 # remove added spaces
3152 foreach my $line (@commit_lines) {
3153 $line =~ s/^ //;
3155 $co{'comment'} = \@commit_lines;
3157 my $age = time - $co{'committer_epoch'};
3158 $co{'age'} = $age;
3159 $co{'age_string'} = age_string($age);
3160 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3161 if ($age > 60*60*24*7*2) {
3162 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3163 $co{'age_string_age'} = $co{'age_string'};
3164 } else {
3165 $co{'age_string_date'} = $co{'age_string'};
3166 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3168 return %co;
3171 sub parse_commit {
3172 my ($commit_id) = @_;
3173 my %co;
3175 local $/ = "\0";
3177 open my $fd, "-|", git_cmd(), "rev-list",
3178 "--parents",
3179 "--header",
3180 "--max-count=1",
3181 $commit_id,
3182 "--",
3183 or die_error(500, "Open git-rev-list failed");
3184 %co = parse_commit_text(<$fd>, 1);
3185 close $fd;
3187 return %co;
3190 sub parse_commits {
3191 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3192 my @cos;
3194 $maxcount ||= 1;
3195 $skip ||= 0;
3197 local $/ = "\0";
3199 open my $fd, "-|", git_cmd(), "rev-list",
3200 "--header",
3201 @args,
3202 ("--max-count=" . $maxcount),
3203 ("--skip=" . $skip),
3204 @extra_options,
3205 $commit_id,
3206 "--",
3207 ($filename ? ($filename) : ())
3208 or die_error(500, "Open git-rev-list failed");
3209 while (my $line = <$fd>) {
3210 my %co = parse_commit_text($line);
3211 push @cos, \%co;
3213 close $fd;
3215 return wantarray ? @cos : \@cos;
3218 # parse line of git-diff-tree "raw" output
3219 sub parse_difftree_raw_line {
3220 my $line = shift;
3221 my %res;
3223 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3224 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3225 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3226 $res{'from_mode'} = $1;
3227 $res{'to_mode'} = $2;
3228 $res{'from_id'} = $3;
3229 $res{'to_id'} = $4;
3230 $res{'status'} = $5;
3231 $res{'similarity'} = $6;
3232 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3233 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3234 } else {
3235 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3238 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3239 # combined diff (for merge commit)
3240 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3241 $res{'nparents'} = length($1);
3242 $res{'from_mode'} = [ split(' ', $2) ];
3243 $res{'to_mode'} = pop @{$res{'from_mode'}};
3244 $res{'from_id'} = [ split(' ', $3) ];
3245 $res{'to_id'} = pop @{$res{'from_id'}};
3246 $res{'status'} = [ split('', $4) ];
3247 $res{'to_file'} = unquote($5);
3249 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3250 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3251 $res{'commit'} = $1;
3254 return wantarray ? %res : \%res;
3257 # wrapper: return parsed line of git-diff-tree "raw" output
3258 # (the argument might be raw line, or parsed info)
3259 sub parsed_difftree_line {
3260 my $line_or_ref = shift;
3262 if (ref($line_or_ref) eq "HASH") {
3263 # pre-parsed (or generated by hand)
3264 return $line_or_ref;
3265 } else {
3266 return parse_difftree_raw_line($line_or_ref);
3270 # parse line of git-ls-tree output
3271 sub parse_ls_tree_line {
3272 my $line = shift;
3273 my %opts = @_;
3274 my %res;
3276 if ($opts{'-l'}) {
3277 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3278 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3280 $res{'mode'} = $1;
3281 $res{'type'} = $2;
3282 $res{'hash'} = $3;
3283 $res{'size'} = $4;
3284 if ($opts{'-z'}) {
3285 $res{'name'} = $5;
3286 } else {
3287 $res{'name'} = unquote($5);
3289 } else {
3290 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3291 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3293 $res{'mode'} = $1;
3294 $res{'type'} = $2;
3295 $res{'hash'} = $3;
3296 if ($opts{'-z'}) {
3297 $res{'name'} = $4;
3298 } else {
3299 $res{'name'} = unquote($4);
3303 return wantarray ? %res : \%res;
3306 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3307 sub parse_from_to_diffinfo {
3308 my ($diffinfo, $from, $to, @parents) = @_;
3310 if ($diffinfo->{'nparents'}) {
3311 # combined diff
3312 $from->{'file'} = [];
3313 $from->{'href'} = [];
3314 fill_from_file_info($diffinfo, @parents)
3315 unless exists $diffinfo->{'from_file'};
3316 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3317 $from->{'file'}[$i] =
3318 defined $diffinfo->{'from_file'}[$i] ?
3319 $diffinfo->{'from_file'}[$i] :
3320 $diffinfo->{'to_file'};
3321 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3322 $from->{'href'}[$i] = href(action=>"blob",
3323 hash_base=>$parents[$i],
3324 hash=>$diffinfo->{'from_id'}[$i],
3325 file_name=>$from->{'file'}[$i]);
3326 } else {
3327 $from->{'href'}[$i] = undef;
3330 } else {
3331 # ordinary (not combined) diff
3332 $from->{'file'} = $diffinfo->{'from_file'};
3333 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3334 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3335 hash=>$diffinfo->{'from_id'},
3336 file_name=>$from->{'file'});
3337 } else {
3338 delete $from->{'href'};
3342 $to->{'file'} = $diffinfo->{'to_file'};
3343 if (!is_deleted($diffinfo)) { # file exists in result
3344 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3345 hash=>$diffinfo->{'to_id'},
3346 file_name=>$to->{'file'});
3347 } else {
3348 delete $to->{'href'};
3352 ## ......................................................................
3353 ## parse to array of hashes functions
3355 sub git_get_heads_list {
3356 my $limit = shift;
3357 my @headslist;
3359 open my $fd, '-|', git_cmd(), 'for-each-ref',
3360 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3361 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3362 'refs/heads'
3363 or return;
3364 while (my $line = <$fd>) {
3365 my %ref_item;
3367 chomp $line;
3368 my ($refinfo, $committerinfo) = split(/\0/, $line);
3369 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3370 my ($committer, $epoch, $tz) =
3371 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3372 $ref_item{'fullname'} = $name;
3373 $name =~ s!^refs/heads/!!;
3375 $ref_item{'name'} = $name;
3376 $ref_item{'id'} = $hash;
3377 $ref_item{'title'} = $title || '(no commit message)';
3378 $ref_item{'epoch'} = $epoch;
3379 if ($epoch) {
3380 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3381 } else {
3382 $ref_item{'age'} = "unknown";
3385 push @headslist, \%ref_item;
3387 close $fd;
3389 return wantarray ? @headslist : \@headslist;
3392 sub git_get_tags_list {
3393 my $limit = shift;
3394 my @tagslist;
3396 open my $fd, '-|', git_cmd(), 'for-each-ref',
3397 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3398 '--format=%(objectname) %(objecttype) %(refname) '.
3399 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3400 'refs/tags'
3401 or return;
3402 while (my $line = <$fd>) {
3403 my %ref_item;
3405 chomp $line;
3406 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3407 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3408 my ($creator, $epoch, $tz) =
3409 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3410 $ref_item{'fullname'} = $name;
3411 $name =~ s!^refs/tags/!!;
3413 $ref_item{'type'} = $type;
3414 $ref_item{'id'} = $id;
3415 $ref_item{'name'} = $name;
3416 if ($type eq "tag") {
3417 $ref_item{'subject'} = $title;
3418 $ref_item{'reftype'} = $reftype;
3419 $ref_item{'refid'} = $refid;
3420 } else {
3421 $ref_item{'reftype'} = $type;
3422 $ref_item{'refid'} = $id;
3425 if ($type eq "tag" || $type eq "commit") {
3426 $ref_item{'epoch'} = $epoch;
3427 if ($epoch) {
3428 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3429 } else {
3430 $ref_item{'age'} = "unknown";
3434 push @tagslist, \%ref_item;
3436 close $fd;
3438 return wantarray ? @tagslist : \@tagslist;
3441 ## ----------------------------------------------------------------------
3442 ## filesystem-related functions
3444 sub get_file_owner {
3445 my $path = shift;
3447 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3448 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3449 if (!defined $gcos) {
3450 return undef;
3452 my $owner = $gcos;
3453 $owner =~ s/[,;].*$//;
3454 return to_utf8($owner);
3457 # assume that file exists
3458 sub insert_file {
3459 my $filename = shift;
3461 open my $fd, '<', $filename;
3462 print map { to_utf8($_) } <$fd>;
3463 close $fd;
3466 ## ......................................................................
3467 ## mimetype related functions
3469 sub mimetype_guess_file {
3470 my $filename = shift;
3471 my $mimemap = shift;
3472 -r $mimemap or return undef;
3474 my %mimemap;
3475 open(my $mh, '<', $mimemap) or return undef;
3476 while (<$mh>) {
3477 next if m/^#/; # skip comments
3478 my ($mimetype, $exts) = split(/\t+/);
3479 if (defined $exts) {
3480 my @exts = split(/\s+/, $exts);
3481 foreach my $ext (@exts) {
3482 $mimemap{$ext} = $mimetype;
3486 close($mh);
3488 $filename =~ /\.([^.]*)$/;
3489 return $mimemap{$1};
3492 sub mimetype_guess {
3493 my $filename = shift;
3494 my $mime;
3495 $filename =~ /\./ or return undef;
3497 if ($mimetypes_file) {
3498 my $file = $mimetypes_file;
3499 if ($file !~ m!^/!) { # if it is relative path
3500 # it is relative to project
3501 $file = "$projectroot/$project/$file";
3503 $mime = mimetype_guess_file($filename, $file);
3505 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3506 return $mime;
3509 sub blob_mimetype {
3510 my $fd = shift;
3511 my $filename = shift;
3513 if ($filename) {
3514 my $mime = mimetype_guess($filename);
3515 $mime and return $mime;
3518 # just in case
3519 return $default_blob_plain_mimetype unless $fd;
3521 if (-T $fd) {
3522 return 'text/plain';
3523 } elsif (! $filename) {
3524 return 'application/octet-stream';
3525 } elsif ($filename =~ m/\.png$/i) {
3526 return 'image/png';
3527 } elsif ($filename =~ m/\.gif$/i) {
3528 return 'image/gif';
3529 } elsif ($filename =~ m/\.jpe?g$/i) {
3530 return 'image/jpeg';
3531 } else {
3532 return 'application/octet-stream';
3536 sub blob_contenttype {
3537 my ($fd, $file_name, $type) = @_;
3539 $type ||= blob_mimetype($fd, $file_name);
3540 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3541 $type .= "; charset=$default_text_plain_charset";
3544 return $type;
3547 # guess file syntax for syntax highlighting; return undef if no highlighting
3548 # the name of syntax can (in the future) depend on syntax highlighter used
3549 sub guess_file_syntax {
3550 my ($highlight, $mimetype, $file_name) = @_;
3551 return undef unless ($highlight && defined $file_name);
3552 my $basename = basename($file_name, '.in');
3553 return $highlight_basename{$basename}
3554 if exists $highlight_basename{$basename};
3556 $basename =~ /\.([^.]*)$/;
3557 my $ext = $1 or return undef;
3558 return $highlight_ext{$ext}
3559 if exists $highlight_ext{$ext};
3561 return undef;
3564 # run highlighter and return FD of its output,
3565 # or return original FD if no highlighting
3566 sub run_highlighter {
3567 my ($fd, $highlight, $syntax) = @_;
3568 return $fd unless ($highlight && defined $syntax);
3570 close $fd
3571 or die_error(404, "Reading blob failed");
3572 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3573 quote_command($highlight_bin).
3574 " --xhtml --fragment --syntax $syntax |"
3575 or die_error(500, "Couldn't open file or run syntax highlighter");
3576 return $fd;
3579 ## ======================================================================
3580 ## functions printing HTML: header, footer, error page
3582 sub get_page_title {
3583 my $title = to_utf8($site_name);
3585 return $title unless (defined $project);
3586 $title .= " - " . to_utf8($project);
3588 return $title unless (defined $action);
3589 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3591 return $title unless (defined $file_name);
3592 $title .= " - " . esc_path($file_name);
3593 if ($action eq "tree" && $file_name !~ m|/$|) {
3594 $title .= "/";
3597 return $title;
3600 # creates "Generating..." page when caching enabled and not in cache
3601 sub git_generating_data_html {
3602 my ($cache, $key, $lock_fh) = @_;
3604 # whitelist of actions that should get "Generating..." page
3605 if (!action_outputs_html($action) ||
3606 browser_is_robot()) {
3607 return;
3610 my $title = "[Generating...] " . get_page_title();
3611 # TODO: the following line of code duplicates the one
3612 # in git_header_html, and it should probably be refactored.
3613 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3615 # Use the trick that 'refresh' HTTP header equivalent (set via http-equiv)
3616 # with timeout of 0 seconds would redirect as soon as page is finished.
3617 # It assumes that browser would display partially received page.
3618 # This "Generating..." redirect page should not be cached (externally).
3619 my %no_cache = (
3620 # HTTP/1.0
3621 -Pragma => 'no-cache',
3622 # HTTP/1.1
3623 -Cache_Control => join(', ', qw(private no-cache no-store must-revalidate
3624 max-age=0 pre-check=0 post-check=0)),
3626 print STDOUT $cgi->header(-type => 'text/html', -charset => 'utf-8',
3627 -status=> '200 OK', -expires => 'now',
3628 %no_cache);
3629 print STDOUT <<"EOF";
3630 <?xml version="1.0" encoding="utf-8"?>
3631 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3632 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3633 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3634 <!-- git web interface version $version -->
3635 <!-- git core binaries version $git_version -->
3636 <head>
3637 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
3638 <meta http-equiv="refresh" content="0" />
3639 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version" />
3640 <meta name="robots" content="noindex, nofollow" />
3641 <title>$title</title>
3642 </head>
3643 <body>
3646 local $| = 1; # autoflush
3647 print STDOUT 'Generating...';
3649 my $total_time = 0;
3650 my $interval = $generating_options{'print_interval'} || 1;
3651 my $timeout = $generating_options{'timeout'};
3652 my $alarm_handler = sub {
3653 local $! = 1;
3654 print STDOUT '.';
3655 $total_time += $interval;
3656 if ($total_time > $timeout) {
3657 die "timeout\n";
3660 eval {
3661 local $SIG{ALRM} = $alarm_handler;
3662 Time::HiRes::alarm($interval, $interval);
3663 my $lock_acquired;
3664 do {
3665 # loop is needed here because SIGALRM (from 'alarm')
3666 # can interrupt process of acquiring lock
3667 $lock_acquired = flock($lock_fh, LOCK_SH); # blocking readers lock
3668 } until ($lock_acquired);
3669 alarm 0;
3671 # It doesn't really matter if we got lock, or timed-out
3672 # but we should re-throw unknown (unexpected) errors
3673 die $@ if ($@ and $@ !~ /timeout/);
3675 print STDOUT <<"EOF";
3677 </body>
3678 </html>
3681 # after refresh web browser would reload page and send new request
3682 goto DONE_GITWEB;
3683 #exit 0;
3684 #return;
3687 sub git_header_html {
3688 my $status = shift || "200 OK";
3689 my $expires = shift;
3690 my %opts = @_;
3692 my $title = get_page_title();
3693 my $content_type;
3694 # require explicit support from the UA if we are to send the page as
3695 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3696 # we have to do this because MSIE sometimes globs '*/*', pretending to
3697 # support xhtml+xml but choking when it gets what it asked for.
3698 # Disable content-type negotiation when caching (use mimetype good for all).
3699 if (!$caching_enabled &&
3700 defined $cgi->http('HTTP_ACCEPT') &&
3701 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3702 $cgi->Accept('application/xhtml+xml') != 0) {
3703 $content_type = 'application/xhtml+xml';
3704 } else {
3705 $content_type = 'text/html';
3707 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3708 -status=> $status, -expires => $expires)
3709 unless ($opts{'-no_http_header'});
3710 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3711 print <<EOF;
3712 <?xml version="1.0" encoding="utf-8"?>
3713 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3714 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3715 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3716 <!-- git core binaries version $git_version -->
3717 <head>
3718 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3719 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3720 <meta name="robots" content="index, nofollow"/>
3721 <title>$title</title>
3723 # the stylesheet, favicon etc urls won't work correctly with path_info
3724 # unless we set the appropriate base URL
3725 # if caching is enabled we can get it from cache for path_info when it
3726 # is generated without path_info
3727 if ($ENV{'PATH_INFO'} || $caching_enabled) {
3728 print "<base href=\"".esc_url($base_url)."\" />\n";
3730 # print out each stylesheet that exist, providing backwards capability
3731 # for those people who defined $stylesheet in a config file
3732 if (defined $stylesheet) {
3733 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3734 } else {
3735 foreach my $stylesheet (@stylesheets) {
3736 next unless $stylesheet;
3737 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3740 if (defined $project) {
3741 my %href_params = get_feed_info();
3742 if (!exists $href_params{'-title'}) {
3743 $href_params{'-title'} = 'log';
3746 foreach my $format qw(RSS Atom) {
3747 my $type = lc($format);
3748 my %link_attr = (
3749 '-rel' => 'alternate',
3750 '-title' => "$project - $href_params{'-title'} - $format feed",
3751 '-type' => "application/$type+xml"
3754 $href_params{'action'} = $type;
3755 $link_attr{'-href'} = href(%href_params);
3756 print "<link ".
3757 "rel=\"$link_attr{'-rel'}\" ".
3758 "title=\"$link_attr{'-title'}\" ".
3759 "href=\"$link_attr{'-href'}\" ".
3760 "type=\"$link_attr{'-type'}\" ".
3761 "/>\n";
3763 $href_params{'extra_options'} = '--no-merges';
3764 $link_attr{'-href'} = href(%href_params);
3765 $link_attr{'-title'} .= ' (no merges)';
3766 print "<link ".
3767 "rel=\"$link_attr{'-rel'}\" ".
3768 "title=\"$link_attr{'-title'}\" ".
3769 "href=\"$link_attr{'-href'}\" ".
3770 "type=\"$link_attr{'-type'}\" ".
3771 "/>\n";
3774 } else {
3775 printf('<link rel="alternate" title="%s projects list" '.
3776 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3777 $site_name, href(project=>undef, action=>"project_index"));
3778 printf('<link rel="alternate" title="%s projects feeds" '.
3779 'href="%s" type="text/x-opml" />'."\n",
3780 $site_name, href(project=>undef, action=>"opml"));
3782 if (defined $favicon) {
3783 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3786 print "</head>\n" .
3787 "<body>\n";
3789 if (defined $site_header && -f $site_header) {
3790 insert_file($site_header);
3793 print "<div class=\"page_header\">\n" .
3794 $cgi->a({-href => esc_url($logo_url),
3795 -title => $logo_label},
3796 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3797 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3798 if (defined $project) {
3799 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3800 if (defined $action) {
3801 print " / $action";
3803 print "\n";
3805 print "</div>\n";
3807 my $have_search = gitweb_check_feature('search');
3808 if (defined $project && $have_search) {
3809 if (!defined $searchtext) {
3810 $searchtext = "";
3812 my $search_hash;
3813 if (defined $hash_base) {
3814 $search_hash = $hash_base;
3815 } elsif (defined $hash) {
3816 $search_hash = $hash;
3817 } else {
3818 $search_hash = "HEAD";
3820 my $action = $my_uri;
3821 my $use_pathinfo = gitweb_check_feature('pathinfo');
3822 if ($use_pathinfo) {
3823 $action .= "/".esc_url($project);
3825 print $cgi->startform(-method => "get", -action => $action) .
3826 "<div class=\"search\">\n" .
3827 (!$use_pathinfo &&
3828 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3829 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3830 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3831 $cgi->popup_menu(-name => 'st', -default => 'commit',
3832 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3833 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3834 " search:\n",
3835 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3836 "<span title=\"Extended regular expression\">" .
3837 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3838 -checked => $search_use_regexp) .
3839 "</span>" .
3840 "</div>" .
3841 $cgi->end_form() . "\n";
3845 sub git_footer_html {
3846 my $feed_class = 'rss_logo';
3848 print "<div class=\"page_footer\">\n";
3849 if (defined $project) {
3850 my $descr = git_get_project_description($project);
3851 if (defined $descr) {
3852 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3855 my %href_params = get_feed_info();
3856 if (!%href_params) {
3857 $feed_class .= ' generic';
3859 $href_params{'-title'} ||= 'log';
3861 foreach my $format qw(RSS Atom) {
3862 $href_params{'action'} = lc($format);
3863 print $cgi->a({-href => href(%href_params),
3864 -title => "$href_params{'-title'} $format feed",
3865 -class => $feed_class}, $format)."\n";
3868 } else {
3869 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3870 -class => $feed_class}, "OPML") . " ";
3871 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3872 -class => $feed_class}, "TXT") . "\n";
3874 print "</div>\n"; # class="page_footer"
3876 # timing info doesn't make much sense with output (response) caching,
3877 # so when caching is enabled gitweb prints the time of page generation
3878 if ((defined $t0 || $caching_enabled) &&
3879 gitweb_check_feature('timed')) {
3880 print "<div id=\"generating_info\">\n";
3881 if ($caching_enabled) {
3882 print 'This page was generated at '.
3883 gmtime( time() )." GMT\n";
3884 } else {
3885 print 'This page took '.
3886 '<span id="generating_time" class="time_span">'.
3887 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3888 ' seconds </span>'.
3889 ' and '.
3890 '<span id="generating_cmd">'.
3891 $number_of_git_cmds.
3892 '</span> git commands '.
3893 " to generate.\n";
3895 print "</div>\n"; # class="page_footer"
3898 if (defined $site_footer && -f $site_footer) {
3899 insert_file($site_footer);
3902 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3903 if (!$caching_enabled &&
3904 defined $action && $action eq 'blame_incremental') {
3905 print qq!<script type="text/javascript">\n!.
3906 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3907 qq! "!. href() .qq!");\n!.
3908 qq!</script>\n!;
3909 } elsif (gitweb_check_feature('javascript-actions')) {
3910 print qq!<script type="text/javascript">\n!.
3911 qq!window.onload = fixLinks;\n!.
3912 qq!</script>\n!;
3915 print "</body>\n" .
3916 "</html>";
3919 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3920 # Example: die_error(404, 'Hash not found')
3921 # By convention, use the following status codes (as defined in RFC 2616):
3922 # 400: Invalid or missing CGI parameters, or
3923 # requested object exists but has wrong type.
3924 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3925 # this server or project.
3926 # 404: Requested object/revision/project doesn't exist.
3927 # 500: The server isn't configured properly, or
3928 # an internal error occurred (e.g. failed assertions caused by bugs), or
3929 # an unknown error occurred (e.g. the git binary died unexpectedly).
3930 # 503: The server is currently unavailable (because it is overloaded,
3931 # or down for maintenance). Generally, this is a temporary state.
3932 sub die_error {
3933 my $status = shift || 500;
3934 my $error = esc_html(shift) || "Internal Server Error";
3935 my $extra = shift;
3936 my %opts = @_;
3938 my %http_responses = (
3939 400 => '400 Bad Request',
3940 403 => '403 Forbidden',
3941 404 => '404 Not Found',
3942 500 => '500 Internal Server Error',
3943 503 => '503 Service Unavailable',
3946 # Do not cache error pages
3947 capture_stop($cache, $capture) if ($capture && $caching_enabled);
3949 git_header_html($http_responses{$status}, undef, %opts);
3950 print <<EOF;
3951 <div class="page_body">
3952 <br /><br />
3953 $status - $error
3954 <br />
3956 if (defined $extra) {
3957 print "<hr />\n" .
3958 "$extra\n";
3960 print "</div>\n";
3962 git_footer_html();
3963 goto DONE_GITWEB
3964 unless ($opts{'-error_handler'});
3967 ## ----------------------------------------------------------------------
3968 ## functions printing or outputting HTML: navigation
3970 sub git_print_page_nav {
3971 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3972 $extra = '' if !defined $extra; # pager or formats
3974 my @navs = qw(summary shortlog log commit commitdiff tree);
3975 if ($suppress) {
3976 @navs = grep { $_ ne $suppress } @navs;
3979 my %arg = map { $_ => {action=>$_} } @navs;
3980 if (defined $head) {
3981 for (qw(commit commitdiff)) {
3982 $arg{$_}{'hash'} = $head;
3984 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3985 for (qw(shortlog log)) {
3986 $arg{$_}{'hash'} = $head;
3991 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3992 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3994 my @actions = gitweb_get_feature('actions');
3995 my %repl = (
3996 '%' => '%',
3997 'n' => $project, # project name
3998 'f' => $git_dir, # project path within filesystem
3999 'h' => $treehead || '', # current hash ('h' parameter)
4000 'b' => $treebase || '', # hash base ('hb' parameter)
4002 while (@actions) {
4003 my ($label, $link, $pos) = splice(@actions,0,3);
4004 # insert
4005 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4006 # munch munch
4007 $link =~ s/%([%nfhb])/$repl{$1}/g;
4008 $arg{$label}{'_href'} = $link;
4011 print "<div class=\"page_nav\">\n" .
4012 (join " | ",
4013 map { $_ eq $current ?
4014 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4015 } @navs);
4016 print "<br/>\n$extra<br/>\n" .
4017 "</div>\n";
4020 sub format_paging_nav {
4021 my ($action, $page, $has_next_link) = @_;
4022 my $paging_nav;
4025 if ($page > 0) {
4026 $paging_nav .=
4027 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4028 " &sdot; " .
4029 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4030 -accesskey => "p", -title => "Alt-p"}, "prev");
4031 } else {
4032 $paging_nav .= "first &sdot; prev";
4035 if ($has_next_link) {
4036 $paging_nav .= " &sdot; " .
4037 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4038 -accesskey => "n", -title => "Alt-n"}, "next");
4039 } else {
4040 $paging_nav .= " &sdot; next";
4043 return $paging_nav;
4046 ## ......................................................................
4047 ## functions printing or outputting HTML: div
4049 sub git_print_header_div {
4050 my ($action, $title, $hash, $hash_base) = @_;
4051 my %args = ();
4053 $args{'action'} = $action;
4054 $args{'hash'} = $hash if $hash;
4055 $args{'hash_base'} = $hash_base if $hash_base;
4057 print "<div class=\"header\">\n" .
4058 $cgi->a({-href => href(%args), -class => "title"},
4059 $title ? $title : $action) .
4060 "\n</div>\n";
4063 sub print_local_time {
4064 print format_local_time(@_);
4067 sub format_local_time {
4068 my $localtime = '';
4069 my %date = @_;
4070 if ($date{'hour_local'} < 6) {
4071 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4072 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4073 } else {
4074 $localtime .= sprintf(" (%02d:%02d %s)",
4075 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
4078 return $localtime;
4081 # Outputs the author name and date in long form
4082 sub git_print_authorship {
4083 my $co = shift;
4084 my %opts = @_;
4085 my $tag = $opts{-tag} || 'div';
4086 my $author = $co->{'author_name'};
4088 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4089 print "<$tag class=\"author_date\">" .
4090 format_search_author($author, "author", esc_html($author)) .
4091 " [$ad{'rfc2822'}";
4092 print_local_time(%ad) if ($opts{-localtime});
4093 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
4094 . "</$tag>\n";
4097 # Outputs table rows containing the full author or committer information,
4098 # in the format expected for 'commit' view (& similar).
4099 # Parameters are a commit hash reference, followed by the list of people
4100 # to output information for. If the list is empty it defaults to both
4101 # author and committer.
4102 sub git_print_authorship_rows {
4103 my $co = shift;
4104 # too bad we can't use @people = @_ || ('author', 'committer')
4105 my @people = @_;
4106 @people = ('author', 'committer') unless @people;
4107 foreach my $who (@people) {
4108 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4109 print "<tr><td>$who</td><td>" .
4110 format_search_author($co->{"${who}_name"}, $who,
4111 esc_html($co->{"${who}_name"})) . " " .
4112 format_search_author($co->{"${who}_email"}, $who,
4113 esc_html("<" . $co->{"${who}_email"} . ">")) .
4114 "</td><td rowspan=\"2\">" .
4115 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4116 "</td></tr>\n" .
4117 "<tr>" .
4118 "<td></td><td> $wd{'rfc2822'}";
4119 print_local_time(%wd);
4120 print "</td>" .
4121 "</tr>\n";
4125 sub git_print_page_path {
4126 my $name = shift;
4127 my $type = shift;
4128 my $hb = shift;
4131 print "<div class=\"page_path\">";
4132 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4133 -title => 'tree root'}, to_utf8("[$project]"));
4134 print " / ";
4135 if (defined $name) {
4136 my @dirname = split '/', $name;
4137 my $basename = pop @dirname;
4138 my $fullname = '';
4140 foreach my $dir (@dirname) {
4141 $fullname .= ($fullname ? '/' : '') . $dir;
4142 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4143 hash_base=>$hb),
4144 -title => $fullname}, esc_path($dir));
4145 print " / ";
4147 if (defined $type && $type eq 'blob') {
4148 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4149 hash_base=>$hb),
4150 -title => $name}, esc_path($basename));
4151 } elsif (defined $type && $type eq 'tree') {
4152 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4153 hash_base=>$hb),
4154 -title => $name}, esc_path($basename));
4155 print " / ";
4156 } else {
4157 print esc_path($basename);
4160 print "<br/></div>\n";
4163 sub git_print_log {
4164 my $log = shift;
4165 my %opts = @_;
4167 if ($opts{'-remove_title'}) {
4168 # remove title, i.e. first line of log
4169 shift @$log;
4171 # remove leading empty lines
4172 while (defined $log->[0] && $log->[0] eq "") {
4173 shift @$log;
4176 # print log
4177 my $signoff = 0;
4178 my $empty = 0;
4179 foreach my $line (@$log) {
4180 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4181 $signoff = 1;
4182 $empty = 0;
4183 if (! $opts{'-remove_signoff'}) {
4184 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4185 next;
4186 } else {
4187 # remove signoff lines
4188 next;
4190 } else {
4191 $signoff = 0;
4194 # print only one empty line
4195 # do not print empty line after signoff
4196 if ($line eq "") {
4197 next if ($empty || $signoff);
4198 $empty = 1;
4199 } else {
4200 $empty = 0;
4203 print format_log_line_html($line) . "<br/>\n";
4206 if ($opts{'-final_empty_line'}) {
4207 # end with single empty line
4208 print "<br/>\n" unless $empty;
4212 # return link target (what link points to)
4213 sub git_get_link_target {
4214 my $hash = shift;
4215 my $link_target;
4217 # read link
4218 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4219 or return;
4221 local $/ = undef;
4222 $link_target = <$fd>;
4224 close $fd
4225 or return;
4227 return $link_target;
4230 # given link target, and the directory (basedir) the link is in,
4231 # return target of link relative to top directory (top tree);
4232 # return undef if it is not possible (including absolute links).
4233 sub normalize_link_target {
4234 my ($link_target, $basedir) = @_;
4236 # absolute symlinks (beginning with '/') cannot be normalized
4237 return if (substr($link_target, 0, 1) eq '/');
4239 # normalize link target to path from top (root) tree (dir)
4240 my $path;
4241 if ($basedir) {
4242 $path = $basedir . '/' . $link_target;
4243 } else {
4244 # we are in top (root) tree (dir)
4245 $path = $link_target;
4248 # remove //, /./, and /../
4249 my @path_parts;
4250 foreach my $part (split('/', $path)) {
4251 # discard '.' and ''
4252 next if (!$part || $part eq '.');
4253 # handle '..'
4254 if ($part eq '..') {
4255 if (@path_parts) {
4256 pop @path_parts;
4257 } else {
4258 # link leads outside repository (outside top dir)
4259 return;
4261 } else {
4262 push @path_parts, $part;
4265 $path = join('/', @path_parts);
4267 return $path;
4270 # print tree entry (row of git_tree), but without encompassing <tr> element
4271 sub git_print_tree_entry {
4272 my ($t, $basedir, $hash_base, $have_blame) = @_;
4274 my %base_key = ();
4275 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4277 # The format of a table row is: mode list link. Where mode is
4278 # the mode of the entry, list is the name of the entry, an href,
4279 # and link is the action links of the entry.
4281 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4282 if (exists $t->{'size'}) {
4283 print "<td class=\"size\">$t->{'size'}</td>\n";
4285 if ($t->{'type'} eq "blob") {
4286 print "<td class=\"list\">" .
4287 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4288 file_name=>"$basedir$t->{'name'}", %base_key),
4289 -class => "list"}, esc_path($t->{'name'}));
4290 if (S_ISLNK(oct $t->{'mode'})) {
4291 my $link_target = git_get_link_target($t->{'hash'});
4292 if ($link_target) {
4293 my $norm_target = normalize_link_target($link_target, $basedir);
4294 if (defined $norm_target) {
4295 print " -> " .
4296 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4297 file_name=>$norm_target),
4298 -title => $norm_target}, esc_path($link_target));
4299 } else {
4300 print " -> " . esc_path($link_target);
4304 print "</td>\n";
4305 print "<td class=\"link\">";
4306 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4307 file_name=>"$basedir$t->{'name'}", %base_key)},
4308 "blob");
4309 if ($have_blame) {
4310 print " | " .
4311 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4312 file_name=>"$basedir$t->{'name'}", %base_key)},
4313 "blame");
4315 if (defined $hash_base) {
4316 print " | " .
4317 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4318 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4319 "history");
4321 print " | " .
4322 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4323 file_name=>"$basedir$t->{'name'}")},
4324 "raw");
4325 print "</td>\n";
4327 } elsif ($t->{'type'} eq "tree") {
4328 print "<td class=\"list\">";
4329 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4330 file_name=>"$basedir$t->{'name'}",
4331 %base_key)},
4332 esc_path($t->{'name'}));
4333 print "</td>\n";
4334 print "<td class=\"link\">";
4335 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4336 file_name=>"$basedir$t->{'name'}",
4337 %base_key)},
4338 "tree");
4339 if (defined $hash_base) {
4340 print " | " .
4341 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4342 file_name=>"$basedir$t->{'name'}")},
4343 "history");
4345 print "</td>\n";
4346 } else {
4347 # unknown object: we can only present history for it
4348 # (this includes 'commit' object, i.e. submodule support)
4349 print "<td class=\"list\">" .
4350 esc_path($t->{'name'}) .
4351 "</td>\n";
4352 print "<td class=\"link\">";
4353 if (defined $hash_base) {
4354 print $cgi->a({-href => href(action=>"history",
4355 hash_base=>$hash_base,
4356 file_name=>"$basedir$t->{'name'}")},
4357 "history");
4359 print "</td>\n";
4363 ## ......................................................................
4364 ## functions printing large fragments of HTML
4366 # get pre-image filenames for merge (combined) diff
4367 sub fill_from_file_info {
4368 my ($diff, @parents) = @_;
4370 $diff->{'from_file'} = [ ];
4371 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4372 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4373 if ($diff->{'status'}[$i] eq 'R' ||
4374 $diff->{'status'}[$i] eq 'C') {
4375 $diff->{'from_file'}[$i] =
4376 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4380 return $diff;
4383 # is current raw difftree line of file deletion
4384 sub is_deleted {
4385 my $diffinfo = shift;
4387 return $diffinfo->{'to_id'} eq ('0' x 40);
4390 # does patch correspond to [previous] difftree raw line
4391 # $diffinfo - hashref of parsed raw diff format
4392 # $patchinfo - hashref of parsed patch diff format
4393 # (the same keys as in $diffinfo)
4394 sub is_patch_split {
4395 my ($diffinfo, $patchinfo) = @_;
4397 return defined $diffinfo && defined $patchinfo
4398 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4402 sub git_difftree_body {
4403 my ($difftree, $hash, @parents) = @_;
4404 my ($parent) = $parents[0];
4405 my $have_blame = gitweb_check_feature('blame');
4406 print "<div class=\"list_head\">\n";
4407 if ($#{$difftree} > 10) {
4408 print(($#{$difftree} + 1) . " files changed:\n");
4410 print "</div>\n";
4412 print "<table class=\"" .
4413 (@parents > 1 ? "combined " : "") .
4414 "diff_tree\">\n";
4416 # header only for combined diff in 'commitdiff' view
4417 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4418 if ($has_header) {
4419 # table header
4420 print "<thead><tr>\n" .
4421 "<th></th><th></th>\n"; # filename, patchN link
4422 for (my $i = 0; $i < @parents; $i++) {
4423 my $par = $parents[$i];
4424 print "<th>" .
4425 $cgi->a({-href => href(action=>"commitdiff",
4426 hash=>$hash, hash_parent=>$par),
4427 -title => 'commitdiff to parent number ' .
4428 ($i+1) . ': ' . substr($par,0,7)},
4429 $i+1) .
4430 "&nbsp;</th>\n";
4432 print "</tr></thead>\n<tbody>\n";
4435 my $alternate = 1;
4436 my $patchno = 0;
4437 foreach my $line (@{$difftree}) {
4438 my $diff = parsed_difftree_line($line);
4440 if ($alternate) {
4441 print "<tr class=\"dark\">\n";
4442 } else {
4443 print "<tr class=\"light\">\n";
4445 $alternate ^= 1;
4447 if (exists $diff->{'nparents'}) { # combined diff
4449 fill_from_file_info($diff, @parents)
4450 unless exists $diff->{'from_file'};
4452 if (!is_deleted($diff)) {
4453 # file exists in the result (child) commit
4454 print "<td>" .
4455 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4456 file_name=>$diff->{'to_file'},
4457 hash_base=>$hash),
4458 -class => "list"}, esc_path($diff->{'to_file'})) .
4459 "</td>\n";
4460 } else {
4461 print "<td>" .
4462 esc_path($diff->{'to_file'}) .
4463 "</td>\n";
4466 if ($action eq 'commitdiff') {
4467 # link to patch
4468 $patchno++;
4469 print "<td class=\"link\">" .
4470 $cgi->a({-href => "#patch$patchno"}, "patch") .
4471 " | " .
4472 "</td>\n";
4475 my $has_history = 0;
4476 my $not_deleted = 0;
4477 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4478 my $hash_parent = $parents[$i];
4479 my $from_hash = $diff->{'from_id'}[$i];
4480 my $from_path = $diff->{'from_file'}[$i];
4481 my $status = $diff->{'status'}[$i];
4483 $has_history ||= ($status ne 'A');
4484 $not_deleted ||= ($status ne 'D');
4486 if ($status eq 'A') {
4487 print "<td class=\"link\" align=\"right\"> | </td>\n";
4488 } elsif ($status eq 'D') {
4489 print "<td class=\"link\">" .
4490 $cgi->a({-href => href(action=>"blob",
4491 hash_base=>$hash,
4492 hash=>$from_hash,
4493 file_name=>$from_path)},
4494 "blob" . ($i+1)) .
4495 " | </td>\n";
4496 } else {
4497 if ($diff->{'to_id'} eq $from_hash) {
4498 print "<td class=\"link nochange\">";
4499 } else {
4500 print "<td class=\"link\">";
4502 print $cgi->a({-href => href(action=>"blobdiff",
4503 hash=>$diff->{'to_id'},
4504 hash_parent=>$from_hash,
4505 hash_base=>$hash,
4506 hash_parent_base=>$hash_parent,
4507 file_name=>$diff->{'to_file'},
4508 file_parent=>$from_path)},
4509 "diff" . ($i+1)) .
4510 " | </td>\n";
4514 print "<td class=\"link\">";
4515 if ($not_deleted) {
4516 print $cgi->a({-href => href(action=>"blob",
4517 hash=>$diff->{'to_id'},
4518 file_name=>$diff->{'to_file'},
4519 hash_base=>$hash)},
4520 "blob");
4521 print " | " if ($has_history);
4523 if ($has_history) {
4524 print $cgi->a({-href => href(action=>"history",
4525 file_name=>$diff->{'to_file'},
4526 hash_base=>$hash)},
4527 "history");
4529 print "</td>\n";
4531 print "</tr>\n";
4532 next; # instead of 'else' clause, to avoid extra indent
4534 # else ordinary diff
4536 my ($to_mode_oct, $to_mode_str, $to_file_type);
4537 my ($from_mode_oct, $from_mode_str, $from_file_type);
4538 if ($diff->{'to_mode'} ne ('0' x 6)) {
4539 $to_mode_oct = oct $diff->{'to_mode'};
4540 if (S_ISREG($to_mode_oct)) { # only for regular file
4541 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4543 $to_file_type = file_type($diff->{'to_mode'});
4545 if ($diff->{'from_mode'} ne ('0' x 6)) {
4546 $from_mode_oct = oct $diff->{'from_mode'};
4547 if (S_ISREG($to_mode_oct)) { # only for regular file
4548 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4550 $from_file_type = file_type($diff->{'from_mode'});
4553 if ($diff->{'status'} eq "A") { # created
4554 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4555 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4556 $mode_chng .= "]</span>";
4557 print "<td>";
4558 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4559 hash_base=>$hash, file_name=>$diff->{'file'}),
4560 -class => "list"}, esc_path($diff->{'file'}));
4561 print "</td>\n";
4562 print "<td>$mode_chng</td>\n";
4563 print "<td class=\"link\">";
4564 if ($action eq 'commitdiff') {
4565 # link to patch
4566 $patchno++;
4567 print $cgi->a({-href => "#patch$patchno"}, "patch");
4568 print " | ";
4570 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4571 hash_base=>$hash, file_name=>$diff->{'file'})},
4572 "blob");
4573 print "</td>\n";
4575 } elsif ($diff->{'status'} eq "D") { # deleted
4576 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4577 print "<td>";
4578 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4579 hash_base=>$parent, file_name=>$diff->{'file'}),
4580 -class => "list"}, esc_path($diff->{'file'}));
4581 print "</td>\n";
4582 print "<td>$mode_chng</td>\n";
4583 print "<td class=\"link\">";
4584 if ($action eq 'commitdiff') {
4585 # link to patch
4586 $patchno++;
4587 print $cgi->a({-href => "#patch$patchno"}, "patch");
4588 print " | ";
4590 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4591 hash_base=>$parent, file_name=>$diff->{'file'})},
4592 "blob") . " | ";
4593 if ($have_blame) {
4594 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4595 file_name=>$diff->{'file'})},
4596 "blame") . " | ";
4598 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4599 file_name=>$diff->{'file'})},
4600 "history");
4601 print "</td>\n";
4603 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4604 my $mode_chnge = "";
4605 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4606 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4607 if ($from_file_type ne $to_file_type) {
4608 $mode_chnge .= " from $from_file_type to $to_file_type";
4610 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4611 if ($from_mode_str && $to_mode_str) {
4612 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4613 } elsif ($to_mode_str) {
4614 $mode_chnge .= " mode: $to_mode_str";
4617 $mode_chnge .= "]</span>\n";
4619 print "<td>";
4620 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4621 hash_base=>$hash, file_name=>$diff->{'file'}),
4622 -class => "list"}, esc_path($diff->{'file'}));
4623 print "</td>\n";
4624 print "<td>$mode_chnge</td>\n";
4625 print "<td class=\"link\">";
4626 if ($action eq 'commitdiff') {
4627 # link to patch
4628 $patchno++;
4629 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4630 " | ";
4631 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4632 # "commit" view and modified file (not onlu mode changed)
4633 print $cgi->a({-href => href(action=>"blobdiff",
4634 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4635 hash_base=>$hash, hash_parent_base=>$parent,
4636 file_name=>$diff->{'file'})},
4637 "diff") .
4638 " | ";
4640 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4641 hash_base=>$hash, file_name=>$diff->{'file'})},
4642 "blob") . " | ";
4643 if ($have_blame) {
4644 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4645 file_name=>$diff->{'file'})},
4646 "blame") . " | ";
4648 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4649 file_name=>$diff->{'file'})},
4650 "history");
4651 print "</td>\n";
4653 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4654 my %status_name = ('R' => 'moved', 'C' => 'copied');
4655 my $nstatus = $status_name{$diff->{'status'}};
4656 my $mode_chng = "";
4657 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4658 # mode also for directories, so we cannot use $to_mode_str
4659 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4661 print "<td>" .
4662 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4663 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4664 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4665 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4666 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4667 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4668 -class => "list"}, esc_path($diff->{'from_file'})) .
4669 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4670 "<td class=\"link\">";
4671 if ($action eq 'commitdiff') {
4672 # link to patch
4673 $patchno++;
4674 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4675 " | ";
4676 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4677 # "commit" view and modified file (not only pure rename or copy)
4678 print $cgi->a({-href => href(action=>"blobdiff",
4679 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4680 hash_base=>$hash, hash_parent_base=>$parent,
4681 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4682 "diff") .
4683 " | ";
4685 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4686 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4687 "blob") . " | ";
4688 if ($have_blame) {
4689 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4690 file_name=>$diff->{'to_file'})},
4691 "blame") . " | ";
4693 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4694 file_name=>$diff->{'to_file'})},
4695 "history");
4696 print "</td>\n";
4698 } # we should not encounter Unmerged (U) or Unknown (X) status
4699 print "</tr>\n";
4701 print "</tbody>" if $has_header;
4702 print "</table>\n";
4705 sub git_patchset_body {
4706 my ($fd, $difftree, $hash, @hash_parents) = @_;
4707 my ($hash_parent) = $hash_parents[0];
4709 my $is_combined = (@hash_parents > 1);
4710 my $patch_idx = 0;
4711 my $patch_number = 0;
4712 my $patch_line;
4713 my $diffinfo;
4714 my $to_name;
4715 my (%from, %to);
4717 print "<div class=\"patchset\">\n";
4719 # skip to first patch
4720 while ($patch_line = <$fd>) {
4721 chomp $patch_line;
4723 last if ($patch_line =~ m/^diff /);
4726 PATCH:
4727 while ($patch_line) {
4729 # parse "git diff" header line
4730 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4731 # $1 is from_name, which we do not use
4732 $to_name = unquote($2);
4733 $to_name =~ s!^b/!!;
4734 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4735 # $1 is 'cc' or 'combined', which we do not use
4736 $to_name = unquote($2);
4737 } else {
4738 $to_name = undef;
4741 # check if current patch belong to current raw line
4742 # and parse raw git-diff line if needed
4743 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4744 # this is continuation of a split patch
4745 print "<div class=\"patch cont\">\n";
4746 } else {
4747 # advance raw git-diff output if needed
4748 $patch_idx++ if defined $diffinfo;
4750 # read and prepare patch information
4751 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4753 # compact combined diff output can have some patches skipped
4754 # find which patch (using pathname of result) we are at now;
4755 if ($is_combined) {
4756 while ($to_name ne $diffinfo->{'to_file'}) {
4757 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4758 format_diff_cc_simplified($diffinfo, @hash_parents) .
4759 "</div>\n"; # class="patch"
4761 $patch_idx++;
4762 $patch_number++;
4764 last if $patch_idx > $#$difftree;
4765 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4769 # modifies %from, %to hashes
4770 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4772 # this is first patch for raw difftree line with $patch_idx index
4773 # we index @$difftree array from 0, but number patches from 1
4774 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4777 # git diff header
4778 #assert($patch_line =~ m/^diff /) if DEBUG;
4779 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4780 $patch_number++;
4781 # print "git diff" header
4782 print format_git_diff_header_line($patch_line, $diffinfo,
4783 \%from, \%to);
4785 # print extended diff header
4786 print "<div class=\"diff extended_header\">\n";
4787 EXTENDED_HEADER:
4788 while ($patch_line = <$fd>) {
4789 chomp $patch_line;
4791 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4793 print format_extended_diff_header_line($patch_line, $diffinfo,
4794 \%from, \%to);
4796 print "</div>\n"; # class="diff extended_header"
4798 # from-file/to-file diff header
4799 if (! $patch_line) {
4800 print "</div>\n"; # class="patch"
4801 last PATCH;
4803 next PATCH if ($patch_line =~ m/^diff /);
4804 #assert($patch_line =~ m/^---/) if DEBUG;
4806 my $last_patch_line = $patch_line;
4807 $patch_line = <$fd>;
4808 chomp $patch_line;
4809 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4811 print format_diff_from_to_header($last_patch_line, $patch_line,
4812 $diffinfo, \%from, \%to,
4813 @hash_parents);
4815 # the patch itself
4816 LINE:
4817 while ($patch_line = <$fd>) {
4818 chomp $patch_line;
4820 next PATCH if ($patch_line =~ m/^diff /);
4822 print format_diff_line($patch_line, \%from, \%to);
4825 } continue {
4826 print "</div>\n"; # class="patch"
4829 # for compact combined (--cc) format, with chunk and patch simplification
4830 # the patchset might be empty, but there might be unprocessed raw lines
4831 for (++$patch_idx if $patch_number > 0;
4832 $patch_idx < @$difftree;
4833 ++$patch_idx) {
4834 # read and prepare patch information
4835 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4837 # generate anchor for "patch" links in difftree / whatchanged part
4838 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4839 format_diff_cc_simplified($diffinfo, @hash_parents) .
4840 "</div>\n"; # class="patch"
4842 $patch_number++;
4845 if ($patch_number == 0) {
4846 if (@hash_parents > 1) {
4847 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4848 } else {
4849 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4853 print "</div>\n"; # class="patchset"
4856 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4858 # fills project list info (age, description, owner, forks) for each
4859 # project in the list, removing invalid projects from returned list
4860 # NOTE: modifies $projlist, but does not remove entries from it
4861 sub fill_project_list_info {
4862 my ($projlist, $check_forks) = @_;
4863 my @projects;
4865 my $show_ctags = gitweb_check_feature('ctags');
4866 PROJECT:
4867 foreach my $pr (@$projlist) {
4868 my (@activity) = git_get_last_activity($pr->{'path'});
4869 unless (@activity) {
4870 next PROJECT;
4872 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4873 if (!defined $pr->{'descr'}) {
4874 my $descr = git_get_project_description($pr->{'path'}) || "";
4875 $descr = to_utf8($descr);
4876 $pr->{'descr_long'} = $descr;
4877 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4879 if (!defined $pr->{'owner'}) {
4880 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4882 if ($check_forks) {
4883 my $pname = $pr->{'path'};
4884 if (($pname =~ s/\.git$//) &&
4885 ($pname !~ /\/$/) &&
4886 (-d "$projectroot/$pname")) {
4887 $pr->{'forks'} = "-d $projectroot/$pname";
4888 } else {
4889 $pr->{'forks'} = 0;
4892 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4893 push @projects, $pr;
4896 return @projects;
4899 # print 'sort by' <th> element, generating 'sort by $name' replay link
4900 # if that order is not selected
4901 sub print_sort_th {
4902 print format_sort_th(@_);
4905 sub format_sort_th {
4906 my ($name, $order, $header) = @_;
4907 my $sort_th = "";
4908 $header ||= ucfirst($name);
4910 if ($order eq $name) {
4911 $sort_th .= "<th>$header</th>\n";
4912 } else {
4913 $sort_th .= "<th>" .
4914 $cgi->a({-href => href(-replay=>1, order=>$name),
4915 -class => "header"}, $header) .
4916 "</th>\n";
4919 return $sort_th;
4922 sub git_project_list_body {
4923 # actually uses global variable $project
4924 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4926 my $check_forks = gitweb_check_feature('forks');
4927 my @projects = fill_project_list_info($projlist, $check_forks);
4929 $order ||= $default_projects_order;
4930 $from = 0 unless defined $from;
4931 $to = $#projects if (!defined $to || $#projects < $to);
4933 my %order_info = (
4934 project => { key => 'path', type => 'str' },
4935 descr => { key => 'descr_long', type => 'str' },
4936 owner => { key => 'owner', type => 'str' },
4937 age => { key => 'age', type => 'num' }
4939 my $oi = $order_info{$order};
4940 if ($oi->{'type'} eq 'str') {
4941 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4942 } else {
4943 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4946 my $show_ctags = gitweb_check_feature('ctags');
4947 if ($show_ctags) {
4948 my %ctags;
4949 foreach my $p (@projects) {
4950 foreach my $ct (keys %{$p->{'ctags'}}) {
4951 $ctags{$ct} += $p->{'ctags'}->{$ct};
4954 my $cloud = git_populate_project_tagcloud(\%ctags);
4955 print git_show_project_tagcloud($cloud, 64);
4958 print "<table class=\"project_list\">\n";
4959 unless ($no_header) {
4960 print "<tr>\n";
4961 if ($check_forks) {
4962 print "<th></th>\n";
4964 print_sort_th('project', $order, 'Project');
4965 print_sort_th('descr', $order, 'Description');
4966 print_sort_th('owner', $order, 'Owner');
4967 print_sort_th('age', $order, 'Last Change');
4968 print "<th></th>\n" . # for links
4969 "</tr>\n";
4971 my $alternate = 1;
4972 my $tagfilter = $cgi->param('by_tag');
4973 for (my $i = $from; $i <= $to; $i++) {
4974 my $pr = $projects[$i];
4976 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4977 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4978 and not $pr->{'descr_long'} =~ /$searchtext/;
4979 # Weed out forks or non-matching entries of search
4980 if ($check_forks) {
4981 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4982 $forkbase="^$forkbase" if $forkbase;
4983 next if not $searchtext and not $tagfilter and $show_ctags
4984 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4987 if ($alternate) {
4988 print "<tr class=\"dark\">\n";
4989 } else {
4990 print "<tr class=\"light\">\n";
4992 $alternate ^= 1;
4993 if ($check_forks) {
4994 print "<td>";
4995 if ($pr->{'forks'}) {
4996 print "<!-- $pr->{'forks'} -->\n";
4997 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4999 print "</td>\n";
5001 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5002 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
5003 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5004 -class => "list", -title => $pr->{'descr_long'}},
5005 esc_html($pr->{'descr'})) . "</td>\n" .
5006 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5007 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5008 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
5009 "<td class=\"link\">" .
5010 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5011 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5012 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5013 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5014 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5015 "</td>\n" .
5016 "</tr>\n";
5018 if (defined $extra) {
5019 print "<tr>\n";
5020 if ($check_forks) {
5021 print "<td></td>\n";
5023 print "<td colspan=\"5\">$extra</td>\n" .
5024 "</tr>\n";
5026 print "</table>\n";
5029 sub git_log_body {
5030 # uses global variable $project
5031 my ($commitlist, $from, $to, $refs, $extra) = @_;
5033 $from = 0 unless defined $from;
5034 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5036 for (my $i = 0; $i <= $to; $i++) {
5037 my %co = %{$commitlist->[$i]};
5038 next if !%co;
5039 my $commit = $co{'id'};
5040 my $ref = format_ref_marker($refs, $commit);
5041 my %ad = parse_date($co{'author_epoch'});
5042 git_print_header_div('commit',
5043 "<span class=\"age\">$co{'age_string'}</span>" .
5044 esc_html($co{'title'}) . $ref,
5045 $commit);
5046 print "<div class=\"title_text\">\n" .
5047 "<div class=\"log_link\">\n" .
5048 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5049 " | " .
5050 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5051 " | " .
5052 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5053 "<br/>\n" .
5054 "</div>\n";
5055 git_print_authorship(\%co, -tag => 'span');
5056 print "<br/>\n</div>\n";
5058 print "<div class=\"log_body\">\n";
5059 git_print_log($co{'comment'}, -final_empty_line=> 1);
5060 print "</div>\n";
5062 if ($extra) {
5063 print "<div class=\"page_nav\">\n";
5064 print "$extra\n";
5065 print "</div>\n";
5069 sub git_shortlog_body {
5070 # uses global variable $project
5071 my ($commitlist, $from, $to, $refs, $extra) = @_;
5073 $from = 0 unless defined $from;
5074 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5076 print "<table class=\"shortlog\">\n";
5077 my $alternate = 1;
5078 for (my $i = $from; $i <= $to; $i++) {
5079 my %co = %{$commitlist->[$i]};
5080 my $commit = $co{'id'};
5081 my $ref = format_ref_marker($refs, $commit);
5082 if ($alternate) {
5083 print "<tr class=\"dark\">\n";
5084 } else {
5085 print "<tr class=\"light\">\n";
5087 $alternate ^= 1;
5088 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5089 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5090 format_author_html('td', \%co, 10) . "<td>";
5091 print format_subject_html($co{'title'}, $co{'title_short'},
5092 href(action=>"commit", hash=>$commit), $ref);
5093 print "</td>\n" .
5094 "<td class=\"link\">" .
5095 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5096 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5097 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5098 my $snapshot_links = format_snapshot_links($commit);
5099 if (defined $snapshot_links) {
5100 print " | " . $snapshot_links;
5102 print "</td>\n" .
5103 "</tr>\n";
5105 if (defined $extra) {
5106 print "<tr>\n" .
5107 "<td colspan=\"4\">$extra</td>\n" .
5108 "</tr>\n";
5110 print "</table>\n";
5113 sub git_history_body {
5114 # Warning: assumes constant type (blob or tree) during history
5115 my ($commitlist, $from, $to, $refs, $extra,
5116 $file_name, $file_hash, $ftype) = @_;
5118 $from = 0 unless defined $from;
5119 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5121 print "<table class=\"history\">\n";
5122 my $alternate = 1;
5123 for (my $i = $from; $i <= $to; $i++) {
5124 my %co = %{$commitlist->[$i]};
5125 if (!%co) {
5126 next;
5128 my $commit = $co{'id'};
5130 my $ref = format_ref_marker($refs, $commit);
5132 if ($alternate) {
5133 print "<tr class=\"dark\">\n";
5134 } else {
5135 print "<tr class=\"light\">\n";
5137 $alternate ^= 1;
5138 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5139 # shortlog: format_author_html('td', \%co, 10)
5140 format_author_html('td', \%co, 15, 3) . "<td>";
5141 # originally git_history used chop_str($co{'title'}, 50)
5142 print format_subject_html($co{'title'}, $co{'title_short'},
5143 href(action=>"commit", hash=>$commit), $ref);
5144 print "</td>\n" .
5145 "<td class=\"link\">" .
5146 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5147 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5149 if ($ftype eq 'blob') {
5150 my $blob_current = $file_hash;
5151 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5152 if (defined $blob_current && defined $blob_parent &&
5153 $blob_current ne $blob_parent) {
5154 print " | " .
5155 $cgi->a({-href => href(action=>"blobdiff",
5156 hash=>$blob_current, hash_parent=>$blob_parent,
5157 hash_base=>$hash_base, hash_parent_base=>$commit,
5158 file_name=>$file_name)},
5159 "diff to current");
5162 print "</td>\n" .
5163 "</tr>\n";
5165 if (defined $extra) {
5166 print "<tr>\n" .
5167 "<td colspan=\"4\">$extra</td>\n" .
5168 "</tr>\n";
5170 print "</table>\n";
5173 sub git_tags_body {
5174 # uses global variable $project
5175 my ($taglist, $from, $to, $extra) = @_;
5176 $from = 0 unless defined $from;
5177 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5179 print "<table class=\"tags\">\n";
5180 my $alternate = 1;
5181 for (my $i = $from; $i <= $to; $i++) {
5182 my $entry = $taglist->[$i];
5183 my %tag = %$entry;
5184 my $comment = $tag{'subject'};
5185 my $comment_short;
5186 if (defined $comment) {
5187 $comment_short = chop_str($comment, 30, 5);
5189 if ($alternate) {
5190 print "<tr class=\"dark\">\n";
5191 } else {
5192 print "<tr class=\"light\">\n";
5194 $alternate ^= 1;
5195 if (defined $tag{'age'}) {
5196 print "<td><i>$tag{'age'}</i></td>\n";
5197 } else {
5198 print "<td></td>\n";
5200 print "<td>" .
5201 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5202 -class => "list name"}, esc_html($tag{'name'})) .
5203 "</td>\n" .
5204 "<td>";
5205 if (defined $comment) {
5206 print format_subject_html($comment, $comment_short,
5207 href(action=>"tag", hash=>$tag{'id'}));
5209 print "</td>\n" .
5210 "<td class=\"selflink\">";
5211 if ($tag{'type'} eq "tag") {
5212 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5213 } else {
5214 print "&nbsp;";
5216 print "</td>\n" .
5217 "<td class=\"link\">" . " | " .
5218 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5219 if ($tag{'reftype'} eq "commit") {
5220 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5221 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5222 } elsif ($tag{'reftype'} eq "blob") {
5223 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5225 print "</td>\n" .
5226 "</tr>";
5228 if (defined $extra) {
5229 print "<tr>\n" .
5230 "<td colspan=\"5\">$extra</td>\n" .
5231 "</tr>\n";
5233 print "</table>\n";
5236 sub git_heads_body {
5237 # uses global variable $project
5238 my ($headlist, $head, $from, $to, $extra) = @_;
5239 $from = 0 unless defined $from;
5240 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5242 print "<table class=\"heads\">\n";
5243 my $alternate = 1;
5244 for (my $i = $from; $i <= $to; $i++) {
5245 my $entry = $headlist->[$i];
5246 my %ref = %$entry;
5247 my $curr = $ref{'id'} eq $head;
5248 if ($alternate) {
5249 print "<tr class=\"dark\">\n";
5250 } else {
5251 print "<tr class=\"light\">\n";
5253 $alternate ^= 1;
5254 print "<td><i>$ref{'age'}</i></td>\n" .
5255 ($curr ? "<td class=\"current_head\">" : "<td>") .
5256 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5257 -class => "list name"},esc_html($ref{'name'})) .
5258 "</td>\n" .
5259 "<td class=\"link\">" .
5260 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5261 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5262 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
5263 "</td>\n" .
5264 "</tr>";
5266 if (defined $extra) {
5267 print "<tr>\n" .
5268 "<td colspan=\"3\">$extra</td>\n" .
5269 "</tr>\n";
5271 print "</table>\n";
5274 sub git_search_grep_body {
5275 my ($commitlist, $from, $to, $extra) = @_;
5276 $from = 0 unless defined $from;
5277 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5279 print "<table class=\"commit_search\">\n";
5280 my $alternate = 1;
5281 for (my $i = $from; $i <= $to; $i++) {
5282 my %co = %{$commitlist->[$i]};
5283 if (!%co) {
5284 next;
5286 my $commit = $co{'id'};
5287 if ($alternate) {
5288 print "<tr class=\"dark\">\n";
5289 } else {
5290 print "<tr class=\"light\">\n";
5292 $alternate ^= 1;
5293 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5294 format_author_html('td', \%co, 15, 5) .
5295 "<td>" .
5296 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5297 -class => "list subject"},
5298 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5299 my $comment = $co{'comment'};
5300 foreach my $line (@$comment) {
5301 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5302 my ($lead, $match, $trail) = ($1, $2, $3);
5303 $match = chop_str($match, 70, 5, 'center');
5304 my $contextlen = int((80 - length($match))/2);
5305 $contextlen = 30 if ($contextlen > 30);
5306 $lead = chop_str($lead, $contextlen, 10, 'left');
5307 $trail = chop_str($trail, $contextlen, 10, 'right');
5309 $lead = esc_html($lead);
5310 $match = esc_html($match);
5311 $trail = esc_html($trail);
5313 print "$lead<span class=\"match\">$match</span>$trail<br />";
5316 print "</td>\n" .
5317 "<td class=\"link\">" .
5318 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5319 " | " .
5320 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5321 " | " .
5322 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5323 print "</td>\n" .
5324 "</tr>\n";
5326 if (defined $extra) {
5327 print "<tr>\n" .
5328 "<td colspan=\"3\">$extra</td>\n" .
5329 "</tr>\n";
5331 print "</table>\n";
5334 ## ======================================================================
5335 ## ======================================================================
5336 ## actions
5338 sub git_project_list {
5339 my $order = $input_params{'order'};
5340 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5341 die_error(400, "Unknown order parameter");
5344 my @list = git_get_projects_list();
5345 if (!@list) {
5346 die_error(404, "No projects found");
5349 git_header_html();
5350 if (defined $home_text && -f $home_text) {
5351 print "<div class=\"index_include\">\n";
5352 insert_file($home_text);
5353 print "</div>\n";
5355 print $cgi->startform(-method => "get") .
5356 "<p class=\"projsearch\">Search:\n" .
5357 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5358 "</p>" .
5359 $cgi->end_form() . "\n";
5360 git_project_list_body(\@list, $order);
5361 git_footer_html();
5364 sub git_forks {
5365 my $order = $input_params{'order'};
5366 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5367 die_error(400, "Unknown order parameter");
5370 my @list = git_get_projects_list($project);
5371 if (!@list) {
5372 die_error(404, "No forks found");
5375 git_header_html();
5376 git_print_page_nav('','');
5377 git_print_header_div('summary', "$project forks");
5378 git_project_list_body(\@list, $order);
5379 git_footer_html();
5382 sub git_project_index {
5383 my @projects = git_get_projects_list($project);
5385 print $cgi->header(
5386 -type => 'text/plain',
5387 -charset => 'utf-8',
5388 -content_disposition => 'inline; filename="index.aux"');
5390 foreach my $pr (@projects) {
5391 if (!exists $pr->{'owner'}) {
5392 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5395 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5396 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5397 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5398 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5399 $path =~ s/ /\+/g;
5400 $owner =~ s/ /\+/g;
5402 print "$path $owner\n";
5406 sub git_summary {
5407 my $descr = git_get_project_description($project) || "none";
5408 my %co = parse_commit("HEAD");
5409 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5410 my $head = $co{'id'};
5412 my $owner = git_get_project_owner($project);
5414 my $refs = git_get_references();
5415 # These get_*_list functions return one more to allow us to see if
5416 # there are more ...
5417 my @taglist = git_get_tags_list(16);
5418 my @headlist = git_get_heads_list(16);
5419 my @forklist;
5420 my $check_forks = gitweb_check_feature('forks');
5422 if ($check_forks) {
5423 @forklist = git_get_projects_list($project);
5426 git_header_html();
5427 git_print_page_nav('summary','', $head);
5429 print "<div class=\"title\">&nbsp;</div>\n";
5430 print "<table class=\"projects_list\">\n" .
5431 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5432 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5433 if (defined $cd{'rfc2822'}) {
5434 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5437 # use per project git URL list in $projectroot/$project/cloneurl
5438 # or make project git URL from git base URL and project name
5439 my $url_tag = "URL";
5440 my @url_list = git_get_project_url_list($project);
5441 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5442 foreach my $git_url (@url_list) {
5443 next unless $git_url;
5444 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5445 $url_tag = "";
5448 # Tag cloud
5449 my $show_ctags = gitweb_check_feature('ctags');
5450 if ($show_ctags) {
5451 my $ctags = git_get_project_ctags($project);
5452 my $cloud = git_populate_project_tagcloud($ctags);
5453 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5454 print "</td>\n<td>" unless %$ctags;
5455 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5456 print "</td>\n<td>" if %$ctags;
5457 print git_show_project_tagcloud($cloud, 48);
5458 print "</td></tr>";
5461 print "</table>\n";
5463 # If XSS prevention is on, we don't include README.html.
5464 # TODO: Allow a readme in some safe format.
5465 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5466 print "<div class=\"title\">readme</div>\n" .
5467 "<div class=\"readme\">\n";
5468 insert_file("$projectroot/$project/README.html");
5469 print "\n</div>\n"; # class="readme"
5472 # we need to request one more than 16 (0..15) to check if
5473 # those 16 are all
5474 my @commitlist = $head ? parse_commits($head, 17) : ();
5475 if (@commitlist) {
5476 git_print_header_div('shortlog');
5477 git_shortlog_body(\@commitlist, 0, 15, $refs,
5478 $#commitlist <= 15 ? undef :
5479 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5482 if (@taglist) {
5483 git_print_header_div('tags');
5484 git_tags_body(\@taglist, 0, 15,
5485 $#taglist <= 15 ? undef :
5486 $cgi->a({-href => href(action=>"tags")}, "..."));
5489 if (@headlist) {
5490 git_print_header_div('heads');
5491 git_heads_body(\@headlist, $head, 0, 15,
5492 $#headlist <= 15 ? undef :
5493 $cgi->a({-href => href(action=>"heads")}, "..."));
5496 if (@forklist) {
5497 git_print_header_div('forks');
5498 git_project_list_body(\@forklist, 'age', 0, 15,
5499 $#forklist <= 15 ? undef :
5500 $cgi->a({-href => href(action=>"forks")}, "..."),
5501 'no_header');
5504 git_footer_html();
5507 sub git_tag {
5508 my %tag = parse_tag($hash);
5510 if (! %tag) {
5511 die_error(404, "Unknown tag object");
5514 my $head = git_get_head_hash($project);
5515 git_header_html();
5516 git_print_page_nav('','', $head,undef,$head);
5517 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5518 print "<div class=\"title_text\">\n" .
5519 "<table class=\"object_header\">\n" .
5520 "<tr>\n" .
5521 "<td>object</td>\n" .
5522 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5523 $tag{'object'}) . "</td>\n" .
5524 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5525 $tag{'type'}) . "</td>\n" .
5526 "</tr>\n";
5527 if (defined($tag{'author'})) {
5528 git_print_authorship_rows(\%tag, 'author');
5530 print "</table>\n\n" .
5531 "</div>\n";
5532 print "<div class=\"page_body\">";
5533 my $comment = $tag{'comment'};
5534 foreach my $line (@$comment) {
5535 chomp $line;
5536 print esc_html($line, -nbsp=>1) . "<br/>\n";
5538 print "</div>\n";
5539 git_footer_html();
5542 sub git_blame_common {
5543 my $format = shift || 'porcelain';
5544 if ($format eq 'porcelain' && $cgi->param('js') &&
5545 !$caching_enabled) {
5546 $format = 'incremental';
5547 $action = 'blame_incremental'; # for page title etc
5550 # permissions
5551 gitweb_check_feature('blame')
5552 or die_error(403, "Blame view not allowed");
5554 # error checking
5555 die_error(400, "No file name given") unless $file_name;
5556 $hash_base ||= git_get_head_hash($project);
5557 die_error(404, "Couldn't find base commit") unless $hash_base;
5558 my %co = parse_commit($hash_base)
5559 or die_error(404, "Commit not found");
5560 my $ftype = "blob";
5561 if (!defined $hash) {
5562 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5563 or die_error(404, "Error looking up file");
5564 } else {
5565 $ftype = git_get_type($hash);
5566 if ($ftype !~ "blob") {
5567 die_error(400, "Object is not a blob");
5571 my $fd;
5572 if ($format eq 'incremental') {
5573 # get file contents (as base)
5574 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5575 or die_error(500, "Open git-cat-file failed");
5576 } elsif ($format eq 'data') {
5577 # run git-blame --incremental
5578 open $fd, "-|", git_cmd(), "blame", "--incremental",
5579 $hash_base, "--", $file_name
5580 or die_error(500, "Open git-blame --incremental failed");
5581 } else {
5582 # run git-blame --porcelain
5583 open $fd, "-|", git_cmd(), "blame", '-p',
5584 $hash_base, '--', $file_name
5585 or die_error(500, "Open git-blame --porcelain failed");
5588 # incremental blame data returns early
5589 if ($format eq 'data') {
5590 print $cgi->header(
5591 -type=>"text/plain", -charset => "utf-8",
5592 -status=> "200 OK");
5593 local $| = 1; # output autoflush
5594 print while <$fd>;
5595 close $fd
5596 or print "ERROR $!\n";
5598 print 'END';
5599 if (!$caching_enabled &&
5600 defined $t0 && gitweb_check_feature('timed')) {
5601 print ' '.
5602 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5603 ' '.$number_of_git_cmds;
5605 print "\n";
5607 return;
5610 # page header
5611 git_header_html();
5612 my $formats_nav =
5613 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5614 "blob") .
5615 " | ";
5616 if ($format eq 'incremental') {
5617 $formats_nav .=
5618 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5619 "blame") . " (non-incremental)";
5620 } elsif (!$caching_enabled) {
5621 $formats_nav .=
5622 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5623 "blame") . " (incremental)";
5625 $formats_nav .=
5626 " | " .
5627 $cgi->a({-href => href(action=>"history", -replay=>1)},
5628 "history") .
5629 " | " .
5630 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5631 "HEAD");
5632 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5633 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5634 git_print_page_path($file_name, $ftype, $hash_base);
5636 # page body
5637 if ($format eq 'incremental') {
5638 print "<noscript>\n<div class=\"error\"><center><b>\n".
5639 "This page requires JavaScript to run.\n Use ".
5640 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5641 'this page').
5642 " instead.\n".
5643 "</b></center></div>\n</noscript>\n";
5645 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5648 print qq!<div class="page_body">\n!;
5649 print qq!<div id="progress_info">... / ...</div>\n!
5650 if ($format eq 'incremental');
5651 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5652 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5653 qq!<thead>\n!.
5654 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5655 qq!</thead>\n!.
5656 qq!<tbody>\n!;
5658 my @rev_color = qw(light dark);
5659 my $num_colors = scalar(@rev_color);
5660 my $current_color = 0;
5662 if ($format eq 'incremental') {
5663 my $color_class = $rev_color[$current_color];
5665 #contents of a file
5666 my $linenr = 0;
5667 LINE:
5668 while (my $line = <$fd>) {
5669 chomp $line;
5670 $linenr++;
5672 print qq!<tr id="l$linenr" class="$color_class">!.
5673 qq!<td class="sha1"><a href=""> </a></td>!.
5674 qq!<td class="linenr">!.
5675 qq!<a class="linenr" href="">$linenr</a></td>!;
5676 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5677 print qq!</tr>\n!;
5680 } else { # porcelain, i.e. ordinary blame
5681 my %metainfo = (); # saves information about commits
5683 # blame data
5684 LINE:
5685 while (my $line = <$fd>) {
5686 chomp $line;
5687 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5688 # no <lines in group> for subsequent lines in group of lines
5689 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5690 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5691 if (!exists $metainfo{$full_rev}) {
5692 $metainfo{$full_rev} = { 'nprevious' => 0 };
5694 my $meta = $metainfo{$full_rev};
5695 my $data;
5696 while ($data = <$fd>) {
5697 chomp $data;
5698 last if ($data =~ s/^\t//); # contents of line
5699 if ($data =~ /^(\S+)(?: (.*))?$/) {
5700 $meta->{$1} = $2 unless exists $meta->{$1};
5702 if ($data =~ /^previous /) {
5703 $meta->{'nprevious'}++;
5706 my $short_rev = substr($full_rev, 0, 8);
5707 my $author = $meta->{'author'};
5708 my %date =
5709 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5710 my $date = $date{'iso-tz'};
5711 if ($group_size) {
5712 $current_color = ($current_color + 1) % $num_colors;
5714 my $tr_class = $rev_color[$current_color];
5715 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5716 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5717 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5718 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5719 if ($group_size) {
5720 print "<td class=\"sha1\"";
5721 print " title=\"". esc_html($author) . ", $date\"";
5722 print " rowspan=\"$group_size\"" if ($group_size > 1);
5723 print ">";
5724 print $cgi->a({-href => href(action=>"commit",
5725 hash=>$full_rev,
5726 file_name=>$file_name)},
5727 esc_html($short_rev));
5728 if ($group_size >= 2) {
5729 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5730 if (@author_initials) {
5731 print "<br />" .
5732 esc_html(join('', @author_initials));
5733 # or join('.', ...)
5736 print "</td>\n";
5738 # 'previous' <sha1 of parent commit> <filename at commit>
5739 if (exists $meta->{'previous'} &&
5740 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5741 $meta->{'parent'} = $1;
5742 $meta->{'file_parent'} = unquote($2);
5744 my $linenr_commit =
5745 exists($meta->{'parent'}) ?
5746 $meta->{'parent'} : $full_rev;
5747 my $linenr_filename =
5748 exists($meta->{'file_parent'}) ?
5749 $meta->{'file_parent'} : unquote($meta->{'filename'});
5750 my $blamed = href(action => 'blame',
5751 file_name => $linenr_filename,
5752 hash_base => $linenr_commit);
5753 print "<td class=\"linenr\">";
5754 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5755 -class => "linenr" },
5756 esc_html($lineno));
5757 print "</td>";
5758 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5759 print "</tr>\n";
5760 } # end while
5764 # footer
5765 print "</tbody>\n".
5766 "</table>\n"; # class="blame"
5767 print "</div>\n"; # class="blame_body"
5768 close $fd
5769 or print "Reading blob failed\n";
5771 git_footer_html();
5774 sub git_blame {
5775 git_blame_common();
5778 sub git_blame_incremental {
5779 git_blame_common(!$caching_enabled ? 'incremental' : undef);
5782 sub git_blame_data {
5783 git_blame_common('data');
5786 sub git_tags {
5787 my $head = git_get_head_hash($project);
5788 git_header_html();
5789 git_print_page_nav('','', $head,undef,$head);
5790 git_print_header_div('summary', $project);
5792 my @tagslist = git_get_tags_list();
5793 if (@tagslist) {
5794 git_tags_body(\@tagslist);
5796 git_footer_html();
5799 sub git_heads {
5800 my $head = git_get_head_hash($project);
5801 git_header_html();
5802 git_print_page_nav('','', $head,undef,$head);
5803 git_print_header_div('summary', $project);
5805 my @headslist = git_get_heads_list();
5806 if (@headslist) {
5807 git_heads_body(\@headslist, $head);
5809 git_footer_html();
5812 sub git_blob_plain {
5813 my $type = shift;
5814 my $expires;
5816 if (!defined $hash) {
5817 if (defined $file_name) {
5818 my $base = $hash_base || git_get_head_hash($project);
5819 $hash = git_get_hash_by_path($base, $file_name, "blob")
5820 or die_error(404, "Cannot find file");
5821 } else {
5822 die_error(400, "No file name defined");
5824 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5825 # blobs defined by non-textual hash id's can be cached
5826 $expires = "+1d";
5829 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5830 or die_error(500, "Open git-cat-file blob '$hash' failed");
5832 # content-type (can include charset)
5833 $type = blob_contenttype($fd, $file_name, $type);
5835 # "save as" filename, even when no $file_name is given
5836 my $save_as = "$hash";
5837 if (defined $file_name) {
5838 $save_as = $file_name;
5839 } elsif ($type =~ m/^text\//) {
5840 $save_as .= '.txt';
5843 # With XSS prevention on, blobs of all types except a few known safe
5844 # ones are served with "Content-Disposition: attachment" to make sure
5845 # they don't run in our security domain. For certain image types,
5846 # blob view writes an <img> tag referring to blob_plain view, and we
5847 # want to be sure not to break that by serving the image as an
5848 # attachment (though Firefox 3 doesn't seem to care).
5849 my $sandbox = $prevent_xss &&
5850 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5852 print $cgi->header(
5853 -type => $type,
5854 -expires => $expires,
5855 -content_disposition =>
5856 ($sandbox ? 'attachment' : 'inline')
5857 . '; filename="' . $save_as . '"');
5858 local $/ = undef;
5859 binmode STDOUT, ':raw';
5860 print <$fd>;
5861 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5862 close $fd;
5865 sub git_blob {
5866 my $expires;
5868 if (!defined $hash) {
5869 if (defined $file_name) {
5870 my $base = $hash_base || git_get_head_hash($project);
5871 $hash = git_get_hash_by_path($base, $file_name, "blob")
5872 or die_error(404, "Cannot find file");
5873 } else {
5874 die_error(400, "No file name defined");
5876 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5877 # blobs defined by non-textual hash id's can be cached
5878 $expires = "+1d";
5881 my $have_blame = gitweb_check_feature('blame');
5882 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5883 or die_error(500, "Couldn't cat $file_name, $hash");
5884 my $mimetype = blob_mimetype($fd, $file_name);
5885 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5886 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5887 close $fd;
5888 return git_blob_plain($mimetype);
5890 # we can have blame only for text/* mimetype
5891 $have_blame &&= ($mimetype =~ m!^text/!);
5893 my $highlight = gitweb_check_feature('highlight');
5894 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5895 $fd = run_highlighter($fd, $highlight, $syntax)
5896 if $syntax;
5898 git_header_html(undef, $expires);
5899 my $formats_nav = '';
5900 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5901 if (defined $file_name) {
5902 if ($have_blame) {
5903 $formats_nav .=
5904 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5905 "blame") .
5906 " | ";
5908 $formats_nav .=
5909 $cgi->a({-href => href(action=>"history", -replay=>1)},
5910 "history") .
5911 " | " .
5912 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5913 "raw") .
5914 " | " .
5915 $cgi->a({-href => href(action=>"blob",
5916 hash_base=>"HEAD", file_name=>$file_name)},
5917 "HEAD");
5918 } else {
5919 $formats_nav .=
5920 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5921 "raw");
5923 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5924 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5925 } else {
5926 print "<div class=\"page_nav\">\n" .
5927 "<br/><br/></div>\n" .
5928 "<div class=\"title\">$hash</div>\n";
5930 git_print_page_path($file_name, "blob", $hash_base);
5931 print "<div class=\"page_body\">\n";
5932 if ($mimetype =~ m!^image/!) {
5933 print qq!<img type="$mimetype"!;
5934 if ($file_name) {
5935 print qq! alt="$file_name" title="$file_name"!;
5937 print qq! src="! .
5938 href(action=>"blob_plain", hash=>$hash,
5939 hash_base=>$hash_base, file_name=>$file_name) .
5940 qq!" />\n!;
5941 } else {
5942 my $nr;
5943 while (my $line = <$fd>) {
5944 chomp $line;
5945 $nr++;
5946 $line = untabify($line);
5947 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5948 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5951 close $fd
5952 or print "Reading blob failed.\n";
5953 print "</div>";
5954 git_footer_html();
5957 sub git_tree {
5958 if (!defined $hash_base) {
5959 $hash_base = "HEAD";
5961 if (!defined $hash) {
5962 if (defined $file_name) {
5963 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5964 } else {
5965 $hash = $hash_base;
5968 die_error(404, "No such tree") unless defined($hash);
5970 my $show_sizes = gitweb_check_feature('show-sizes');
5971 my $have_blame = gitweb_check_feature('blame');
5973 my @entries = ();
5975 local $/ = "\0";
5976 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5977 ($show_sizes ? '-l' : ()), @extra_options, $hash
5978 or die_error(500, "Open git-ls-tree failed");
5979 @entries = map { chomp; $_ } <$fd>;
5980 close $fd
5981 or die_error(404, "Reading tree failed");
5984 my $refs = git_get_references();
5985 my $ref = format_ref_marker($refs, $hash_base);
5986 git_header_html();
5987 my $basedir = '';
5988 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5989 my @views_nav = ();
5990 if (defined $file_name) {
5991 push @views_nav,
5992 $cgi->a({-href => href(action=>"history", -replay=>1)},
5993 "history"),
5994 $cgi->a({-href => href(action=>"tree",
5995 hash_base=>"HEAD", file_name=>$file_name)},
5996 "HEAD"),
5998 my $snapshot_links = format_snapshot_links($hash);
5999 if (defined $snapshot_links) {
6000 # FIXME: Should be available when we have no hash base as well.
6001 push @views_nav, $snapshot_links;
6003 git_print_page_nav('tree','', $hash_base, undef, undef,
6004 join(' | ', @views_nav));
6005 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
6006 } else {
6007 undef $hash_base;
6008 print "<div class=\"page_nav\">\n";
6009 print "<br/><br/></div>\n";
6010 print "<div class=\"title\">$hash</div>\n";
6012 if (defined $file_name) {
6013 $basedir = $file_name;
6014 if ($basedir ne '' && substr($basedir, -1) ne '/') {
6015 $basedir .= '/';
6017 git_print_page_path($file_name, 'tree', $hash_base);
6019 print "<div class=\"page_body\">\n";
6020 print "<table class=\"tree\">\n";
6021 my $alternate = 1;
6022 # '..' (top directory) link if possible
6023 if (defined $hash_base &&
6024 defined $file_name && $file_name =~ m![^/]+$!) {
6025 if ($alternate) {
6026 print "<tr class=\"dark\">\n";
6027 } else {
6028 print "<tr class=\"light\">\n";
6030 $alternate ^= 1;
6032 my $up = $file_name;
6033 $up =~ s!/?[^/]+$!!;
6034 undef $up unless $up;
6035 # based on git_print_tree_entry
6036 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6037 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
6038 print '<td class="list">';
6039 print $cgi->a({-href => href(action=>"tree",
6040 hash_base=>$hash_base,
6041 file_name=>$up)},
6042 "..");
6043 print "</td>\n";
6044 print "<td class=\"link\"></td>\n";
6046 print "</tr>\n";
6048 foreach my $line (@entries) {
6049 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6051 if ($alternate) {
6052 print "<tr class=\"dark\">\n";
6053 } else {
6054 print "<tr class=\"light\">\n";
6056 $alternate ^= 1;
6058 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6060 print "</tr>\n";
6062 print "</table>\n" .
6063 "</div>";
6064 git_footer_html();
6067 sub snapshot_name {
6068 my ($project, $hash) = @_;
6070 # path/to/project.git -> project
6071 # path/to/project/.git -> project
6072 my $name = to_utf8($project);
6073 $name =~ s,([^/])/*\.git$,$1,;
6074 $name = basename($name);
6075 # sanitize name
6076 $name =~ s/[[:cntrl:]]/?/g;
6078 my $ver = $hash;
6079 if ($hash =~ /^[0-9a-fA-F]+$/) {
6080 # shorten SHA-1 hash
6081 my $full_hash = git_get_full_hash($project, $hash);
6082 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6083 $ver = git_get_short_hash($project, $hash);
6085 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6086 # tags don't need shortened SHA-1 hash
6087 $ver = $1;
6088 } else {
6089 # branches and other need shortened SHA-1 hash
6090 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6091 $ver = $1;
6093 $ver .= '-' . git_get_short_hash($project, $hash);
6095 # in case of hierarchical branch names
6096 $ver =~ s!/!.!g;
6098 # name = project-version_string
6099 $name = "$name-$ver";
6101 return wantarray ? ($name, $name) : $name;
6104 sub git_snapshot {
6105 my $format = $input_params{'snapshot_format'};
6106 if (!@snapshot_fmts) {
6107 die_error(403, "Snapshots not allowed");
6109 # default to first supported snapshot format
6110 $format ||= $snapshot_fmts[0];
6111 if ($format !~ m/^[a-z0-9]+$/) {
6112 die_error(400, "Invalid snapshot format parameter");
6113 } elsif (!exists($known_snapshot_formats{$format})) {
6114 die_error(400, "Unknown snapshot format");
6115 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6116 die_error(403, "Snapshot format not allowed");
6117 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6118 die_error(403, "Unsupported snapshot format");
6121 my $type = git_get_type("$hash^{}");
6122 if (!$type) {
6123 die_error(404, 'Object does not exist');
6124 } elsif ($type eq 'blob') {
6125 die_error(400, 'Object is not a tree-ish');
6128 my ($name, $prefix) = snapshot_name($project, $hash);
6129 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6130 my $cmd = quote_command(
6131 git_cmd(), 'archive',
6132 "--format=$known_snapshot_formats{$format}{'format'}",
6133 "--prefix=$prefix/", $hash);
6134 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6135 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6138 $filename =~ s/(["\\])/\\$1/g;
6139 print $cgi->header(
6140 -type => $known_snapshot_formats{$format}{'type'},
6141 -content_disposition => 'inline; filename="' . $filename . '"',
6142 -status => '200 OK');
6144 open my $fd, "-|", $cmd
6145 or die_error(500, "Execute git-archive failed");
6146 binmode STDOUT, ':raw';
6147 print <$fd>;
6148 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6149 close $fd;
6152 sub git_log_generic {
6153 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6155 my $head = git_get_head_hash($project);
6156 if (!defined $base) {
6157 $base = $head;
6159 if (!defined $page) {
6160 $page = 0;
6162 my $refs = git_get_references();
6164 my $commit_hash = $base;
6165 if (defined $parent) {
6166 $commit_hash = "$parent..$base";
6168 my @commitlist =
6169 parse_commits($commit_hash, 101, (100 * $page),
6170 defined $file_name ? ($file_name, "--full-history") : ());
6172 my $ftype;
6173 if (!defined $file_hash && defined $file_name) {
6174 # some commits could have deleted file in question,
6175 # and not have it in tree, but one of them has to have it
6176 for (my $i = 0; $i < @commitlist; $i++) {
6177 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6178 last if defined $file_hash;
6181 if (defined $file_hash) {
6182 $ftype = git_get_type($file_hash);
6184 if (defined $file_name && !defined $ftype) {
6185 die_error(500, "Unknown type of object");
6187 my %co;
6188 if (defined $file_name) {
6189 %co = parse_commit($base)
6190 or die_error(404, "Unknown commit object");
6194 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6195 my $next_link = '';
6196 if ($#commitlist >= 100) {
6197 $next_link =
6198 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6199 -accesskey => "n", -title => "Alt-n"}, "next");
6201 my $patch_max = gitweb_get_feature('patches');
6202 if ($patch_max && !defined $file_name) {
6203 if ($patch_max < 0 || @commitlist <= $patch_max) {
6204 $paging_nav .= " &sdot; " .
6205 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6206 "patches");
6210 git_header_html();
6211 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6212 if (defined $file_name) {
6213 git_print_header_div('commit', esc_html($co{'title'}), $base);
6214 } else {
6215 git_print_header_div('summary', $project)
6217 git_print_page_path($file_name, $ftype, $hash_base)
6218 if (defined $file_name);
6220 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6221 $file_name, $file_hash, $ftype);
6223 git_footer_html();
6226 sub git_log {
6227 git_log_generic('log', \&git_log_body,
6228 $hash, $hash_parent);
6231 sub git_commit {
6232 $hash ||= $hash_base || "HEAD";
6233 my %co = parse_commit($hash)
6234 or die_error(404, "Unknown commit object");
6236 my $parent = $co{'parent'};
6237 my $parents = $co{'parents'}; # listref
6239 # we need to prepare $formats_nav before any parameter munging
6240 my $formats_nav;
6241 if (!defined $parent) {
6242 # --root commitdiff
6243 $formats_nav .= '(initial)';
6244 } elsif (@$parents == 1) {
6245 # single parent commit
6246 $formats_nav .=
6247 '(parent: ' .
6248 $cgi->a({-href => href(action=>"commit",
6249 hash=>$parent)},
6250 esc_html(substr($parent, 0, 7))) .
6251 ')';
6252 } else {
6253 # merge commit
6254 $formats_nav .=
6255 '(merge: ' .
6256 join(' ', map {
6257 $cgi->a({-href => href(action=>"commit",
6258 hash=>$_)},
6259 esc_html(substr($_, 0, 7)));
6260 } @$parents ) .
6261 ')';
6263 if (gitweb_check_feature('patches') && @$parents <= 1) {
6264 $formats_nav .= " | " .
6265 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6266 "patch");
6269 if (!defined $parent) {
6270 $parent = "--root";
6272 my @difftree;
6273 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6274 @diff_opts,
6275 (@$parents <= 1 ? $parent : '-c'),
6276 $hash, "--"
6277 or die_error(500, "Open git-diff-tree failed");
6278 @difftree = map { chomp; $_ } <$fd>;
6279 close $fd or die_error(404, "Reading git-diff-tree failed");
6281 # non-textual hash id's can be cached
6282 my $expires;
6283 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6284 $expires = "+1d";
6286 my $refs = git_get_references();
6287 my $ref = format_ref_marker($refs, $co{'id'});
6289 git_header_html(undef, $expires);
6290 git_print_page_nav('commit', '',
6291 $hash, $co{'tree'}, $hash,
6292 $formats_nav);
6294 if (defined $co{'parent'}) {
6295 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6296 } else {
6297 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6299 print "<div class=\"title_text\">\n" .
6300 "<table class=\"object_header\">\n";
6301 git_print_authorship_rows(\%co);
6302 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6303 print "<tr>" .
6304 "<td>tree</td>" .
6305 "<td class=\"sha1\">" .
6306 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6307 class => "list"}, $co{'tree'}) .
6308 "</td>" .
6309 "<td class=\"link\">" .
6310 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6311 "tree");
6312 my $snapshot_links = format_snapshot_links($hash);
6313 if (defined $snapshot_links) {
6314 print " | " . $snapshot_links;
6316 print "</td>" .
6317 "</tr>\n";
6319 foreach my $par (@$parents) {
6320 print "<tr>" .
6321 "<td>parent</td>" .
6322 "<td class=\"sha1\">" .
6323 $cgi->a({-href => href(action=>"commit", hash=>$par),
6324 class => "list"}, $par) .
6325 "</td>" .
6326 "<td class=\"link\">" .
6327 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6328 " | " .
6329 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6330 "</td>" .
6331 "</tr>\n";
6333 print "</table>".
6334 "</div>\n";
6336 print "<div class=\"page_body\">\n";
6337 git_print_log($co{'comment'});
6338 print "</div>\n";
6340 git_difftree_body(\@difftree, $hash, @$parents);
6342 git_footer_html();
6345 sub git_object {
6346 # object is defined by:
6347 # - hash or hash_base alone
6348 # - hash_base and file_name
6349 my $type;
6351 # - hash or hash_base alone
6352 if ($hash || ($hash_base && !defined $file_name)) {
6353 my $object_id = $hash || $hash_base;
6355 open my $fd, "-|", quote_command(
6356 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6357 or die_error(404, "Object does not exist");
6358 $type = <$fd>;
6359 chomp $type;
6360 close $fd
6361 or die_error(404, "Object does not exist");
6363 # - hash_base and file_name
6364 } elsif ($hash_base && defined $file_name) {
6365 $file_name =~ s,/+$,,;
6367 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6368 or die_error(404, "Base object does not exist");
6370 # here errors should not hapen
6371 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6372 or die_error(500, "Open git-ls-tree failed");
6373 my $line = <$fd>;
6374 close $fd;
6376 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6377 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6378 die_error(404, "File or directory for given base does not exist");
6380 $type = $2;
6381 $hash = $3;
6382 } else {
6383 die_error(400, "Not enough information to find object");
6386 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6387 hash=>$hash, hash_base=>$hash_base,
6388 file_name=>$file_name),
6389 -status => '302 Found');
6392 sub git_blobdiff {
6393 my $format = shift || 'html';
6395 my $fd;
6396 my @difftree;
6397 my %diffinfo;
6398 my $expires;
6400 # preparing $fd and %diffinfo for git_patchset_body
6401 # new style URI
6402 if (defined $hash_base && defined $hash_parent_base) {
6403 if (defined $file_name) {
6404 # read raw output
6405 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6406 $hash_parent_base, $hash_base,
6407 "--", (defined $file_parent ? $file_parent : ()), $file_name
6408 or die_error(500, "Open git-diff-tree failed");
6409 @difftree = map { chomp; $_ } <$fd>;
6410 close $fd
6411 or die_error(404, "Reading git-diff-tree failed");
6412 @difftree
6413 or die_error(404, "Blob diff not found");
6415 } elsif (defined $hash &&
6416 $hash =~ /[0-9a-fA-F]{40}/) {
6417 # try to find filename from $hash
6419 # read filtered raw output
6420 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6421 $hash_parent_base, $hash_base, "--"
6422 or die_error(500, "Open git-diff-tree failed");
6423 @difftree =
6424 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6425 # $hash == to_id
6426 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6427 map { chomp; $_ } <$fd>;
6428 close $fd
6429 or die_error(404, "Reading git-diff-tree failed");
6430 @difftree
6431 or die_error(404, "Blob diff not found");
6433 } else {
6434 die_error(400, "Missing one of the blob diff parameters");
6437 if (@difftree > 1) {
6438 die_error(400, "Ambiguous blob diff specification");
6441 %diffinfo = parse_difftree_raw_line($difftree[0]);
6442 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6443 $file_name ||= $diffinfo{'to_file'};
6445 $hash_parent ||= $diffinfo{'from_id'};
6446 $hash ||= $diffinfo{'to_id'};
6448 # non-textual hash id's can be cached
6449 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6450 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6451 $expires = '+1d';
6454 # open patch output
6455 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6456 '-p', ($format eq 'html' ? "--full-index" : ()),
6457 $hash_parent_base, $hash_base,
6458 "--", (defined $file_parent ? $file_parent : ()), $file_name
6459 or die_error(500, "Open git-diff-tree failed");
6462 # old/legacy style URI -- not generated anymore since 1.4.3.
6463 if (!%diffinfo) {
6464 die_error('404 Not Found', "Missing one of the blob diff parameters")
6467 # header
6468 if ($format eq 'html') {
6469 my $formats_nav =
6470 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6471 "raw");
6472 git_header_html(undef, $expires);
6473 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6474 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6475 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6476 } else {
6477 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6478 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6480 if (defined $file_name) {
6481 git_print_page_path($file_name, "blob", $hash_base);
6482 } else {
6483 print "<div class=\"page_path\"></div>\n";
6486 } elsif ($format eq 'plain') {
6487 print $cgi->header(
6488 -type => 'text/plain',
6489 -charset => 'utf-8',
6490 -expires => $expires,
6491 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6493 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6495 } else {
6496 die_error(400, "Unknown blobdiff format");
6499 # patch
6500 if ($format eq 'html') {
6501 print "<div class=\"page_body\">\n";
6503 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6504 close $fd;
6506 print "</div>\n"; # class="page_body"
6507 git_footer_html();
6509 } else {
6510 while (my $line = <$fd>) {
6511 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6512 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6514 print $line;
6516 last if $line =~ m!^\+\+\+!;
6518 local $/ = undef;
6519 print <$fd>;
6520 close $fd;
6524 sub git_blobdiff_plain {
6525 git_blobdiff('plain');
6528 sub git_commitdiff {
6529 my %params = @_;
6530 my $format = $params{-format} || 'html';
6532 my ($patch_max) = gitweb_get_feature('patches');
6533 if ($format eq 'patch') {
6534 die_error(403, "Patch view not allowed") unless $patch_max;
6537 $hash ||= $hash_base || "HEAD";
6538 my %co = parse_commit($hash)
6539 or die_error(404, "Unknown commit object");
6541 # choose format for commitdiff for merge
6542 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6543 $hash_parent = '--cc';
6545 # we need to prepare $formats_nav before almost any parameter munging
6546 my $formats_nav;
6547 if ($format eq 'html') {
6548 $formats_nav =
6549 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6550 "raw");
6551 if ($patch_max && @{$co{'parents'}} <= 1) {
6552 $formats_nav .= " | " .
6553 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6554 "patch");
6557 if (defined $hash_parent &&
6558 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6559 # commitdiff with two commits given
6560 my $hash_parent_short = $hash_parent;
6561 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6562 $hash_parent_short = substr($hash_parent, 0, 7);
6564 $formats_nav .=
6565 ' (from';
6566 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6567 if ($co{'parents'}[$i] eq $hash_parent) {
6568 $formats_nav .= ' parent ' . ($i+1);
6569 last;
6572 $formats_nav .= ': ' .
6573 $cgi->a({-href => href(action=>"commitdiff",
6574 hash=>$hash_parent)},
6575 esc_html($hash_parent_short)) .
6576 ')';
6577 } elsif (!$co{'parent'}) {
6578 # --root commitdiff
6579 $formats_nav .= ' (initial)';
6580 } elsif (scalar @{$co{'parents'}} == 1) {
6581 # single parent commit
6582 $formats_nav .=
6583 ' (parent: ' .
6584 $cgi->a({-href => href(action=>"commitdiff",
6585 hash=>$co{'parent'})},
6586 esc_html(substr($co{'parent'}, 0, 7))) .
6587 ')';
6588 } else {
6589 # merge commit
6590 if ($hash_parent eq '--cc') {
6591 $formats_nav .= ' | ' .
6592 $cgi->a({-href => href(action=>"commitdiff",
6593 hash=>$hash, hash_parent=>'-c')},
6594 'combined');
6595 } else { # $hash_parent eq '-c'
6596 $formats_nav .= ' | ' .
6597 $cgi->a({-href => href(action=>"commitdiff",
6598 hash=>$hash, hash_parent=>'--cc')},
6599 'compact');
6601 $formats_nav .=
6602 ' (merge: ' .
6603 join(' ', map {
6604 $cgi->a({-href => href(action=>"commitdiff",
6605 hash=>$_)},
6606 esc_html(substr($_, 0, 7)));
6607 } @{$co{'parents'}} ) .
6608 ')';
6612 my $hash_parent_param = $hash_parent;
6613 if (!defined $hash_parent_param) {
6614 # --cc for multiple parents, --root for parentless
6615 $hash_parent_param =
6616 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6619 # read commitdiff
6620 my $fd;
6621 my @difftree;
6622 if ($format eq 'html') {
6623 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6624 "--no-commit-id", "--patch-with-raw", "--full-index",
6625 $hash_parent_param, $hash, "--"
6626 or die_error(500, "Open git-diff-tree failed");
6628 while (my $line = <$fd>) {
6629 chomp $line;
6630 # empty line ends raw part of diff-tree output
6631 last unless $line;
6632 push @difftree, scalar parse_difftree_raw_line($line);
6635 } elsif ($format eq 'plain') {
6636 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6637 '-p', $hash_parent_param, $hash, "--"
6638 or die_error(500, "Open git-diff-tree failed");
6639 } elsif ($format eq 'patch') {
6640 # For commit ranges, we limit the output to the number of
6641 # patches specified in the 'patches' feature.
6642 # For single commits, we limit the output to a single patch,
6643 # diverging from the git-format-patch default.
6644 my @commit_spec = ();
6645 if ($hash_parent) {
6646 if ($patch_max > 0) {
6647 push @commit_spec, "-$patch_max";
6649 push @commit_spec, '-n', "$hash_parent..$hash";
6650 } else {
6651 if ($params{-single}) {
6652 push @commit_spec, '-1';
6653 } else {
6654 if ($patch_max > 0) {
6655 push @commit_spec, "-$patch_max";
6657 push @commit_spec, "-n";
6659 push @commit_spec, '--root', $hash;
6661 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6662 '--encoding=utf8', '--stdout', @commit_spec
6663 or die_error(500, "Open git-format-patch failed");
6664 } else {
6665 die_error(400, "Unknown commitdiff format");
6668 # non-textual hash id's can be cached
6669 my $expires;
6670 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6671 $expires = "+1d";
6674 # write commit message
6675 if ($format eq 'html') {
6676 my $refs = git_get_references();
6677 my $ref = format_ref_marker($refs, $co{'id'});
6679 git_header_html(undef, $expires);
6680 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6681 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6682 print "<div class=\"title_text\">\n" .
6683 "<table class=\"object_header\">\n";
6684 git_print_authorship_rows(\%co);
6685 print "</table>".
6686 "</div>\n";
6687 print "<div class=\"page_body\">\n";
6688 if (@{$co{'comment'}} > 1) {
6689 print "<div class=\"log\">\n";
6690 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6691 print "</div>\n"; # class="log"
6694 } elsif ($format eq 'plain') {
6695 my $refs = git_get_references("tags");
6696 my $tagname = git_get_rev_name_tags($hash);
6697 my $filename = basename($project) . "-$hash.patch";
6699 print $cgi->header(
6700 -type => 'text/plain',
6701 -charset => 'utf-8',
6702 -expires => $expires,
6703 -content_disposition => 'inline; filename="' . "$filename" . '"');
6704 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6705 print "From: " . to_utf8($co{'author'}) . "\n";
6706 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6707 print "Subject: " . to_utf8($co{'title'}) . "\n";
6709 print "X-Git-Tag: $tagname\n" if $tagname;
6710 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6712 foreach my $line (@{$co{'comment'}}) {
6713 print to_utf8($line) . "\n";
6715 print "---\n\n";
6716 } elsif ($format eq 'patch') {
6717 my $filename = basename($project) . "-$hash.patch";
6719 print $cgi->header(
6720 -type => 'text/plain',
6721 -charset => 'utf-8',
6722 -expires => $expires,
6723 -content_disposition => 'inline; filename="' . "$filename" . '"');
6726 # write patch
6727 if ($format eq 'html') {
6728 my $use_parents = !defined $hash_parent ||
6729 $hash_parent eq '-c' || $hash_parent eq '--cc';
6730 git_difftree_body(\@difftree, $hash,
6731 $use_parents ? @{$co{'parents'}} : $hash_parent);
6732 print "<br/>\n";
6734 git_patchset_body($fd, \@difftree, $hash,
6735 $use_parents ? @{$co{'parents'}} : $hash_parent);
6736 close $fd;
6737 print "</div>\n"; # class="page_body"
6738 git_footer_html();
6740 } elsif ($format eq 'plain') {
6741 local $/ = undef;
6742 print <$fd>;
6743 close $fd
6744 or print "Reading git-diff-tree failed\n";
6745 } elsif ($format eq 'patch') {
6746 local $/ = undef;
6747 print <$fd>;
6748 close $fd
6749 or print "Reading git-format-patch failed\n";
6753 sub git_commitdiff_plain {
6754 git_commitdiff(-format => 'plain');
6757 # format-patch-style patches
6758 sub git_patch {
6759 git_commitdiff(-format => 'patch', -single => 1);
6762 sub git_patches {
6763 git_commitdiff(-format => 'patch');
6766 sub git_history {
6767 git_log_generic('history', \&git_history_body,
6768 $hash_base, $hash_parent_base,
6769 $file_name, $hash);
6772 sub git_search {
6773 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6774 if (!defined $searchtext) {
6775 die_error(400, "Text field is empty");
6777 if (!defined $hash) {
6778 $hash = git_get_head_hash($project);
6780 my %co = parse_commit($hash);
6781 if (!%co) {
6782 die_error(404, "Unknown commit object");
6784 if (!defined $page) {
6785 $page = 0;
6788 $searchtype ||= 'commit';
6789 if ($searchtype eq 'pickaxe') {
6790 # pickaxe may take all resources of your box and run for several minutes
6791 # with every query - so decide by yourself how public you make this feature
6792 gitweb_check_feature('pickaxe')
6793 or die_error(403, "Pickaxe is disabled");
6795 if ($searchtype eq 'grep') {
6796 gitweb_check_feature('grep')
6797 or die_error(403, "Grep is disabled");
6800 git_header_html();
6802 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6803 my $greptype;
6804 if ($searchtype eq 'commit') {
6805 $greptype = "--grep=";
6806 } elsif ($searchtype eq 'author') {
6807 $greptype = "--author=";
6808 } elsif ($searchtype eq 'committer') {
6809 $greptype = "--committer=";
6811 $greptype .= $searchtext;
6812 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6813 $greptype, '--regexp-ignore-case',
6814 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6816 my $paging_nav = '';
6817 if ($page > 0) {
6818 $paging_nav .=
6819 $cgi->a({-href => href(action=>"search", hash=>$hash,
6820 searchtext=>$searchtext,
6821 searchtype=>$searchtype)},
6822 "first");
6823 $paging_nav .= " &sdot; " .
6824 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6825 -accesskey => "p", -title => "Alt-p"}, "prev");
6826 } else {
6827 $paging_nav .= "first";
6828 $paging_nav .= " &sdot; prev";
6830 my $next_link = '';
6831 if ($#commitlist >= 100) {
6832 $next_link =
6833 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6834 -accesskey => "n", -title => "Alt-n"}, "next");
6835 $paging_nav .= " &sdot; $next_link";
6836 } else {
6837 $paging_nav .= " &sdot; next";
6840 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6841 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6842 if ($page == 0 && !@commitlist) {
6843 print "<p>No match.</p>\n";
6844 } else {
6845 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6849 if ($searchtype eq 'pickaxe') {
6850 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6851 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6853 print "<table class=\"pickaxe search\">\n";
6854 my $alternate = 1;
6855 local $/ = "\n";
6856 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6857 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6858 ($search_use_regexp ? '--pickaxe-regex' : ());
6859 undef %co;
6860 my @files;
6861 while (my $line = <$fd>) {
6862 chomp $line;
6863 next unless $line;
6865 my %set = parse_difftree_raw_line($line);
6866 if (defined $set{'commit'}) {
6867 # finish previous commit
6868 if (%co) {
6869 print "</td>\n" .
6870 "<td class=\"link\">" .
6871 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6872 " | " .
6873 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6874 print "</td>\n" .
6875 "</tr>\n";
6878 if ($alternate) {
6879 print "<tr class=\"dark\">\n";
6880 } else {
6881 print "<tr class=\"light\">\n";
6883 $alternate ^= 1;
6884 %co = parse_commit($set{'commit'});
6885 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6886 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6887 "<td><i>$author</i></td>\n" .
6888 "<td>" .
6889 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6890 -class => "list subject"},
6891 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6892 } elsif (defined $set{'to_id'}) {
6893 next if ($set{'to_id'} =~ m/^0{40}$/);
6895 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6896 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6897 -class => "list"},
6898 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6899 "<br/>\n";
6902 close $fd;
6904 # finish last commit (warning: repetition!)
6905 if (%co) {
6906 print "</td>\n" .
6907 "<td class=\"link\">" .
6908 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6909 " | " .
6910 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6911 print "</td>\n" .
6912 "</tr>\n";
6915 print "</table>\n";
6918 if ($searchtype eq 'grep') {
6919 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6920 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6922 print "<table class=\"grep_search\">\n";
6923 my $alternate = 1;
6924 my $matches = 0;
6925 local $/ = "\n";
6926 open my $fd, "-|", git_cmd(), 'grep', '-n',
6927 $search_use_regexp ? ('-E', '-i') : '-F',
6928 $searchtext, $co{'tree'};
6929 my $lastfile = '';
6930 while (my $line = <$fd>) {
6931 chomp $line;
6932 my ($file, $lno, $ltext, $binary);
6933 last if ($matches++ > 1000);
6934 if ($line =~ /^Binary file (.+) matches$/) {
6935 $file = $1;
6936 $binary = 1;
6937 } else {
6938 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6940 if ($file ne $lastfile) {
6941 $lastfile and print "</td></tr>\n";
6942 if ($alternate++) {
6943 print "<tr class=\"dark\">\n";
6944 } else {
6945 print "<tr class=\"light\">\n";
6947 print "<td class=\"list\">".
6948 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6949 file_name=>"$file"),
6950 -class => "list"}, esc_path($file));
6951 print "</td><td>\n";
6952 $lastfile = $file;
6954 if ($binary) {
6955 print "<div class=\"binary\">Binary file</div>\n";
6956 } else {
6957 $ltext = untabify($ltext);
6958 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6959 $ltext = esc_html($1, -nbsp=>1);
6960 $ltext .= '<span class="match">';
6961 $ltext .= esc_html($2, -nbsp=>1);
6962 $ltext .= '</span>';
6963 $ltext .= esc_html($3, -nbsp=>1);
6964 } else {
6965 $ltext = esc_html($ltext, -nbsp=>1);
6967 print "<div class=\"pre\">" .
6968 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6969 file_name=>"$file").'#l'.$lno,
6970 -class => "linenr"}, sprintf('%4i', $lno))
6971 . ' ' . $ltext . "</div>\n";
6974 if ($lastfile) {
6975 print "</td></tr>\n";
6976 if ($matches > 1000) {
6977 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6979 } else {
6980 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6982 close $fd;
6984 print "</table>\n";
6986 git_footer_html();
6989 sub git_search_help {
6990 git_header_html();
6991 git_print_page_nav('','', $hash,$hash,$hash);
6992 print <<EOT;
6993 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6994 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6995 the pattern entered is recognized as the POSIX extended
6996 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6997 insensitive).</p>
6998 <dl>
6999 <dt><b>commit</b></dt>
7000 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7002 my $have_grep = gitweb_check_feature('grep');
7003 if ($have_grep) {
7004 print <<EOT;
7005 <dt><b>grep</b></dt>
7006 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7007 a different one) are searched for the given pattern. On large trees, this search can take
7008 a while and put some strain on the server, so please use it with some consideration. Note that
7009 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7010 case-sensitive.</dd>
7013 print <<EOT;
7014 <dt><b>author</b></dt>
7015 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7016 <dt><b>committer</b></dt>
7017 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7019 my $have_pickaxe = gitweb_check_feature('pickaxe');
7020 if ($have_pickaxe) {
7021 print <<EOT;
7022 <dt><b>pickaxe</b></dt>
7023 <dd>All commits that caused the string to appear or disappear from any file (changes that
7024 added, removed or "modified" the string) will be listed. This search can take a while and
7025 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7026 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7029 print "</dl>\n";
7030 git_footer_html();
7033 sub git_shortlog {
7034 git_log_generic('shortlog', \&git_shortlog_body,
7035 $hash, $hash_parent);
7038 ## ......................................................................
7039 ## feeds (RSS, Atom; OPML)
7041 sub git_feed {
7042 my $format = shift || 'atom';
7043 my $have_blame = gitweb_check_feature('blame');
7045 # Atom: http://www.atomenabled.org/developers/syndication/
7046 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7047 if ($format ne 'rss' && $format ne 'atom') {
7048 die_error(400, "Unknown web feed format");
7051 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7052 my $head = $hash || 'HEAD';
7053 my @commitlist = parse_commits($head, 150, 0, $file_name);
7055 my %latest_commit;
7056 my %latest_date;
7057 my $content_type = "application/$format+xml";
7058 if (defined $cgi->http('HTTP_ACCEPT') &&
7059 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7060 # browser (feed reader) prefers text/xml
7061 $content_type = 'text/xml';
7063 if (defined($commitlist[0])) {
7064 %latest_commit = %{$commitlist[0]};
7065 my $latest_epoch = $latest_commit{'committer_epoch'};
7066 %latest_date = parse_date($latest_epoch);
7067 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7068 if (defined $if_modified) {
7069 my $since;
7070 if (eval { require HTTP::Date; 1; }) {
7071 $since = HTTP::Date::str2time($if_modified);
7072 } elsif (eval { require Time::ParseDate; 1; }) {
7073 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7075 if (defined $since && $latest_epoch <= $since) {
7076 print $cgi->header(
7077 -type => $content_type,
7078 -charset => 'utf-8',
7079 -last_modified => $latest_date{'rfc2822'},
7080 -status => '304 Not Modified');
7081 return;
7084 print $cgi->header(
7085 -type => $content_type,
7086 -charset => 'utf-8',
7087 -last_modified => $latest_date{'rfc2822'});
7088 } else {
7089 print $cgi->header(
7090 -type => $content_type,
7091 -charset => 'utf-8');
7094 # Optimization: skip generating the body if client asks only
7095 # for Last-Modified date.
7096 return if ($cgi->request_method() eq 'HEAD');
7098 # header variables
7099 my $title = "$site_name - $project/$action";
7100 my $feed_type = 'log';
7101 if (defined $hash) {
7102 $title .= " - '$hash'";
7103 $feed_type = 'branch log';
7104 if (defined $file_name) {
7105 $title .= " :: $file_name";
7106 $feed_type = 'history';
7108 } elsif (defined $file_name) {
7109 $title .= " - $file_name";
7110 $feed_type = 'history';
7112 $title .= " $feed_type";
7113 my $descr = git_get_project_description($project);
7114 if (defined $descr) {
7115 $descr = esc_html($descr);
7116 } else {
7117 $descr = "$project " .
7118 ($format eq 'rss' ? 'RSS' : 'Atom') .
7119 " feed";
7121 my $owner = git_get_project_owner($project);
7122 $owner = esc_html($owner);
7124 #header
7125 my $alt_url;
7126 if (defined $file_name) {
7127 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7128 } elsif (defined $hash) {
7129 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7130 } else {
7131 $alt_url = href(-full=>1, action=>"summary");
7133 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7134 if ($format eq 'rss') {
7135 print <<XML;
7136 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7137 <channel>
7139 print "<title>$title</title>\n" .
7140 "<link>$alt_url</link>\n" .
7141 "<description>$descr</description>\n" .
7142 "<language>en</language>\n" .
7143 # project owner is responsible for 'editorial' content
7144 "<managingEditor>$owner</managingEditor>\n";
7145 if (defined $logo || defined $favicon) {
7146 # prefer the logo to the favicon, since RSS
7147 # doesn't allow both
7148 my $img = esc_url($logo || $favicon);
7149 print "<image>\n" .
7150 "<url>$img</url>\n" .
7151 "<title>$title</title>\n" .
7152 "<link>$alt_url</link>\n" .
7153 "</image>\n";
7155 if (%latest_date) {
7156 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7157 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7159 print "<generator>gitweb v.$version/$git_version</generator>\n";
7160 } elsif ($format eq 'atom') {
7161 print <<XML;
7162 <feed xmlns="http://www.w3.org/2005/Atom">
7164 print "<title>$title</title>\n" .
7165 "<subtitle>$descr</subtitle>\n" .
7166 '<link rel="alternate" type="text/html" href="' .
7167 $alt_url . '" />' . "\n" .
7168 '<link rel="self" type="' . $content_type . '" href="' .
7169 $cgi->self_url() . '" />' . "\n" .
7170 "<id>" . href(-full=>1) . "</id>\n" .
7171 # use project owner for feed author
7172 "<author><name>$owner</name></author>\n";
7173 if (defined $favicon) {
7174 print "<icon>" . esc_url($favicon) . "</icon>\n";
7176 if (defined $logo_url) {
7177 # not twice as wide as tall: 72 x 27 pixels
7178 print "<logo>" . esc_url($logo) . "</logo>\n";
7180 if (! %latest_date) {
7181 # dummy date to keep the feed valid until commits trickle in:
7182 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7183 } else {
7184 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7186 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7189 # contents
7190 for (my $i = 0; $i <= $#commitlist; $i++) {
7191 my %co = %{$commitlist[$i]};
7192 my $commit = $co{'id'};
7193 # we read 150, we always show 30 and the ones more recent than 48 hours
7194 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7195 last;
7197 my %cd = parse_date($co{'author_epoch'});
7199 # get list of changed files
7200 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7201 $co{'parent'} || "--root",
7202 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7203 or next;
7204 my @difftree = map { chomp; $_ } <$fd>;
7205 close $fd
7206 or next;
7208 # print element (entry, item)
7209 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7210 if ($format eq 'rss') {
7211 print "<item>\n" .
7212 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7213 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7214 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7215 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7216 "<link>$co_url</link>\n" .
7217 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7218 "<content:encoded>" .
7219 "<![CDATA[\n";
7220 } elsif ($format eq 'atom') {
7221 print "<entry>\n" .
7222 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7223 "<updated>$cd{'iso-8601'}</updated>\n" .
7224 "<author>\n" .
7225 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7226 if ($co{'author_email'}) {
7227 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7229 print "</author>\n" .
7230 # use committer for contributor
7231 "<contributor>\n" .
7232 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7233 if ($co{'committer_email'}) {
7234 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7236 print "</contributor>\n" .
7237 "<published>$cd{'iso-8601'}</published>\n" .
7238 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7239 "<id>$co_url</id>\n" .
7240 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7241 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7243 my $comment = $co{'comment'};
7244 print "<pre>\n";
7245 foreach my $line (@$comment) {
7246 $line = esc_html($line);
7247 print "$line\n";
7249 print "</pre><ul>\n";
7250 foreach my $difftree_line (@difftree) {
7251 my %difftree = parse_difftree_raw_line($difftree_line);
7252 next if !$difftree{'from_id'};
7254 my $file = $difftree{'file'} || $difftree{'to_file'};
7256 print "<li>" .
7257 "[" .
7258 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7259 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7260 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7261 file_name=>$file, file_parent=>$difftree{'from_file'}),
7262 -title => "diff"}, 'D');
7263 if ($have_blame) {
7264 print $cgi->a({-href => href(-full=>1, action=>"blame",
7265 file_name=>$file, hash_base=>$commit),
7266 -title => "blame"}, 'B');
7268 # if this is not a feed of a file history
7269 if (!defined $file_name || $file_name ne $file) {
7270 print $cgi->a({-href => href(-full=>1, action=>"history",
7271 file_name=>$file, hash=>$commit),
7272 -title => "history"}, 'H');
7274 $file = esc_path($file);
7275 print "] ".
7276 "$file</li>\n";
7278 if ($format eq 'rss') {
7279 print "</ul>]]>\n" .
7280 "</content:encoded>\n" .
7281 "</item>\n";
7282 } elsif ($format eq 'atom') {
7283 print "</ul>\n</div>\n" .
7284 "</content>\n" .
7285 "</entry>\n";
7289 # end of feed
7290 if ($format eq 'rss') {
7291 print "</channel>\n</rss>\n";
7292 } elsif ($format eq 'atom') {
7293 print "</feed>\n";
7297 sub git_rss {
7298 git_feed('rss');
7301 sub git_atom {
7302 git_feed('atom');
7305 sub git_opml {
7306 my @list = git_get_projects_list();
7308 print $cgi->header(
7309 -type => 'text/xml',
7310 -charset => 'utf-8',
7311 -content_disposition => 'inline; filename="opml.xml"');
7313 print <<XML;
7314 <?xml version="1.0" encoding="utf-8"?>
7315 <opml version="1.0">
7316 <head>
7317 <title>$site_name OPML Export</title>
7318 </head>
7319 <body>
7320 <outline text="git RSS feeds">
7323 foreach my $pr (@list) {
7324 my %proj = %$pr;
7325 my $head = git_get_head_hash($proj{'path'});
7326 if (!defined $head) {
7327 next;
7329 $git_dir = "$projectroot/$proj{'path'}";
7330 my %co = parse_commit($head);
7331 if (!%co) {
7332 next;
7335 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7336 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7337 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7338 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7340 print <<XML;
7341 </outline>
7342 </body>
7343 </opml>