gitweb/lib - Regenerate (refresh) cache in background
[git/jnareb-git.git] / gitweb / gitweb.perl
blobc5ba1d4f1e20187e1e4f392c9c3b510515c2ce35
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use 5.008;
11 use strict;
12 use warnings;
14 use File::Spec;
15 # __DIR__ is taken from Dir::Self __DIR__ fragment
16 sub __DIR__ () {
17 File::Spec->rel2abs(join '', (File::Spec->splitpath(__FILE__))[0, 1]);
19 use lib __DIR__ . '/lib';
21 use CGI qw(:standard :escapeHTML -nosticky);
22 use CGI::Util qw(unescape);
23 use CGI::Carp qw(fatalsToBrowser set_message);
24 use Encode;
25 use Fcntl ':mode';
26 use File::Find qw();
27 use File::Basename qw(basename);
28 binmode STDOUT, ':utf8';
30 our $t0;
31 if (eval { require Time::HiRes; 1; }) {
32 $t0 = [Time::HiRes::gettimeofday()];
34 our $number_of_git_cmds = 0;
36 BEGIN {
37 CGI->compile() if $ENV{'MOD_PERL'};
40 our $version = "++GIT_VERSION++";
42 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
43 sub evaluate_uri {
44 our $cgi;
46 our $my_url = $cgi->url();
47 our $my_uri = $cgi->url(-absolute => 1);
49 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
50 # needed and used only for URLs with nonempty PATH_INFO
51 our $base_url = $my_url;
53 # When the script is used as DirectoryIndex, the URL does not contain the name
54 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
55 # have to do it ourselves. We make $path_info global because it's also used
56 # later on.
58 # Another issue with the script being the DirectoryIndex is that the resulting
59 # $my_url data is not the full script URL: this is good, because we want
60 # generated links to keep implying the script name if it wasn't explicitly
61 # indicated in the URL we're handling, but it means that $my_url cannot be used
62 # as base URL.
63 # Therefore, if we needed to strip PATH_INFO, then we know that we have
64 # to build the base URL ourselves:
65 our $path_info = $ENV{"PATH_INFO"};
66 if ($path_info) {
67 if ($my_url =~ s,\Q$path_info\E$,, &&
68 $my_uri =~ s,\Q$path_info\E$,, &&
69 defined $ENV{'SCRIPT_NAME'}) {
70 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
74 # target of the home link on top of all pages
75 our $home_link = $my_uri || "/";
78 # core git executable to use
79 # this can just be "git" if your webserver has a sensible PATH
80 our $GIT = "++GIT_BINDIR++/git";
82 # absolute fs-path which will be prepended to the project path
83 #our $projectroot = "/pub/scm";
84 our $projectroot = "++GITWEB_PROJECTROOT++";
86 # fs traversing limit for getting project list
87 # the number is relative to the projectroot
88 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
90 # string of the home link on top of all pages
91 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
93 # name of your site or organization to appear in page titles
94 # replace this with something more descriptive for clearer bookmarks
95 our $site_name = "++GITWEB_SITENAME++"
96 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
98 # filename of html text to include at top of each page
99 our $site_header = "++GITWEB_SITE_HEADER++";
100 # html text to include at home page
101 our $home_text = "++GITWEB_HOMETEXT++";
102 # filename of html text to include at bottom of each page
103 our $site_footer = "++GITWEB_SITE_FOOTER++";
105 # URI of stylesheets
106 our @stylesheets = ("++GITWEB_CSS++");
107 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
108 our $stylesheet = undef;
109 # URI of GIT logo (72x27 size)
110 our $logo = "++GITWEB_LOGO++";
111 # URI of GIT favicon, assumed to be image/png type
112 our $favicon = "++GITWEB_FAVICON++";
113 # URI of gitweb.js (JavaScript code for gitweb)
114 our $javascript = "++GITWEB_JS++";
116 # URI and label (title) of GIT logo link
117 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
118 #our $logo_label = "git documentation";
119 our $logo_url = "http://git-scm.com/";
120 our $logo_label = "git homepage";
122 # source of projects list
123 our $projects_list = "++GITWEB_LIST++";
125 # the width (in characters) of the projects list "Description" column
126 our $projects_list_description_width = 25;
128 # default order of projects list
129 # valid values are none, project, descr, owner, and age
130 our $default_projects_order = "project";
132 # show repository only if this file exists
133 # (only effective if this variable evaluates to true)
134 our $export_ok = "++GITWEB_EXPORT_OK++";
136 # show repository only if this subroutine returns true
137 # when given the path to the project, for example:
138 # sub { return -e "$_[0]/git-daemon-export-ok"; }
139 our $export_auth_hook = undef;
141 # only allow viewing of repositories also shown on the overview page
142 our $strict_export = "++GITWEB_STRICT_EXPORT++";
144 # list of git base URLs used for URL to where fetch project from,
145 # i.e. full URL is "$git_base_url/$project"
146 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
148 # default blob_plain mimetype and default charset for text/plain blob
149 our $default_blob_plain_mimetype = 'text/plain';
150 our $default_text_plain_charset = undef;
152 # file to use for guessing MIME types before trying /etc/mime.types
153 # (relative to the current git repository)
154 our $mimetypes_file = undef;
156 # assume this charset if line contains non-UTF-8 characters;
157 # it should be valid encoding (see Encoding::Supported(3pm) for list),
158 # for which encoding all byte sequences are valid, for example
159 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
160 # could be even 'utf-8' for the old behavior)
161 our $fallback_encoding = 'latin1';
163 # rename detection options for git-diff and git-diff-tree
164 # - default is '-M', with the cost proportional to
165 # (number of removed files) * (number of new files).
166 # - more costly is '-C' (which implies '-M'), with the cost proportional to
167 # (number of changed files + number of removed files) * (number of new files)
168 # - even more costly is '-C', '--find-copies-harder' with cost
169 # (number of files in the original tree) * (number of new files)
170 # - one might want to include '-B' option, e.g. '-B', '-M'
171 our @diff_opts = ('-M'); # taken from git_commit
173 # Disables features that would allow repository owners to inject script into
174 # the gitweb domain.
175 our $prevent_xss = 0;
177 # Path to the highlight executable to use (must be the one from
178 # http://www.andre-simon.de due to assumptions about parameters and output).
179 # Useful if highlight is not installed on your webserver's PATH.
180 # [Default: highlight]
181 our $highlight_bin = "++HIGHLIGHT_BIN++";
183 # information about snapshot formats that gitweb is capable of serving
184 our %known_snapshot_formats = (
185 # name => {
186 # 'display' => display name,
187 # 'type' => mime type,
188 # 'suffix' => filename suffix,
189 # 'format' => --format for git-archive,
190 # 'compressor' => [compressor command and arguments]
191 # (array reference, optional)
192 # 'disabled' => boolean (optional)}
194 'tgz' => {
195 'display' => 'tar.gz',
196 'type' => 'application/x-gzip',
197 'suffix' => '.tar.gz',
198 'format' => 'tar',
199 'compressor' => ['gzip']},
201 'tbz2' => {
202 'display' => 'tar.bz2',
203 'type' => 'application/x-bzip2',
204 'suffix' => '.tar.bz2',
205 'format' => 'tar',
206 'compressor' => ['bzip2']},
208 'txz' => {
209 'display' => 'tar.xz',
210 'type' => 'application/x-xz',
211 'suffix' => '.tar.xz',
212 'format' => 'tar',
213 'compressor' => ['xz'],
214 'disabled' => 1},
216 'zip' => {
217 'display' => 'zip',
218 'type' => 'application/x-zip',
219 'suffix' => '.zip',
220 'format' => 'zip'},
223 # Aliases so we understand old gitweb.snapshot values in repository
224 # configuration.
225 our %known_snapshot_format_aliases = (
226 'gzip' => 'tgz',
227 'bzip2' => 'tbz2',
228 'xz' => 'txz',
230 # backward compatibility: legacy gitweb config support
231 'x-gzip' => undef, 'gz' => undef,
232 'x-bzip2' => undef, 'bz2' => undef,
233 'x-zip' => undef, '' => undef,
236 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
237 # are changed, it may be appropriate to change these values too via
238 # $GITWEB_CONFIG.
239 our %avatar_size = (
240 'default' => 16,
241 'double' => 32
244 # Used to set the maximum load that we will still respond to gitweb queries.
245 # If server load exceed this value then return "503 server busy" error.
246 # If gitweb cannot determined server load, it is taken to be 0.
247 # Leave it undefined (or set to 'undef') to turn off load checking.
248 our $maxload = 300;
250 # configuration for 'highlight' (http://www.andre-simon.de/)
251 # match by basename
252 our %highlight_basename = (
253 #'Program' => 'py',
254 #'Library' => 'py',
255 'SConstruct' => 'py', # SCons equivalent of Makefile
256 'Makefile' => 'make',
258 # match by extension
259 our %highlight_ext = (
260 # main extensions, defining name of syntax;
261 # see files in /usr/share/highlight/langDefs/ directory
262 map { $_ => $_ }
263 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl),
264 # alternate extensions, see /etc/highlight/filetypes.conf
265 'h' => 'c',
266 map { $_ => 'cpp' } qw(cxx c++ cc),
267 map { $_ => 'php' } qw(php3 php4),
268 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
269 'mak' => 'make',
270 map { $_ => 'xml' } qw(xhtml html htm),
274 # This enables/disables the caching layer in gitweb. Currently supported
275 # is only output (response) caching, similar to the one used on git.kernel.org.
276 our $caching_enabled = 0;
277 # Set to _initialized_ instance of cache interface implementing (at least)
278 # get($key) and set($key, $data) methods (Cache::Cache and CHI interfaces),
279 # or to name of class of cache interface implementing said methods.
280 # If unset, GitwebCache::FileCacheWithLocking would be used, which is 'dumb'
281 # (but fast) file based caching layer, currently without any support for
282 # cache size limiting. It is therefore recommended that the cache directory
283 # be periodically completely deleted; this operation is safe to perform.
284 # Suggested mechanism:
285 # mv $cachedir $cachedir.flush && mkdir $cachedir && rm -rf $cachedir.flush
286 our $cache;
287 # You define site-wide cache options defaults here; override them with
288 # $GITWEB_CONFIG as necessary.
289 our %cache_options = (
290 # The location in the filesystem that will hold the root of the cache.
291 # This directory will be created as needed (if possible) on the first
292 # cache set. Note that either this directory must exists and web server
293 # has to have write permissions to it, or web server must be able to
294 # create this directory.
295 # Possible values:
296 # * 'cache' (relative to gitweb),
297 # * File::Spec->catdir(File::Spec->tmpdir(), 'gitweb-cache'),
298 # * '/var/cache/gitweb' (FHS compliant, requires being set up),
299 'cache_root' => 'cache',
301 # The number of subdirectories deep to cache object item. This should be
302 # large enough that no cache directory has more than a few hundred
303 # objects. Each non-leaf directory contains up to 256 subdirectories
304 # (00-ff). Must be larger than 0.
305 'cache_depth' => 1,
307 # The (global) minimum expiration time for objects placed in the cache,
308 # in seconds. If the dynamic adaptive cache exporation time is lower
309 # than this number, we set cache timeout to this minimum.
310 'expires_min' => 20, # 20 seconds
312 # The (global) maximum expiration time for dynamic (adaptive) caching
313 # algorithm, in seconds. If the adaptive cache lifetime exceeds this
314 # number, we set cache timeout to this maximum.
315 # (If 'expires_min' >= 'expires_max', there is no adaptive cache timeout,
316 # and 'expires_min' is used as expiration time for objects in cache.)
317 'expires_max' => 1200, # 20 minutes
319 # Cache lifetime will be increased by applying this factor to the result
320 # from 'check_load' callback (see below).
321 'expires_factor' => 60, # expire time in seconds for 1.0 (100% CPU) load
323 # User supplied callback for deciding the cache policy, usually system
324 # load. Multiplied by 'expires_factor' gives adaptive expiration time,
325 # in seconds, subject to the limits imposed by 'expires_min' and
326 # 'expires_max' bounds. Set to undef (or delete) to turn off dynamic
327 # lifetime control.
328 # (Compatibile with Cache::Adaptive.)
329 'check_load' => \&get_loadavg,
331 # 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 # Set to _initialized_ instance of GitwebCache::Capture compatibile capturing
349 # engine, i.e. one implementing ->new() constructor, and ->capture($code)
350 # method. If unset (default), the GitwebCache::Capture::Simple would be used.
351 our $capture;
353 # You define site-wide feature defaults here; override them with
354 # $GITWEB_CONFIG as necessary.
355 our %feature = (
356 # feature => {
357 # 'sub' => feature-sub (subroutine),
358 # 'override' => allow-override (boolean),
359 # 'default' => [ default options...] (array reference)}
361 # if feature is overridable (it means that allow-override has true value),
362 # then feature-sub will be called with default options as parameters;
363 # return value of feature-sub indicates if to enable specified feature
365 # if there is no 'sub' key (no feature-sub), then feature cannot be
366 # overridden
368 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
369 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
370 # is enabled
372 # Enable the 'blame' blob view, showing the last commit that modified
373 # each line in the file. This can be very CPU-intensive.
375 # To enable system wide have in $GITWEB_CONFIG
376 # $feature{'blame'}{'default'} = [1];
377 # To have project specific config enable override in $GITWEB_CONFIG
378 # $feature{'blame'}{'override'} = 1;
379 # and in project config gitweb.blame = 0|1;
380 'blame' => {
381 'sub' => sub { feature_bool('blame', @_) },
382 'override' => 0,
383 'default' => [0]},
385 # Enable the 'snapshot' link, providing a compressed archive of any
386 # tree. This can potentially generate high traffic if you have large
387 # project.
389 # Value is a list of formats defined in %known_snapshot_formats that
390 # you wish to offer.
391 # To disable system wide have in $GITWEB_CONFIG
392 # $feature{'snapshot'}{'default'} = [];
393 # To have project specific config enable override in $GITWEB_CONFIG
394 # $feature{'snapshot'}{'override'} = 1;
395 # and in project config, a comma-separated list of formats or "none"
396 # to disable. Example: gitweb.snapshot = tbz2,zip;
397 'snapshot' => {
398 'sub' => \&feature_snapshot,
399 'override' => 0,
400 'default' => ['tgz']},
402 # Enable text search, which will list the commits which match author,
403 # committer or commit text to a given string. Enabled by default.
404 # Project specific override is not supported.
405 'search' => {
406 'override' => 0,
407 'default' => [1]},
409 # Enable grep search, which will list the files in currently selected
410 # tree containing the given string. Enabled by default. This can be
411 # potentially CPU-intensive, of course.
413 # To enable system wide have in $GITWEB_CONFIG
414 # $feature{'grep'}{'default'} = [1];
415 # To have project specific config enable override in $GITWEB_CONFIG
416 # $feature{'grep'}{'override'} = 1;
417 # and in project config gitweb.grep = 0|1;
418 'grep' => {
419 'sub' => sub { feature_bool('grep', @_) },
420 'override' => 0,
421 'default' => [1]},
423 # Enable the pickaxe search, which will list the commits that modified
424 # a given string in a file. This can be practical and quite faster
425 # alternative to 'blame', but still potentially CPU-intensive.
427 # To enable system wide have in $GITWEB_CONFIG
428 # $feature{'pickaxe'}{'default'} = [1];
429 # To have project specific config enable override in $GITWEB_CONFIG
430 # $feature{'pickaxe'}{'override'} = 1;
431 # and in project config gitweb.pickaxe = 0|1;
432 'pickaxe' => {
433 'sub' => sub { feature_bool('pickaxe', @_) },
434 'override' => 0,
435 'default' => [1]},
437 # Enable showing size of blobs in a 'tree' view, in a separate
438 # column, similar to what 'ls -l' does. This cost a bit of IO.
440 # To disable system wide have in $GITWEB_CONFIG
441 # $feature{'show-sizes'}{'default'} = [0];
442 # To have project specific config enable override in $GITWEB_CONFIG
443 # $feature{'show-sizes'}{'override'} = 1;
444 # and in project config gitweb.showsizes = 0|1;
445 'show-sizes' => {
446 'sub' => sub { feature_bool('showsizes', @_) },
447 'override' => 0,
448 'default' => [1]},
450 # Make gitweb use an alternative format of the URLs which can be
451 # more readable and natural-looking: project name is embedded
452 # directly in the path and the query string contains other
453 # auxiliary information. All gitweb installations recognize
454 # URL in either format; this configures in which formats gitweb
455 # generates links.
457 # To enable system wide have in $GITWEB_CONFIG
458 # $feature{'pathinfo'}{'default'} = [1];
459 # Project specific override is not supported.
461 # Note that you will need to change the default location of CSS,
462 # favicon, logo and possibly other files to an absolute URL. Also,
463 # if gitweb.cgi serves as your indexfile, you will need to force
464 # $my_uri to contain the script name in your $GITWEB_CONFIG.
465 'pathinfo' => {
466 'override' => 0,
467 'default' => [0]},
469 # Make gitweb consider projects in project root subdirectories
470 # to be forks of existing projects. Given project $projname.git,
471 # projects matching $projname/*.git will not be shown in the main
472 # projects list, instead a '+' mark will be added to $projname
473 # there and a 'forks' view will be enabled for the project, listing
474 # all the forks. If project list is taken from a file, forks have
475 # to be listed after the main project.
477 # To enable system wide have in $GITWEB_CONFIG
478 # $feature{'forks'}{'default'} = [1];
479 # Project specific override is not supported.
480 'forks' => {
481 'override' => 0,
482 'default' => [0]},
484 # Insert custom links to the action bar of all project pages.
485 # This enables you mainly to link to third-party scripts integrating
486 # into gitweb; e.g. git-browser for graphical history representation
487 # or custom web-based repository administration interface.
489 # The 'default' value consists of a list of triplets in the form
490 # (label, link, position) where position is the label after which
491 # to insert the link and link is a format string where %n expands
492 # to the project name, %f to the project path within the filesystem,
493 # %h to the current hash (h gitweb parameter) and %b to the current
494 # hash base (hb gitweb parameter); %% expands to %.
496 # To enable system wide have in $GITWEB_CONFIG e.g.
497 # $feature{'actions'}{'default'} = [('graphiclog',
498 # '/git-browser/by-commit.html?r=%n', 'summary')];
499 # Project specific override is not supported.
500 'actions' => {
501 'override' => 0,
502 'default' => []},
504 # Allow gitweb scan project content tags described in ctags/
505 # of project repository, and display the popular Web 2.0-ish
506 # "tag cloud" near the project list. Note that this is something
507 # COMPLETELY different from the normal Git tags.
509 # gitweb by itself can show existing tags, but it does not handle
510 # tagging itself; you need an external application for that.
511 # For an example script, check Girocco's cgi/tagproj.cgi.
512 # You may want to install the HTML::TagCloud Perl module to get
513 # a pretty tag cloud instead of just a list of tags.
515 # To enable system wide have in $GITWEB_CONFIG
516 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
517 # Project specific override is not supported.
518 'ctags' => {
519 'override' => 0,
520 'default' => [0]},
522 # The maximum number of patches in a patchset generated in patch
523 # view. Set this to 0 or undef to disable patch view, or to a
524 # negative number to remove any limit.
526 # To disable system wide have in $GITWEB_CONFIG
527 # $feature{'patches'}{'default'} = [0];
528 # To have project specific config enable override in $GITWEB_CONFIG
529 # $feature{'patches'}{'override'} = 1;
530 # and in project config gitweb.patches = 0|n;
531 # where n is the maximum number of patches allowed in a patchset.
532 'patches' => {
533 'sub' => \&feature_patches,
534 'override' => 0,
535 'default' => [16]},
537 # Avatar support. When this feature is enabled, views such as
538 # shortlog or commit will display an avatar associated with
539 # the email of the committer(s) and/or author(s).
541 # Currently available providers are gravatar and picon.
542 # If an unknown provider is specified, the feature is disabled.
544 # Gravatar depends on Digest::MD5.
545 # Picon currently relies on the indiana.edu database.
547 # To enable system wide have in $GITWEB_CONFIG
548 # $feature{'avatar'}{'default'} = ['<provider>'];
549 # where <provider> is either gravatar or picon.
550 # To have project specific config enable override in $GITWEB_CONFIG
551 # $feature{'avatar'}{'override'} = 1;
552 # and in project config gitweb.avatar = <provider>;
553 'avatar' => {
554 'sub' => \&feature_avatar,
555 'override' => 0,
556 'default' => ['']},
558 # Enable displaying how much time and how many git commands
559 # it took to generate and display page. Disabled by default.
560 # Project specific override is not supported.
561 'timed' => {
562 'override' => 0,
563 'default' => [0]},
565 # Enable turning some links into links to actions which require
566 # JavaScript to run (like 'blame_incremental'). Not enabled by
567 # default. Project specific override is currently not supported.
568 'javascript-actions' => {
569 'override' => 0,
570 'default' => [0]},
572 # Syntax highlighting support. This is based on Daniel Svensson's
573 # and Sham Chukoury's work in gitweb-xmms2.git.
574 # It requires the 'highlight' program present in $PATH,
575 # and therefore is disabled by default.
577 # To enable system wide have in $GITWEB_CONFIG
578 # $feature{'highlight'}{'default'} = [1];
580 'highlight' => {
581 'sub' => sub { feature_bool('highlight', @_) },
582 'override' => 0,
583 'default' => [0]},
586 sub gitweb_get_feature {
587 my ($name) = @_;
588 return unless exists $feature{$name};
589 my ($sub, $override, @defaults) = (
590 $feature{$name}{'sub'},
591 $feature{$name}{'override'},
592 @{$feature{$name}{'default'}});
593 # project specific override is possible only if we have project
594 our $git_dir; # global variable, declared later
595 if (!$override || !defined $git_dir) {
596 return @defaults;
598 if (!defined $sub) {
599 warn "feature $name is not overridable";
600 return @defaults;
602 return $sub->(@defaults);
605 # A wrapper to check if a given feature is enabled.
606 # With this, you can say
608 # my $bool_feat = gitweb_check_feature('bool_feat');
609 # gitweb_check_feature('bool_feat') or somecode;
611 # instead of
613 # my ($bool_feat) = gitweb_get_feature('bool_feat');
614 # (gitweb_get_feature('bool_feat'))[0] or somecode;
616 sub gitweb_check_feature {
617 return (gitweb_get_feature(@_))[0];
621 sub feature_bool {
622 my $key = shift;
623 my ($val) = git_get_project_config($key, '--bool');
625 if (!defined $val) {
626 return ($_[0]);
627 } elsif ($val eq 'true') {
628 return (1);
629 } elsif ($val eq 'false') {
630 return (0);
634 sub feature_snapshot {
635 my (@fmts) = @_;
637 my ($val) = git_get_project_config('snapshot');
639 if ($val) {
640 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
643 return @fmts;
646 sub feature_patches {
647 my @val = (git_get_project_config('patches', '--int'));
649 if (@val) {
650 return @val;
653 return ($_[0]);
656 sub feature_avatar {
657 my @val = (git_get_project_config('avatar'));
659 return @val ? @val : @_;
662 # checking HEAD file with -e is fragile if the repository was
663 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
664 # and then pruned.
665 sub check_head_link {
666 my ($dir) = @_;
667 my $headfile = "$dir/HEAD";
668 return ((-e $headfile) ||
669 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
672 sub check_export_ok {
673 my ($dir) = @_;
674 return (check_head_link($dir) &&
675 (!$export_ok || -e "$dir/$export_ok") &&
676 (!$export_auth_hook || $export_auth_hook->($dir)));
679 # process alternate names for backward compatibility
680 # filter out unsupported (unknown) snapshot formats
681 sub filter_snapshot_fmts {
682 my @fmts = @_;
684 @fmts = map {
685 exists $known_snapshot_format_aliases{$_} ?
686 $known_snapshot_format_aliases{$_} : $_} @fmts;
687 @fmts = grep {
688 exists $known_snapshot_formats{$_} &&
689 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
692 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
693 sub evaluate_gitweb_config {
694 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
695 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
696 # die if there are errors parsing config file
697 if (-e $GITWEB_CONFIG) {
698 do $GITWEB_CONFIG;
699 die $@ if $@;
700 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
701 do $GITWEB_CONFIG_SYSTEM;
702 die $@ if $@;
706 # Get loadavg of system, to compare against $maxload.
707 # Currently it requires '/proc/loadavg' present to get loadavg;
708 # if it is not present it returns 0, which means no load checking.
709 sub get_loadavg {
710 if( -e '/proc/loadavg' ){
711 open my $fd, '<', '/proc/loadavg'
712 or return 0;
713 my @load = split(/\s+/, scalar <$fd>);
714 close $fd;
716 # The first three columns measure CPU and IO utilization of the last one,
717 # five, and 10 minute periods. The fourth column shows the number of
718 # currently running processes and the total number of processes in the m/n
719 # format. The last column displays the last process ID used.
720 return $load[0] || 0;
722 # additional checks for load average should go here for things that don't export
723 # /proc/loadavg
725 return 0;
728 # version of the core git binary
729 our $git_version;
730 sub evaluate_git_version {
731 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
732 $number_of_git_cmds++;
735 sub check_loadavg {
736 if (defined $maxload && get_loadavg() > $maxload) {
737 die_error(503, "The load average on the server is too high");
741 # ======================================================================
742 # input validation and dispatch
744 # input parameters can be collected from a variety of sources (presently, CGI
745 # and PATH_INFO), so we define an %input_params hash that collects them all
746 # together during validation: this allows subsequent uses (e.g. href()) to be
747 # agnostic of the parameter origin
749 our %input_params = ();
751 # input parameters are stored with the long parameter name as key. This will
752 # also be used in the href subroutine to convert parameters to their CGI
753 # equivalent, and since the href() usage is the most frequent one, we store
754 # the name -> CGI key mapping here, instead of the reverse.
756 # XXX: Warning: If you touch this, check the search form for updating,
757 # too.
759 our @cgi_param_mapping = (
760 project => "p",
761 action => "a",
762 file_name => "f",
763 file_parent => "fp",
764 hash => "h",
765 hash_parent => "hp",
766 hash_base => "hb",
767 hash_parent_base => "hpb",
768 page => "pg",
769 order => "o",
770 searchtext => "s",
771 searchtype => "st",
772 snapshot_format => "sf",
773 extra_options => "opt",
774 search_use_regexp => "sr",
775 # this must be last entry (for manipulation from JavaScript)
776 javascript => "js"
778 our %cgi_param_mapping = @cgi_param_mapping;
780 # we will also need to know the possible actions, for validation
781 our %actions = (
782 "blame" => \&git_blame,
783 "blame_incremental" => \&git_blame_incremental,
784 "blame_data" => \&git_blame_data,
785 "blobdiff" => \&git_blobdiff,
786 "blobdiff_plain" => \&git_blobdiff_plain,
787 "blob" => \&git_blob,
788 "blob_plain" => \&git_blob_plain,
789 "commitdiff" => \&git_commitdiff,
790 "commitdiff_plain" => \&git_commitdiff_plain,
791 "commit" => \&git_commit,
792 "forks" => \&git_forks,
793 "heads" => \&git_heads,
794 "history" => \&git_history,
795 "log" => \&git_log,
796 "patch" => \&git_patch,
797 "patches" => \&git_patches,
798 "rss" => \&git_rss,
799 "atom" => \&git_atom,
800 "search" => \&git_search,
801 "search_help" => \&git_search_help,
802 "shortlog" => \&git_shortlog,
803 "summary" => \&git_summary,
804 "tag" => \&git_tag,
805 "tags" => \&git_tags,
806 "tree" => \&git_tree,
807 "snapshot" => \&git_snapshot,
808 "object" => \&git_object,
809 # those below don't need $project
810 "opml" => \&git_opml,
811 "project_list" => \&git_project_list,
812 "project_index" => \&git_project_index,
815 # finally, we have the hash of allowed extra_options for the commands that
816 # allow them
817 our %allowed_options = (
818 "--no-merges" => [ qw(rss atom log shortlog history) ],
821 # fill %input_params with the CGI parameters. All values except for 'opt'
822 # should be single values, but opt can be an array. We should probably
823 # build an array of parameters that can be multi-valued, but since for the time
824 # being it's only this one, we just single it out
825 sub evaluate_query_params {
826 our $cgi;
828 while (my ($name, $symbol) = each %cgi_param_mapping) {
829 if ($symbol eq 'opt') {
830 $input_params{$name} = [ $cgi->param($symbol) ];
831 } else {
832 $input_params{$name} = $cgi->param($symbol);
837 # now read PATH_INFO and update the parameter list for missing parameters
838 sub evaluate_path_info {
839 return if defined $input_params{'project'};
840 return if !$path_info;
841 $path_info =~ s,^/+,,;
842 return if !$path_info;
844 # find which part of PATH_INFO is project
845 my $project = $path_info;
846 $project =~ s,/+$,,;
847 while ($project && !check_head_link("$projectroot/$project")) {
848 $project =~ s,/*[^/]*$,,;
850 return unless $project;
851 $input_params{'project'} = $project;
853 # do not change any parameters if an action is given using the query string
854 return if $input_params{'action'};
855 $path_info =~ s,^\Q$project\E/*,,;
857 # next, check if we have an action
858 my $action = $path_info;
859 $action =~ s,/.*$,,;
860 if (exists $actions{$action}) {
861 $path_info =~ s,^$action/*,,;
862 $input_params{'action'} = $action;
865 # list of actions that want hash_base instead of hash, but can have no
866 # pathname (f) parameter
867 my @wants_base = (
868 'tree',
869 'history',
872 # we want to catch, among others
873 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
874 my ($parentrefname, $parentpathname, $refname, $pathname) =
875 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
877 # first, analyze the 'current' part
878 if (defined $pathname) {
879 # we got "branch:filename" or "branch:dir/"
880 # we could use git_get_type(branch:pathname), but:
881 # - it needs $git_dir
882 # - it does a git() call
883 # - the convention of terminating directories with a slash
884 # makes it superfluous
885 # - embedding the action in the PATH_INFO would make it even
886 # more superfluous
887 $pathname =~ s,^/+,,;
888 if (!$pathname || substr($pathname, -1) eq "/") {
889 $input_params{'action'} ||= "tree";
890 $pathname =~ s,/$,,;
891 } else {
892 # the default action depends on whether we had parent info
893 # or not
894 if ($parentrefname) {
895 $input_params{'action'} ||= "blobdiff_plain";
896 } else {
897 $input_params{'action'} ||= "blob_plain";
900 $input_params{'hash_base'} ||= $refname;
901 $input_params{'file_name'} ||= $pathname;
902 } elsif (defined $refname) {
903 # we got "branch". In this case we have to choose if we have to
904 # set hash or hash_base.
906 # Most of the actions without a pathname only want hash to be
907 # set, except for the ones specified in @wants_base that want
908 # hash_base instead. It should also be noted that hand-crafted
909 # links having 'history' as an action and no pathname or hash
910 # set will fail, but that happens regardless of PATH_INFO.
911 if (defined $parentrefname) {
912 # if there is parent let the default be 'shortlog' action
913 # (for http://git.example.com/repo.git/A..B links); if there
914 # is no parent, dispatch will detect type of object and set
915 # action appropriately if required (if action is not set)
916 $input_params{'action'} ||= "shortlog";
918 if ($input_params{'action'} &&
919 grep { $_ eq $input_params{'action'} } @wants_base) {
920 $input_params{'hash_base'} ||= $refname;
921 } else {
922 $input_params{'hash'} ||= $refname;
926 # next, handle the 'parent' part, if present
927 if (defined $parentrefname) {
928 # a missing pathspec defaults to the 'current' filename, allowing e.g.
929 # someproject/blobdiff/oldrev..newrev:/filename
930 if ($parentpathname) {
931 $parentpathname =~ s,^/+,,;
932 $parentpathname =~ s,/$,,;
933 $input_params{'file_parent'} ||= $parentpathname;
934 } else {
935 $input_params{'file_parent'} ||= $input_params{'file_name'};
937 # we assume that hash_parent_base is wanted if a path was specified,
938 # or if the action wants hash_base instead of hash
939 if (defined $input_params{'file_parent'} ||
940 grep { $_ eq $input_params{'action'} } @wants_base) {
941 $input_params{'hash_parent_base'} ||= $parentrefname;
942 } else {
943 $input_params{'hash_parent'} ||= $parentrefname;
947 # for the snapshot action, we allow URLs in the form
948 # $project/snapshot/$hash.ext
949 # where .ext determines the snapshot and gets removed from the
950 # passed $refname to provide the $hash.
952 # To be able to tell that $refname includes the format extension, we
953 # require the following two conditions to be satisfied:
954 # - the hash input parameter MUST have been set from the $refname part
955 # of the URL (i.e. they must be equal)
956 # - the snapshot format MUST NOT have been defined already (e.g. from
957 # CGI parameter sf)
958 # It's also useless to try any matching unless $refname has a dot,
959 # so we check for that too
960 if (defined $input_params{'action'} &&
961 $input_params{'action'} eq 'snapshot' &&
962 defined $refname && index($refname, '.') != -1 &&
963 $refname eq $input_params{'hash'} &&
964 !defined $input_params{'snapshot_format'}) {
965 # We loop over the known snapshot formats, checking for
966 # extensions. Allowed extensions are both the defined suffix
967 # (which includes the initial dot already) and the snapshot
968 # format key itself, with a prepended dot
969 while (my ($fmt, $opt) = each %known_snapshot_formats) {
970 my $hash = $refname;
971 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
972 next;
974 my $sfx = $1;
975 # a valid suffix was found, so set the snapshot format
976 # and reset the hash parameter
977 $input_params{'snapshot_format'} = $fmt;
978 $input_params{'hash'} = $hash;
979 # we also set the format suffix to the one requested
980 # in the URL: this way a request for e.g. .tgz returns
981 # a .tgz instead of a .tar.gz
982 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
983 last;
988 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
989 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
990 $searchtext, $search_regexp);
991 sub evaluate_and_validate_params {
992 our $action = $input_params{'action'};
993 if (defined $action) {
994 if (!validate_action($action)) {
995 die_error(400, "Invalid action parameter");
999 # parameters which are pathnames
1000 our $project = $input_params{'project'};
1001 if (defined $project) {
1002 if (!validate_project($project)) {
1003 undef $project;
1004 die_error(404, "No such project");
1008 our $file_name = $input_params{'file_name'};
1009 if (defined $file_name) {
1010 if (!validate_pathname($file_name)) {
1011 die_error(400, "Invalid file parameter");
1015 our $file_parent = $input_params{'file_parent'};
1016 if (defined $file_parent) {
1017 if (!validate_pathname($file_parent)) {
1018 die_error(400, "Invalid file parent parameter");
1022 # parameters which are refnames
1023 our $hash = $input_params{'hash'};
1024 if (defined $hash) {
1025 if (!validate_refname($hash)) {
1026 die_error(400, "Invalid hash parameter");
1030 our $hash_parent = $input_params{'hash_parent'};
1031 if (defined $hash_parent) {
1032 if (!validate_refname($hash_parent)) {
1033 die_error(400, "Invalid hash parent parameter");
1037 our $hash_base = $input_params{'hash_base'};
1038 if (defined $hash_base) {
1039 if (!validate_refname($hash_base)) {
1040 die_error(400, "Invalid hash base parameter");
1044 our @extra_options = @{$input_params{'extra_options'}};
1045 # @extra_options is always defined, since it can only be (currently) set from
1046 # CGI, and $cgi->param() returns the empty array in array context if the param
1047 # is not set
1048 foreach my $opt (@extra_options) {
1049 if (not exists $allowed_options{$opt}) {
1050 die_error(400, "Invalid option parameter");
1052 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1053 die_error(400, "Invalid option parameter for this action");
1057 our $hash_parent_base = $input_params{'hash_parent_base'};
1058 if (defined $hash_parent_base) {
1059 if (!validate_refname($hash_parent_base)) {
1060 die_error(400, "Invalid hash parent base parameter");
1064 # other parameters
1065 our $page = $input_params{'page'};
1066 if (defined $page) {
1067 if ($page =~ m/[^0-9]/) {
1068 die_error(400, "Invalid page parameter");
1072 our $searchtype = $input_params{'searchtype'};
1073 if (defined $searchtype) {
1074 if ($searchtype =~ m/[^a-z]/) {
1075 die_error(400, "Invalid searchtype parameter");
1079 our $search_use_regexp = $input_params{'search_use_regexp'};
1081 our $searchtext = $input_params{'searchtext'};
1082 our $search_regexp;
1083 if (defined $searchtext) {
1084 if (length($searchtext) < 2) {
1085 die_error(403, "At least two characters are required for search parameter");
1087 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1091 # path to the current git repository
1092 our $git_dir;
1093 sub evaluate_git_dir {
1094 our $git_dir = "$projectroot/$project" if $project;
1097 our (@snapshot_fmts, $git_avatar);
1098 sub configure_gitweb_features {
1099 # list of supported snapshot formats
1100 our @snapshot_fmts = gitweb_get_feature('snapshot');
1101 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1103 # check that the avatar feature is set to a known provider name,
1104 # and for each provider check if the dependencies are satisfied.
1105 # if the provider name is invalid or the dependencies are not met,
1106 # reset $git_avatar to the empty string.
1107 our ($git_avatar) = gitweb_get_feature('avatar');
1108 if ($git_avatar eq 'gravatar') {
1109 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1110 } elsif ($git_avatar eq 'picon') {
1111 # no dependencies
1112 } else {
1113 $git_avatar = '';
1117 # custom error handler: 'die <message>' is Internal Server Error
1118 sub handle_errors_html {
1119 my $msg = shift; # it is already HTML escaped
1121 # to avoid infinite loop where error occurs in die_error,
1122 # change handler to default handler, disabling handle_errors_html
1123 set_message("Error occured when inside die_error:\n$msg");
1125 # you cannot jump out of die_error when called as error handler;
1126 # the subroutine set via CGI::Carp::set_message is called _after_
1127 # HTTP headers are already written, so it cannot write them itself
1128 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1130 set_message(\&handle_errors_html);
1132 # dispatch
1133 sub dispatch {
1134 if (!defined $action) {
1135 if (defined $hash) {
1136 $action = git_get_type($hash);
1137 } elsif (defined $hash_base && defined $file_name) {
1138 $action = git_get_type("$hash_base:$file_name");
1139 } elsif (defined $project) {
1140 $action = 'summary';
1141 } else {
1142 $action = 'project_list';
1145 if (!defined($actions{$action})) {
1146 die_error(400, "Unknown action");
1148 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1149 !$project) {
1150 die_error(400, "Project needed");
1153 if ($caching_enabled) {
1154 # human readable key identifying gitweb output
1155 my $output_key = href(-replay => 1, -full => 1, -path_info => 0);
1157 cache_output($cache, $capture, $output_key, $actions{$action});
1158 } else {
1159 $actions{$action}->();
1163 sub reset_timer {
1164 our $t0 = [Time::HiRes::gettimeofday()]
1165 if defined $t0;
1166 our $number_of_git_cmds = 0;
1169 sub run_request {
1170 reset_timer();
1172 evaluate_uri();
1173 evaluate_gitweb_config();
1174 evaluate_git_version();
1175 check_loadavg();
1176 configure_caching()
1177 if ($caching_enabled);
1179 # $projectroot and $projects_list might be set in gitweb config file
1180 $projects_list ||= $projectroot;
1182 evaluate_query_params();
1183 evaluate_path_info();
1184 evaluate_and_validate_params();
1185 evaluate_git_dir();
1187 configure_gitweb_features();
1189 dispatch();
1192 our $is_last_request = sub { 1 };
1193 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1194 our $CGI = 'CGI';
1195 our $cgi;
1196 sub configure_as_fcgi {
1197 require CGI::Fast;
1198 our $CGI = 'CGI::Fast';
1200 my $request_number = 0;
1201 # let each child service 100 requests
1202 our $is_last_request = sub { ++$request_number > 100 };
1204 sub evaluate_argv {
1205 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1206 configure_as_fcgi()
1207 if $script_name =~ /\.fcgi$/;
1209 return unless (@ARGV);
1211 require Getopt::Long;
1212 Getopt::Long::GetOptions(
1213 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1214 'nproc|n=i' => sub {
1215 my ($arg, $val) = @_;
1216 return unless eval { require FCGI::ProcManager; 1; };
1217 my $proc_manager = FCGI::ProcManager->new({
1218 n_processes => $val,
1220 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1221 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1222 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1227 sub run {
1228 evaluate_argv();
1230 $pre_listen_hook->()
1231 if $pre_listen_hook;
1233 REQUEST:
1234 while ($cgi = $CGI->new()) {
1235 $pre_dispatch_hook->()
1236 if $pre_dispatch_hook;
1238 run_request();
1240 $post_dispatch_hook->()
1241 if $post_dispatch_hook;
1243 last REQUEST if ($is_last_request->());
1246 DONE_GITWEB:
1250 sub configure_caching {
1251 if (!eval { require GitwebCache::CacheOutput; 1; }) {
1252 # cache is configured _before_ handling request, so $cgi is not defined,
1253 # so we can't just "die" with sending error message to web browser
1254 #die_error(500, "Caching enabled and GitwebCache::CacheOutput not found");
1256 # turn off caching and warn instead
1257 $caching_enabled = 0;
1258 warn "Caching enabled and GitwebCache::CacheOutput not found";
1260 GitwebCache::CacheOutput->import();
1262 # $cache might be initialized (instantiated) cache, i.e. cache object,
1263 # or it might be name of class, or it might be undefined
1264 unless (defined $cache && ref($cache)) {
1265 $cache ||= 'GitwebCache::FileCacheWithLocking';
1266 eval "require $cache";
1267 die $@ if $@;
1268 $cache = $cache->new({
1269 %cache_options,
1270 #'cache_root' => '/tmp/cache',
1271 #'cache_depth' => 2,
1272 #'expires_in' => 20, # in seconds (CHI compatibile)
1273 # (Cache::Cache compatibile initialization)
1274 'default_expires_in' => $cache_options{'expires_in'},
1275 # (CHI compatibile initialization)
1276 'root_dir' => $cache_options{'cache_root'},
1277 'depth' => $cache_options{'cache_depth'},
1280 unless (defined $capture && ref($capture)) {
1281 require GitwebCache::Capture::Simple;
1282 $capture = GitwebCache::Capture::Simple->new();
1286 run();
1288 if (defined caller) {
1289 # wrapped in a subroutine processing requests,
1290 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1291 return;
1292 } else {
1293 # pure CGI script, serving single request
1294 exit;
1297 ## ======================================================================
1298 ## action links
1300 # possible values of extra options
1301 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1302 # -replay => 1 - start from a current view (replay with modifications)
1303 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1304 sub href {
1305 my %params = @_;
1306 # default is to use -absolute url() i.e. $my_uri
1307 my $href = $params{-full} ? $my_url : $my_uri;
1309 $params{'project'} = $project unless exists $params{'project'};
1311 if ($params{-replay}) {
1312 while (my ($name, $symbol) = each %cgi_param_mapping) {
1313 if (!exists $params{$name}) {
1314 $params{$name} = $input_params{$name};
1319 my $use_pathinfo = gitweb_check_feature('pathinfo');
1320 if (defined $params{'project'} &&
1321 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1322 # try to put as many parameters as possible in PATH_INFO:
1323 # - project name
1324 # - action
1325 # - hash_parent or hash_parent_base:/file_parent
1326 # - hash or hash_base:/filename
1327 # - the snapshot_format as an appropriate suffix
1329 # When the script is the root DirectoryIndex for the domain,
1330 # $href here would be something like http://gitweb.example.com/
1331 # Thus, we strip any trailing / from $href, to spare us double
1332 # slashes in the final URL
1333 $href =~ s,/$,,;
1335 # Then add the project name, if present
1336 $href .= "/".esc_url($params{'project'});
1337 delete $params{'project'};
1339 # since we destructively absorb parameters, we keep this
1340 # boolean that remembers if we're handling a snapshot
1341 my $is_snapshot = $params{'action'} eq 'snapshot';
1343 # Summary just uses the project path URL, any other action is
1344 # added to the URL
1345 if (defined $params{'action'}) {
1346 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1347 delete $params{'action'};
1350 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1351 # stripping nonexistent or useless pieces
1352 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1353 || $params{'hash_parent'} || $params{'hash'});
1354 if (defined $params{'hash_base'}) {
1355 if (defined $params{'hash_parent_base'}) {
1356 $href .= esc_url($params{'hash_parent_base'});
1357 # skip the file_parent if it's the same as the file_name
1358 if (defined $params{'file_parent'}) {
1359 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1360 delete $params{'file_parent'};
1361 } elsif ($params{'file_parent'} !~ /\.\./) {
1362 $href .= ":/".esc_url($params{'file_parent'});
1363 delete $params{'file_parent'};
1366 $href .= "..";
1367 delete $params{'hash_parent'};
1368 delete $params{'hash_parent_base'};
1369 } elsif (defined $params{'hash_parent'}) {
1370 $href .= esc_url($params{'hash_parent'}). "..";
1371 delete $params{'hash_parent'};
1374 $href .= esc_url($params{'hash_base'});
1375 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1376 $href .= ":/".esc_url($params{'file_name'});
1377 delete $params{'file_name'};
1379 delete $params{'hash'};
1380 delete $params{'hash_base'};
1381 } elsif (defined $params{'hash'}) {
1382 $href .= esc_url($params{'hash'});
1383 delete $params{'hash'};
1386 # If the action was a snapshot, we can absorb the
1387 # snapshot_format parameter too
1388 if ($is_snapshot) {
1389 my $fmt = $params{'snapshot_format'};
1390 # snapshot_format should always be defined when href()
1391 # is called, but just in case some code forgets, we
1392 # fall back to the default
1393 $fmt ||= $snapshot_fmts[0];
1394 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1395 delete $params{'snapshot_format'};
1399 # now encode the parameters explicitly
1400 my @result = ();
1401 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1402 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1403 if (defined $params{$name}) {
1404 if (ref($params{$name}) eq "ARRAY") {
1405 foreach my $par (@{$params{$name}}) {
1406 push @result, $symbol . "=" . esc_param($par);
1408 } else {
1409 push @result, $symbol . "=" . esc_param($params{$name});
1413 $href .= "?" . join(';', @result) if scalar @result;
1415 return $href;
1419 ## ======================================================================
1420 ## validation, quoting/unquoting and escaping
1422 sub validate_action {
1423 my $input = shift || return undef;
1424 return undef unless exists $actions{$input};
1425 return $input;
1428 sub validate_project {
1429 my $input = shift || return undef;
1430 if (!validate_pathname($input) ||
1431 !(-d "$projectroot/$input") ||
1432 !check_export_ok("$projectroot/$input") ||
1433 ($strict_export && !project_in_list($input))) {
1434 return undef;
1435 } else {
1436 return $input;
1440 sub validate_pathname {
1441 my $input = shift || return undef;
1443 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1444 # at the beginning, at the end, and between slashes.
1445 # also this catches doubled slashes
1446 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1447 return undef;
1449 # no null characters
1450 if ($input =~ m!\0!) {
1451 return undef;
1453 return $input;
1456 sub validate_refname {
1457 my $input = shift || return undef;
1459 # textual hashes are O.K.
1460 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1461 return $input;
1463 # it must be correct pathname
1464 $input = validate_pathname($input)
1465 or return undef;
1466 # restrictions on ref name according to git-check-ref-format
1467 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1468 return undef;
1470 return $input;
1473 # decode sequences of octets in utf8 into Perl's internal form,
1474 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1475 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1476 sub to_utf8 {
1477 my $str = shift;
1478 return undef unless defined $str;
1479 if (utf8::valid($str)) {
1480 utf8::decode($str);
1481 return $str;
1482 } else {
1483 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1487 # quote unsafe chars, but keep the slash, even when it's not
1488 # correct, but quoted slashes look too horrible in bookmarks
1489 sub esc_param {
1490 my $str = shift;
1491 return undef unless defined $str;
1492 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1493 $str =~ s/ /\+/g;
1494 return $str;
1497 # quote unsafe chars in whole URL, so some characters cannot be quoted
1498 sub esc_url {
1499 my $str = shift;
1500 return undef unless defined $str;
1501 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1502 $str =~ s/ /\+/g;
1503 return $str;
1506 # replace invalid utf8 character with SUBSTITUTION sequence
1507 sub esc_html {
1508 my $str = shift;
1509 my %opts = @_;
1511 return undef unless defined $str;
1513 $str = to_utf8($str);
1514 $str = $cgi->escapeHTML($str);
1515 if ($opts{'-nbsp'}) {
1516 $str =~ s/ /&nbsp;/g;
1518 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1519 return $str;
1522 # quote control characters and escape filename to HTML
1523 sub esc_path {
1524 my $str = shift;
1525 my %opts = @_;
1527 return undef unless defined $str;
1529 $str = to_utf8($str);
1530 $str = $cgi->escapeHTML($str);
1531 if ($opts{'-nbsp'}) {
1532 $str =~ s/ /&nbsp;/g;
1534 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1535 return $str;
1538 # Make control characters "printable", using character escape codes (CEC)
1539 sub quot_cec {
1540 my $cntrl = shift;
1541 my %opts = @_;
1542 my %es = ( # character escape codes, aka escape sequences
1543 "\t" => '\t', # tab (HT)
1544 "\n" => '\n', # line feed (LF)
1545 "\r" => '\r', # carrige return (CR)
1546 "\f" => '\f', # form feed (FF)
1547 "\b" => '\b', # backspace (BS)
1548 "\a" => '\a', # alarm (bell) (BEL)
1549 "\e" => '\e', # escape (ESC)
1550 "\013" => '\v', # vertical tab (VT)
1551 "\000" => '\0', # nul character (NUL)
1553 my $chr = ( (exists $es{$cntrl})
1554 ? $es{$cntrl}
1555 : sprintf('\%2x', ord($cntrl)) );
1556 if ($opts{-nohtml}) {
1557 return $chr;
1558 } else {
1559 return "<span class=\"cntrl\">$chr</span>";
1563 # Alternatively use unicode control pictures codepoints,
1564 # Unicode "printable representation" (PR)
1565 sub quot_upr {
1566 my $cntrl = shift;
1567 my %opts = @_;
1569 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1570 if ($opts{-nohtml}) {
1571 return $chr;
1572 } else {
1573 return "<span class=\"cntrl\">$chr</span>";
1577 # git may return quoted and escaped filenames
1578 sub unquote {
1579 my $str = shift;
1581 sub unq {
1582 my $seq = shift;
1583 my %es = ( # character escape codes, aka escape sequences
1584 't' => "\t", # tab (HT, TAB)
1585 'n' => "\n", # newline (NL)
1586 'r' => "\r", # return (CR)
1587 'f' => "\f", # form feed (FF)
1588 'b' => "\b", # backspace (BS)
1589 'a' => "\a", # alarm (bell) (BEL)
1590 'e' => "\e", # escape (ESC)
1591 'v' => "\013", # vertical tab (VT)
1594 if ($seq =~ m/^[0-7]{1,3}$/) {
1595 # octal char sequence
1596 return chr(oct($seq));
1597 } elsif (exists $es{$seq}) {
1598 # C escape sequence, aka character escape code
1599 return $es{$seq};
1601 # quoted ordinary character
1602 return $seq;
1605 if ($str =~ m/^"(.*)"$/) {
1606 # needs unquoting
1607 $str = $1;
1608 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1610 return $str;
1613 # escape tabs (convert tabs to spaces)
1614 sub untabify {
1615 my $line = shift;
1617 while ((my $pos = index($line, "\t")) != -1) {
1618 if (my $count = (8 - ($pos % 8))) {
1619 my $spaces = ' ' x $count;
1620 $line =~ s/\t/$spaces/;
1624 return $line;
1627 sub project_in_list {
1628 my $project = shift;
1629 my @list = git_get_projects_list();
1630 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1633 ## ----------------------------------------------------------------------
1634 ## HTML aware string manipulation
1636 # Try to chop given string on a word boundary between position
1637 # $len and $len+$add_len. If there is no word boundary there,
1638 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1639 # (marking chopped part) would be longer than given string.
1640 sub chop_str {
1641 my $str = shift;
1642 my $len = shift;
1643 my $add_len = shift || 10;
1644 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1646 # Make sure perl knows it is utf8 encoded so we don't
1647 # cut in the middle of a utf8 multibyte char.
1648 $str = to_utf8($str);
1650 # allow only $len chars, but don't cut a word if it would fit in $add_len
1651 # if it doesn't fit, cut it if it's still longer than the dots we would add
1652 # remove chopped character entities entirely
1654 # when chopping in the middle, distribute $len into left and right part
1655 # return early if chopping wouldn't make string shorter
1656 if ($where eq 'center') {
1657 return $str if ($len + 5 >= length($str)); # filler is length 5
1658 $len = int($len/2);
1659 } else {
1660 return $str if ($len + 4 >= length($str)); # filler is length 4
1663 # regexps: ending and beginning with word part up to $add_len
1664 my $endre = qr/.{$len}\w{0,$add_len}/;
1665 my $begre = qr/\w{0,$add_len}.{$len}/;
1667 if ($where eq 'left') {
1668 $str =~ m/^(.*?)($begre)$/;
1669 my ($lead, $body) = ($1, $2);
1670 if (length($lead) > 4) {
1671 $lead = " ...";
1673 return "$lead$body";
1675 } elsif ($where eq 'center') {
1676 $str =~ m/^($endre)(.*)$/;
1677 my ($left, $str) = ($1, $2);
1678 $str =~ m/^(.*?)($begre)$/;
1679 my ($mid, $right) = ($1, $2);
1680 if (length($mid) > 5) {
1681 $mid = " ... ";
1683 return "$left$mid$right";
1685 } else {
1686 $str =~ m/^($endre)(.*)$/;
1687 my $body = $1;
1688 my $tail = $2;
1689 if (length($tail) > 4) {
1690 $tail = "... ";
1692 return "$body$tail";
1696 # takes the same arguments as chop_str, but also wraps a <span> around the
1697 # result with a title attribute if it does get chopped. Additionally, the
1698 # string is HTML-escaped.
1699 sub chop_and_escape_str {
1700 my ($str) = @_;
1702 my $chopped = chop_str(@_);
1703 if ($chopped eq $str) {
1704 return esc_html($chopped);
1705 } else {
1706 $str =~ s/[[:cntrl:]]/?/g;
1707 return $cgi->span({-title=>$str}, esc_html($chopped));
1711 ## ----------------------------------------------------------------------
1712 ## functions returning short strings
1714 # CSS class for given age value (in seconds)
1715 sub age_class {
1716 my $age = shift;
1718 if (!defined $age) {
1719 return "noage";
1720 } elsif ($age < 60*60*2) {
1721 return "age0";
1722 } elsif ($age < 60*60*24*2) {
1723 return "age1";
1724 } else {
1725 return "age2";
1729 # convert age in seconds to "nn units ago" string
1730 sub age_string {
1731 my $age = shift;
1732 my $age_str;
1734 if ($age > 60*60*24*365*2) {
1735 $age_str = (int $age/60/60/24/365);
1736 $age_str .= " years ago";
1737 } elsif ($age > 60*60*24*(365/12)*2) {
1738 $age_str = int $age/60/60/24/(365/12);
1739 $age_str .= " months ago";
1740 } elsif ($age > 60*60*24*7*2) {
1741 $age_str = int $age/60/60/24/7;
1742 $age_str .= " weeks ago";
1743 } elsif ($age > 60*60*24*2) {
1744 $age_str = int $age/60/60/24;
1745 $age_str .= " days ago";
1746 } elsif ($age > 60*60*2) {
1747 $age_str = int $age/60/60;
1748 $age_str .= " hours ago";
1749 } elsif ($age > 60*2) {
1750 $age_str = int $age/60;
1751 $age_str .= " min ago";
1752 } elsif ($age > 2) {
1753 $age_str = int $age;
1754 $age_str .= " sec ago";
1755 } else {
1756 $age_str .= " right now";
1758 return $age_str;
1761 use constant {
1762 S_IFINVALID => 0030000,
1763 S_IFGITLINK => 0160000,
1766 # submodule/subproject, a commit object reference
1767 sub S_ISGITLINK {
1768 my $mode = shift;
1770 return (($mode & S_IFMT) == S_IFGITLINK)
1773 # convert file mode in octal to symbolic file mode string
1774 sub mode_str {
1775 my $mode = oct shift;
1777 if (S_ISGITLINK($mode)) {
1778 return 'm---------';
1779 } elsif (S_ISDIR($mode & S_IFMT)) {
1780 return 'drwxr-xr-x';
1781 } elsif (S_ISLNK($mode)) {
1782 return 'lrwxrwxrwx';
1783 } elsif (S_ISREG($mode)) {
1784 # git cares only about the executable bit
1785 if ($mode & S_IXUSR) {
1786 return '-rwxr-xr-x';
1787 } else {
1788 return '-rw-r--r--';
1790 } else {
1791 return '----------';
1795 # convert file mode in octal to file type string
1796 sub file_type {
1797 my $mode = shift;
1799 if ($mode !~ m/^[0-7]+$/) {
1800 return $mode;
1801 } else {
1802 $mode = oct $mode;
1805 if (S_ISGITLINK($mode)) {
1806 return "submodule";
1807 } elsif (S_ISDIR($mode & S_IFMT)) {
1808 return "directory";
1809 } elsif (S_ISLNK($mode)) {
1810 return "symlink";
1811 } elsif (S_ISREG($mode)) {
1812 return "file";
1813 } else {
1814 return "unknown";
1818 # convert file mode in octal to file type description string
1819 sub file_type_long {
1820 my $mode = shift;
1822 if ($mode !~ m/^[0-7]+$/) {
1823 return $mode;
1824 } else {
1825 $mode = oct $mode;
1828 if (S_ISGITLINK($mode)) {
1829 return "submodule";
1830 } elsif (S_ISDIR($mode & S_IFMT)) {
1831 return "directory";
1832 } elsif (S_ISLNK($mode)) {
1833 return "symlink";
1834 } elsif (S_ISREG($mode)) {
1835 if ($mode & S_IXUSR) {
1836 return "executable";
1837 } else {
1838 return "file";
1840 } else {
1841 return "unknown";
1846 ## ----------------------------------------------------------------------
1847 ## functions returning short HTML fragments, or transforming HTML fragments
1848 ## which don't belong to other sections
1850 # format line of commit message.
1851 sub format_log_line_html {
1852 my $line = shift;
1854 $line = esc_html($line, -nbsp=>1);
1855 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1856 $cgi->a({-href => href(action=>"object", hash=>$1),
1857 -class => "text"}, $1);
1858 }eg;
1860 return $line;
1863 # format marker of refs pointing to given object
1865 # the destination action is chosen based on object type and current context:
1866 # - for annotated tags, we choose the tag view unless it's the current view
1867 # already, in which case we go to shortlog view
1868 # - for other refs, we keep the current view if we're in history, shortlog or
1869 # log view, and select shortlog otherwise
1870 sub format_ref_marker {
1871 my ($refs, $id) = @_;
1872 my $markers = '';
1874 if (defined $refs->{$id}) {
1875 foreach my $ref (@{$refs->{$id}}) {
1876 # this code exploits the fact that non-lightweight tags are the
1877 # only indirect objects, and that they are the only objects for which
1878 # we want to use tag instead of shortlog as action
1879 my ($type, $name) = qw();
1880 my $indirect = ($ref =~ s/\^\{\}$//);
1881 # e.g. tags/v2.6.11 or heads/next
1882 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1883 $type = $1;
1884 $name = $2;
1885 } else {
1886 $type = "ref";
1887 $name = $ref;
1890 my $class = $type;
1891 $class .= " indirect" if $indirect;
1893 my $dest_action = "shortlog";
1895 if ($indirect) {
1896 $dest_action = "tag" unless $action eq "tag";
1897 } elsif ($action =~ /^(history|(short)?log)$/) {
1898 $dest_action = $action;
1901 my $dest = "";
1902 $dest .= "refs/" unless $ref =~ m!^refs/!;
1903 $dest .= $ref;
1905 my $link = $cgi->a({
1906 -href => href(
1907 action=>$dest_action,
1908 hash=>$dest
1909 )}, $name);
1911 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1912 $link . "</span>";
1916 if ($markers) {
1917 return ' <span class="refs">'. $markers . '</span>';
1918 } else {
1919 return "";
1923 # format, perhaps shortened and with markers, title line
1924 sub format_subject_html {
1925 my ($long, $short, $href, $extra) = @_;
1926 $extra = '' unless defined($extra);
1928 if (length($short) < length($long)) {
1929 $long =~ s/[[:cntrl:]]/?/g;
1930 return $cgi->a({-href => $href, -class => "list subject",
1931 -title => to_utf8($long)},
1932 esc_html($short)) . $extra;
1933 } else {
1934 return $cgi->a({-href => $href, -class => "list subject"},
1935 esc_html($long)) . $extra;
1939 # Rather than recomputing the url for an email multiple times, we cache it
1940 # after the first hit. This gives a visible benefit in views where the avatar
1941 # for the same email is used repeatedly (e.g. shortlog).
1942 # The cache is shared by all avatar engines (currently gravatar only), which
1943 # are free to use it as preferred. Since only one avatar engine is used for any
1944 # given page, there's no risk for cache conflicts.
1945 our %avatar_cache = ();
1947 # Compute the picon url for a given email, by using the picon search service over at
1948 # http://www.cs.indiana.edu/picons/search.html
1949 sub picon_url {
1950 my $email = lc shift;
1951 if (!$avatar_cache{$email}) {
1952 my ($user, $domain) = split('@', $email);
1953 $avatar_cache{$email} =
1954 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1955 "$domain/$user/" .
1956 "users+domains+unknown/up/single";
1958 return $avatar_cache{$email};
1961 # Compute the gravatar url for a given email, if it's not in the cache already.
1962 # Gravatar stores only the part of the URL before the size, since that's the
1963 # one computationally more expensive. This also allows reuse of the cache for
1964 # different sizes (for this particular engine).
1965 sub gravatar_url {
1966 my $email = lc shift;
1967 my $size = shift;
1968 $avatar_cache{$email} ||=
1969 "http://www.gravatar.com/avatar/" .
1970 Digest::MD5::md5_hex($email) . "?s=";
1971 return $avatar_cache{$email} . $size;
1974 # Insert an avatar for the given $email at the given $size if the feature
1975 # is enabled.
1976 sub git_get_avatar {
1977 my ($email, %opts) = @_;
1978 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1979 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1980 $opts{-size} ||= 'default';
1981 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1982 my $url = "";
1983 if ($git_avatar eq 'gravatar') {
1984 $url = gravatar_url($email, $size);
1985 } elsif ($git_avatar eq 'picon') {
1986 $url = picon_url($email);
1988 # Other providers can be added by extending the if chain, defining $url
1989 # as needed. If no variant puts something in $url, we assume avatars
1990 # are completely disabled/unavailable.
1991 if ($url) {
1992 return $pre_white .
1993 "<img width=\"$size\" " .
1994 "class=\"avatar\" " .
1995 "src=\"$url\" " .
1996 "alt=\"\" " .
1997 "/>" . $post_white;
1998 } else {
1999 return "";
2003 sub format_search_author {
2004 my ($author, $searchtype, $displaytext) = @_;
2005 my $have_search = gitweb_check_feature('search');
2007 if ($have_search) {
2008 my $performed = "";
2009 if ($searchtype eq 'author') {
2010 $performed = "authored";
2011 } elsif ($searchtype eq 'committer') {
2012 $performed = "committed";
2015 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2016 searchtext=>$author,
2017 searchtype=>$searchtype), class=>"list",
2018 title=>"Search for commits $performed by $author"},
2019 $displaytext);
2021 } else {
2022 return $displaytext;
2026 # format the author name of the given commit with the given tag
2027 # the author name is chopped and escaped according to the other
2028 # optional parameters (see chop_str).
2029 sub format_author_html {
2030 my $tag = shift;
2031 my $co = shift;
2032 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2033 return "<$tag class=\"author\">" .
2034 format_search_author($co->{'author_name'}, "author",
2035 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2036 $author) .
2037 "</$tag>";
2040 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2041 sub format_git_diff_header_line {
2042 my $line = shift;
2043 my $diffinfo = shift;
2044 my ($from, $to) = @_;
2046 if ($diffinfo->{'nparents'}) {
2047 # combined diff
2048 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2049 if ($to->{'href'}) {
2050 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2051 esc_path($to->{'file'}));
2052 } else { # file was deleted (no href)
2053 $line .= esc_path($to->{'file'});
2055 } else {
2056 # "ordinary" diff
2057 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2058 if ($from->{'href'}) {
2059 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2060 'a/' . esc_path($from->{'file'}));
2061 } else { # file was added (no href)
2062 $line .= 'a/' . esc_path($from->{'file'});
2064 $line .= ' ';
2065 if ($to->{'href'}) {
2066 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2067 'b/' . esc_path($to->{'file'}));
2068 } else { # file was deleted
2069 $line .= 'b/' . esc_path($to->{'file'});
2073 return "<div class=\"diff header\">$line</div>\n";
2076 # format extended diff header line, before patch itself
2077 sub format_extended_diff_header_line {
2078 my $line = shift;
2079 my $diffinfo = shift;
2080 my ($from, $to) = @_;
2082 # match <path>
2083 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2084 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2085 esc_path($from->{'file'}));
2087 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2088 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2089 esc_path($to->{'file'}));
2091 # match single <mode>
2092 if ($line =~ m/\s(\d{6})$/) {
2093 $line .= '<span class="info"> (' .
2094 file_type_long($1) .
2095 ')</span>';
2097 # match <hash>
2098 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2099 # can match only for combined diff
2100 $line = 'index ';
2101 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2102 if ($from->{'href'}[$i]) {
2103 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2104 -class=>"hash"},
2105 substr($diffinfo->{'from_id'}[$i],0,7));
2106 } else {
2107 $line .= '0' x 7;
2109 # separator
2110 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2112 $line .= '..';
2113 if ($to->{'href'}) {
2114 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2115 substr($diffinfo->{'to_id'},0,7));
2116 } else {
2117 $line .= '0' x 7;
2120 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2121 # can match only for ordinary diff
2122 my ($from_link, $to_link);
2123 if ($from->{'href'}) {
2124 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2125 substr($diffinfo->{'from_id'},0,7));
2126 } else {
2127 $from_link = '0' x 7;
2129 if ($to->{'href'}) {
2130 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2131 substr($diffinfo->{'to_id'},0,7));
2132 } else {
2133 $to_link = '0' x 7;
2135 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2136 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2139 return $line . "<br/>\n";
2142 # format from-file/to-file diff header
2143 sub format_diff_from_to_header {
2144 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2145 my $line;
2146 my $result = '';
2148 $line = $from_line;
2149 #assert($line =~ m/^---/) if DEBUG;
2150 # no extra formatting for "^--- /dev/null"
2151 if (! $diffinfo->{'nparents'}) {
2152 # ordinary (single parent) diff
2153 if ($line =~ m!^--- "?a/!) {
2154 if ($from->{'href'}) {
2155 $line = '--- a/' .
2156 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2157 esc_path($from->{'file'}));
2158 } else {
2159 $line = '--- a/' .
2160 esc_path($from->{'file'});
2163 $result .= qq!<div class="diff from_file">$line</div>\n!;
2165 } else {
2166 # combined diff (merge commit)
2167 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2168 if ($from->{'href'}[$i]) {
2169 $line = '--- ' .
2170 $cgi->a({-href=>href(action=>"blobdiff",
2171 hash_parent=>$diffinfo->{'from_id'}[$i],
2172 hash_parent_base=>$parents[$i],
2173 file_parent=>$from->{'file'}[$i],
2174 hash=>$diffinfo->{'to_id'},
2175 hash_base=>$hash,
2176 file_name=>$to->{'file'}),
2177 -class=>"path",
2178 -title=>"diff" . ($i+1)},
2179 $i+1) .
2180 '/' .
2181 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2182 esc_path($from->{'file'}[$i]));
2183 } else {
2184 $line = '--- /dev/null';
2186 $result .= qq!<div class="diff from_file">$line</div>\n!;
2190 $line = $to_line;
2191 #assert($line =~ m/^\+\+\+/) if DEBUG;
2192 # no extra formatting for "^+++ /dev/null"
2193 if ($line =~ m!^\+\+\+ "?b/!) {
2194 if ($to->{'href'}) {
2195 $line = '+++ b/' .
2196 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2197 esc_path($to->{'file'}));
2198 } else {
2199 $line = '+++ b/' .
2200 esc_path($to->{'file'});
2203 $result .= qq!<div class="diff to_file">$line</div>\n!;
2205 return $result;
2208 # create note for patch simplified by combined diff
2209 sub format_diff_cc_simplified {
2210 my ($diffinfo, @parents) = @_;
2211 my $result = '';
2213 $result .= "<div class=\"diff header\">" .
2214 "diff --cc ";
2215 if (!is_deleted($diffinfo)) {
2216 $result .= $cgi->a({-href => href(action=>"blob",
2217 hash_base=>$hash,
2218 hash=>$diffinfo->{'to_id'},
2219 file_name=>$diffinfo->{'to_file'}),
2220 -class => "path"},
2221 esc_path($diffinfo->{'to_file'}));
2222 } else {
2223 $result .= esc_path($diffinfo->{'to_file'});
2225 $result .= "</div>\n" . # class="diff header"
2226 "<div class=\"diff nodifferences\">" .
2227 "Simple merge" .
2228 "</div>\n"; # class="diff nodifferences"
2230 return $result;
2233 # format patch (diff) line (not to be used for diff headers)
2234 sub format_diff_line {
2235 my $line = shift;
2236 my ($from, $to) = @_;
2237 my $diff_class = "";
2239 chomp $line;
2241 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2242 # combined diff
2243 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2244 if ($line =~ m/^\@{3}/) {
2245 $diff_class = " chunk_header";
2246 } elsif ($line =~ m/^\\/) {
2247 $diff_class = " incomplete";
2248 } elsif ($prefix =~ tr/+/+/) {
2249 $diff_class = " add";
2250 } elsif ($prefix =~ tr/-/-/) {
2251 $diff_class = " rem";
2253 } else {
2254 # assume ordinary diff
2255 my $char = substr($line, 0, 1);
2256 if ($char eq '+') {
2257 $diff_class = " add";
2258 } elsif ($char eq '-') {
2259 $diff_class = " rem";
2260 } elsif ($char eq '@') {
2261 $diff_class = " chunk_header";
2262 } elsif ($char eq "\\") {
2263 $diff_class = " incomplete";
2266 $line = untabify($line);
2267 if ($from && $to && $line =~ m/^\@{2} /) {
2268 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2269 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2271 $from_lines = 0 unless defined $from_lines;
2272 $to_lines = 0 unless defined $to_lines;
2274 if ($from->{'href'}) {
2275 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2276 -class=>"list"}, $from_text);
2278 if ($to->{'href'}) {
2279 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2280 -class=>"list"}, $to_text);
2282 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2283 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2284 return "<div class=\"diff$diff_class\">$line</div>\n";
2285 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2286 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2287 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2289 @from_text = split(' ', $ranges);
2290 for (my $i = 0; $i < @from_text; ++$i) {
2291 ($from_start[$i], $from_nlines[$i]) =
2292 (split(',', substr($from_text[$i], 1)), 0);
2295 $to_text = pop @from_text;
2296 $to_start = pop @from_start;
2297 $to_nlines = pop @from_nlines;
2299 $line = "<span class=\"chunk_info\">$prefix ";
2300 for (my $i = 0; $i < @from_text; ++$i) {
2301 if ($from->{'href'}[$i]) {
2302 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2303 -class=>"list"}, $from_text[$i]);
2304 } else {
2305 $line .= $from_text[$i];
2307 $line .= " ";
2309 if ($to->{'href'}) {
2310 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2311 -class=>"list"}, $to_text);
2312 } else {
2313 $line .= $to_text;
2315 $line .= " $prefix</span>" .
2316 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2317 return "<div class=\"diff$diff_class\">$line</div>\n";
2319 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2322 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2323 # linked. Pass the hash of the tree/commit to snapshot.
2324 sub format_snapshot_links {
2325 my ($hash) = @_;
2326 my $num_fmts = @snapshot_fmts;
2327 if ($num_fmts > 1) {
2328 # A parenthesized list of links bearing format names.
2329 # e.g. "snapshot (_tar.gz_ _zip_)"
2330 return "snapshot (" . join(' ', map
2331 $cgi->a({
2332 -href => href(
2333 action=>"snapshot",
2334 hash=>$hash,
2335 snapshot_format=>$_
2337 }, $known_snapshot_formats{$_}{'display'})
2338 , @snapshot_fmts) . ")";
2339 } elsif ($num_fmts == 1) {
2340 # A single "snapshot" link whose tooltip bears the format name.
2341 # i.e. "_snapshot_"
2342 my ($fmt) = @snapshot_fmts;
2343 return
2344 $cgi->a({
2345 -href => href(
2346 action=>"snapshot",
2347 hash=>$hash,
2348 snapshot_format=>$fmt
2350 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2351 }, "snapshot");
2352 } else { # $num_fmts == 0
2353 return undef;
2357 ## ......................................................................
2358 ## functions returning values to be passed, perhaps after some
2359 ## transformation, to other functions; e.g. returning arguments to href()
2361 # returns hash to be passed to href to generate gitweb URL
2362 # in -title key it returns description of link
2363 sub get_feed_info {
2364 my $format = shift || 'Atom';
2365 my %res = (action => lc($format));
2367 # feed links are possible only for project views
2368 return unless (defined $project);
2369 # some views should link to OPML, or to generic project feed,
2370 # or don't have specific feed yet (so they should use generic)
2371 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2373 my $branch;
2374 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2375 # from tag links; this also makes possible to detect branch links
2376 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2377 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2378 $branch = $1;
2380 # find log type for feed description (title)
2381 my $type = 'log';
2382 if (defined $file_name) {
2383 $type = "history of $file_name";
2384 $type .= "/" if ($action eq 'tree');
2385 $type .= " on '$branch'" if (defined $branch);
2386 } else {
2387 $type = "log of $branch" if (defined $branch);
2390 $res{-title} = $type;
2391 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2392 $res{'file_name'} = $file_name;
2394 return %res;
2397 ## ----------------------------------------------------------------------
2398 ## git utility subroutines, invoking git commands
2400 # returns path to the core git executable and the --git-dir parameter as list
2401 sub git_cmd {
2402 $number_of_git_cmds++;
2403 return $GIT, '--git-dir='.$git_dir;
2406 # quote the given arguments for passing them to the shell
2407 # quote_command("command", "arg 1", "arg with ' and ! characters")
2408 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2409 # Try to avoid using this function wherever possible.
2410 sub quote_command {
2411 return join(' ',
2412 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2415 # get HEAD ref of given project as hash
2416 sub git_get_head_hash {
2417 return git_get_full_hash(shift, 'HEAD');
2420 sub git_get_full_hash {
2421 return git_get_hash(@_);
2424 sub git_get_short_hash {
2425 return git_get_hash(@_, '--short=7');
2428 sub git_get_hash {
2429 my ($project, $hash, @options) = @_;
2430 my $o_git_dir = $git_dir;
2431 my $retval = undef;
2432 $git_dir = "$projectroot/$project";
2433 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2434 '--verify', '-q', @options, $hash) {
2435 $retval = <$fd>;
2436 chomp $retval if defined $retval;
2437 close $fd;
2439 if (defined $o_git_dir) {
2440 $git_dir = $o_git_dir;
2442 return $retval;
2445 # get type of given object
2446 sub git_get_type {
2447 my $hash = shift;
2449 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2450 my $type = <$fd>;
2451 close $fd or return;
2452 chomp $type;
2453 return $type;
2456 # repository configuration
2457 our $config_file = '';
2458 our %config;
2460 # store multiple values for single key as anonymous array reference
2461 # single values stored directly in the hash, not as [ <value> ]
2462 sub hash_set_multi {
2463 my ($hash, $key, $value) = @_;
2465 if (!exists $hash->{$key}) {
2466 $hash->{$key} = $value;
2467 } elsif (!ref $hash->{$key}) {
2468 $hash->{$key} = [ $hash->{$key}, $value ];
2469 } else {
2470 push @{$hash->{$key}}, $value;
2474 # return hash of git project configuration
2475 # optionally limited to some section, e.g. 'gitweb'
2476 sub git_parse_project_config {
2477 my $section_regexp = shift;
2478 my %config;
2480 local $/ = "\0";
2482 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2483 or return;
2485 while (my $keyval = <$fh>) {
2486 chomp $keyval;
2487 my ($key, $value) = split(/\n/, $keyval, 2);
2489 hash_set_multi(\%config, $key, $value)
2490 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2492 close $fh;
2494 return %config;
2497 # convert config value to boolean: 'true' or 'false'
2498 # no value, number > 0, 'true' and 'yes' values are true
2499 # rest of values are treated as false (never as error)
2500 sub config_to_bool {
2501 my $val = shift;
2503 return 1 if !defined $val; # section.key
2505 # strip leading and trailing whitespace
2506 $val =~ s/^\s+//;
2507 $val =~ s/\s+$//;
2509 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2510 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2513 # convert config value to simple decimal number
2514 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2515 # to be multiplied by 1024, 1048576, or 1073741824
2516 sub config_to_int {
2517 my $val = shift;
2519 # strip leading and trailing whitespace
2520 $val =~ s/^\s+//;
2521 $val =~ s/\s+$//;
2523 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2524 $unit = lc($unit);
2525 # unknown unit is treated as 1
2526 return $num * ($unit eq 'g' ? 1073741824 :
2527 $unit eq 'm' ? 1048576 :
2528 $unit eq 'k' ? 1024 : 1);
2530 return $val;
2533 # convert config value to array reference, if needed
2534 sub config_to_multi {
2535 my $val = shift;
2537 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2540 sub git_get_project_config {
2541 my ($key, $type) = @_;
2543 return unless defined $git_dir;
2545 # key sanity check
2546 return unless ($key);
2547 $key =~ s/^gitweb\.//;
2548 return if ($key =~ m/\W/);
2550 # type sanity check
2551 if (defined $type) {
2552 $type =~ s/^--//;
2553 $type = undef
2554 unless ($type eq 'bool' || $type eq 'int');
2557 # get config
2558 if (!defined $config_file ||
2559 $config_file ne "$git_dir/config") {
2560 %config = git_parse_project_config('gitweb');
2561 $config_file = "$git_dir/config";
2564 # check if config variable (key) exists
2565 return unless exists $config{"gitweb.$key"};
2567 # ensure given type
2568 if (!defined $type) {
2569 return $config{"gitweb.$key"};
2570 } elsif ($type eq 'bool') {
2571 # backward compatibility: 'git config --bool' returns true/false
2572 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2573 } elsif ($type eq 'int') {
2574 return config_to_int($config{"gitweb.$key"});
2576 return $config{"gitweb.$key"};
2579 # get hash of given path at given ref
2580 sub git_get_hash_by_path {
2581 my $base = shift;
2582 my $path = shift || return undef;
2583 my $type = shift;
2585 $path =~ s,/+$,,;
2587 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2588 or die_error(500, "Open git-ls-tree failed");
2589 my $line = <$fd>;
2590 close $fd or return undef;
2592 if (!defined $line) {
2593 # there is no tree or hash given by $path at $base
2594 return undef;
2597 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2598 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2599 if (defined $type && $type ne $2) {
2600 # type doesn't match
2601 return undef;
2603 return $3;
2606 # get path of entry with given hash at given tree-ish (ref)
2607 # used to get 'from' filename for combined diff (merge commit) for renames
2608 sub git_get_path_by_hash {
2609 my $base = shift || return;
2610 my $hash = shift || return;
2612 local $/ = "\0";
2614 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2615 or return undef;
2616 while (my $line = <$fd>) {
2617 chomp $line;
2619 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2620 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2621 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2622 close $fd;
2623 return $1;
2626 close $fd;
2627 return undef;
2630 ## ......................................................................
2631 ## git utility functions, directly accessing git repository
2633 sub git_get_project_description {
2634 my $path = shift;
2636 $git_dir = "$projectroot/$path";
2637 open my $fd, '<', "$git_dir/description"
2638 or return git_get_project_config('description');
2639 my $descr = <$fd>;
2640 close $fd;
2641 if (defined $descr) {
2642 chomp $descr;
2644 return $descr;
2647 sub git_get_project_ctags {
2648 my $path = shift;
2649 my $ctags = {};
2651 $git_dir = "$projectroot/$path";
2652 opendir my $dh, "$git_dir/ctags"
2653 or return $ctags;
2654 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2655 open my $ct, '<', $_ or next;
2656 my $val = <$ct>;
2657 chomp $val;
2658 close $ct;
2659 my $ctag = $_; $ctag =~ s#.*/##;
2660 $ctags->{$ctag} = $val;
2662 closedir $dh;
2663 $ctags;
2666 sub git_populate_project_tagcloud {
2667 my $ctags = shift;
2669 # First, merge different-cased tags; tags vote on casing
2670 my %ctags_lc;
2671 foreach (keys %$ctags) {
2672 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2673 if (not $ctags_lc{lc $_}->{topcount}
2674 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2675 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2676 $ctags_lc{lc $_}->{topname} = $_;
2680 my $cloud;
2681 if (eval { require HTML::TagCloud; 1; }) {
2682 $cloud = HTML::TagCloud->new;
2683 foreach (sort keys %ctags_lc) {
2684 # Pad the title with spaces so that the cloud looks
2685 # less crammed.
2686 my $title = $ctags_lc{$_}->{topname};
2687 $title =~ s/ /&nbsp;/g;
2688 $title =~ s/^/&nbsp;/g;
2689 $title =~ s/$/&nbsp;/g;
2690 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2692 } else {
2693 $cloud = \%ctags_lc;
2695 $cloud;
2698 sub git_show_project_tagcloud {
2699 my ($cloud, $count) = @_;
2700 print STDERR ref($cloud)."..\n";
2701 if (ref $cloud eq 'HTML::TagCloud') {
2702 return $cloud->html_and_css($count);
2703 } else {
2704 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2705 return '<p align="center">' . join (', ', map {
2706 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2707 } splice(@tags, 0, $count)) . '</p>';
2711 sub git_get_project_url_list {
2712 my $path = shift;
2714 $git_dir = "$projectroot/$path";
2715 open my $fd, '<', "$git_dir/cloneurl"
2716 or return wantarray ?
2717 @{ config_to_multi(git_get_project_config('url')) } :
2718 config_to_multi(git_get_project_config('url'));
2719 my @git_project_url_list = map { chomp; $_ } <$fd>;
2720 close $fd;
2722 return wantarray ? @git_project_url_list : \@git_project_url_list;
2725 sub git_get_projects_list {
2726 my ($filter) = @_;
2727 my @list;
2729 $filter ||= '';
2730 $filter =~ s/\.git$//;
2732 my $check_forks = gitweb_check_feature('forks');
2734 if (-d $projects_list) {
2735 # search in directory
2736 my $dir = $projects_list . ($filter ? "/$filter" : '');
2737 # remove the trailing "/"
2738 $dir =~ s!/+$!!;
2739 my $pfxlen = length("$dir");
2740 my $pfxdepth = ($dir =~ tr!/!!);
2742 File::Find::find({
2743 follow_fast => 1, # follow symbolic links
2744 follow_skip => 2, # ignore duplicates
2745 dangling_symlinks => 0, # ignore dangling symlinks, silently
2746 wanted => sub {
2747 # global variables
2748 our $project_maxdepth;
2749 our $projectroot;
2750 # skip project-list toplevel, if we get it.
2751 return if (m!^[/.]$!);
2752 # only directories can be git repositories
2753 return unless (-d $_);
2754 # don't traverse too deep (Find is super slow on os x)
2755 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2756 $File::Find::prune = 1;
2757 return;
2760 my $subdir = substr($File::Find::name, $pfxlen + 1);
2761 # we check related file in $projectroot
2762 my $path = ($filter ? "$filter/" : '') . $subdir;
2763 if (check_export_ok("$projectroot/$path")) {
2764 push @list, { path => $path };
2765 $File::Find::prune = 1;
2768 }, "$dir");
2770 } elsif (-f $projects_list) {
2771 # read from file(url-encoded):
2772 # 'git%2Fgit.git Linus+Torvalds'
2773 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2774 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2775 my %paths;
2776 open my $fd, '<', $projects_list or return;
2777 PROJECT:
2778 while (my $line = <$fd>) {
2779 chomp $line;
2780 my ($path, $owner) = split ' ', $line;
2781 $path = unescape($path);
2782 $owner = unescape($owner);
2783 if (!defined $path) {
2784 next;
2786 if ($filter ne '') {
2787 # looking for forks;
2788 my $pfx = substr($path, 0, length($filter));
2789 if ($pfx ne $filter) {
2790 next PROJECT;
2792 my $sfx = substr($path, length($filter));
2793 if ($sfx !~ /^\/.*\.git$/) {
2794 next PROJECT;
2796 } elsif ($check_forks) {
2797 PATH:
2798 foreach my $filter (keys %paths) {
2799 # looking for forks;
2800 my $pfx = substr($path, 0, length($filter));
2801 if ($pfx ne $filter) {
2802 next PATH;
2804 my $sfx = substr($path, length($filter));
2805 if ($sfx !~ /^\/.*\.git$/) {
2806 next PATH;
2808 # is a fork, don't include it in
2809 # the list
2810 next PROJECT;
2813 if (check_export_ok("$projectroot/$path")) {
2814 my $pr = {
2815 path => $path,
2816 owner => to_utf8($owner),
2818 push @list, $pr;
2819 (my $forks_path = $path) =~ s/\.git$//;
2820 $paths{$forks_path}++;
2823 close $fd;
2825 return @list;
2828 our $gitweb_project_owner = undef;
2829 sub git_get_project_list_from_file {
2831 return if (defined $gitweb_project_owner);
2833 $gitweb_project_owner = {};
2834 # read from file (url-encoded):
2835 # 'git%2Fgit.git Linus+Torvalds'
2836 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2837 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2838 if (-f $projects_list) {
2839 open(my $fd, '<', $projects_list);
2840 while (my $line = <$fd>) {
2841 chomp $line;
2842 my ($pr, $ow) = split ' ', $line;
2843 $pr = unescape($pr);
2844 $ow = unescape($ow);
2845 $gitweb_project_owner->{$pr} = to_utf8($ow);
2847 close $fd;
2851 sub git_get_project_owner {
2852 my $project = shift;
2853 my $owner;
2855 return undef unless $project;
2856 $git_dir = "$projectroot/$project";
2858 if (!defined $gitweb_project_owner) {
2859 git_get_project_list_from_file();
2862 if (exists $gitweb_project_owner->{$project}) {
2863 $owner = $gitweb_project_owner->{$project};
2865 if (!defined $owner){
2866 $owner = git_get_project_config('owner');
2868 if (!defined $owner) {
2869 $owner = get_file_owner("$git_dir");
2872 return $owner;
2875 sub git_get_last_activity {
2876 my ($path) = @_;
2877 my $fd;
2879 $git_dir = "$projectroot/$path";
2880 open($fd, "-|", git_cmd(), 'for-each-ref',
2881 '--format=%(committer)',
2882 '--sort=-committerdate',
2883 '--count=1',
2884 'refs/heads') or return;
2885 my $most_recent = <$fd>;
2886 close $fd or return;
2887 if (defined $most_recent &&
2888 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2889 my $timestamp = $1;
2890 my $age = time - $timestamp;
2891 return ($age, age_string($age));
2893 return (undef, undef);
2896 sub git_get_references {
2897 my $type = shift || "";
2898 my %refs;
2899 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2900 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2901 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2902 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2903 or return;
2905 while (my $line = <$fd>) {
2906 chomp $line;
2907 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2908 if (defined $refs{$1}) {
2909 push @{$refs{$1}}, $2;
2910 } else {
2911 $refs{$1} = [ $2 ];
2915 close $fd or return;
2916 return \%refs;
2919 sub git_get_rev_name_tags {
2920 my $hash = shift || return undef;
2922 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2923 or return;
2924 my $name_rev = <$fd>;
2925 close $fd;
2927 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2928 return $1;
2929 } else {
2930 # catches also '$hash undefined' output
2931 return undef;
2935 ## ----------------------------------------------------------------------
2936 ## parse to hash functions
2938 sub parse_date {
2939 my $epoch = shift;
2940 my $tz = shift || "-0000";
2942 my %date;
2943 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2944 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2945 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2946 $date{'hour'} = $hour;
2947 $date{'minute'} = $min;
2948 $date{'mday'} = $mday;
2949 $date{'day'} = $days[$wday];
2950 $date{'month'} = $months[$mon];
2951 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2952 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2953 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2954 $mday, $months[$mon], $hour ,$min;
2955 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2956 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2958 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2959 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2960 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2961 $date{'hour_local'} = $hour;
2962 $date{'minute_local'} = $min;
2963 $date{'tz_local'} = $tz;
2964 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2965 1900+$year, $mon+1, $mday,
2966 $hour, $min, $sec, $tz);
2967 return %date;
2970 sub parse_tag {
2971 my $tag_id = shift;
2972 my %tag;
2973 my @comment;
2975 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2976 $tag{'id'} = $tag_id;
2977 while (my $line = <$fd>) {
2978 chomp $line;
2979 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2980 $tag{'object'} = $1;
2981 } elsif ($line =~ m/^type (.+)$/) {
2982 $tag{'type'} = $1;
2983 } elsif ($line =~ m/^tag (.+)$/) {
2984 $tag{'name'} = $1;
2985 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2986 $tag{'author'} = $1;
2987 $tag{'author_epoch'} = $2;
2988 $tag{'author_tz'} = $3;
2989 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2990 $tag{'author_name'} = $1;
2991 $tag{'author_email'} = $2;
2992 } else {
2993 $tag{'author_name'} = $tag{'author'};
2995 } elsif ($line =~ m/--BEGIN/) {
2996 push @comment, $line;
2997 last;
2998 } elsif ($line eq "") {
2999 last;
3002 push @comment, <$fd>;
3003 $tag{'comment'} = \@comment;
3004 close $fd or return;
3005 if (!defined $tag{'name'}) {
3006 return
3008 return %tag
3011 sub parse_commit_text {
3012 my ($commit_text, $withparents) = @_;
3013 my @commit_lines = split '\n', $commit_text;
3014 my %co;
3016 pop @commit_lines; # Remove '\0'
3018 if (! @commit_lines) {
3019 return;
3022 my $header = shift @commit_lines;
3023 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3024 return;
3026 ($co{'id'}, my @parents) = split ' ', $header;
3027 while (my $line = shift @commit_lines) {
3028 last if $line eq "\n";
3029 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3030 $co{'tree'} = $1;
3031 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3032 push @parents, $1;
3033 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3034 $co{'author'} = to_utf8($1);
3035 $co{'author_epoch'} = $2;
3036 $co{'author_tz'} = $3;
3037 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3038 $co{'author_name'} = $1;
3039 $co{'author_email'} = $2;
3040 } else {
3041 $co{'author_name'} = $co{'author'};
3043 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3044 $co{'committer'} = to_utf8($1);
3045 $co{'committer_epoch'} = $2;
3046 $co{'committer_tz'} = $3;
3047 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3048 $co{'committer_name'} = $1;
3049 $co{'committer_email'} = $2;
3050 } else {
3051 $co{'committer_name'} = $co{'committer'};
3055 if (!defined $co{'tree'}) {
3056 return;
3058 $co{'parents'} = \@parents;
3059 $co{'parent'} = $parents[0];
3061 foreach my $title (@commit_lines) {
3062 $title =~ s/^ //;
3063 if ($title ne "") {
3064 $co{'title'} = chop_str($title, 80, 5);
3065 # remove leading stuff of merges to make the interesting part visible
3066 if (length($title) > 50) {
3067 $title =~ s/^Automatic //;
3068 $title =~ s/^merge (of|with) /Merge ... /i;
3069 if (length($title) > 50) {
3070 $title =~ s/(http|rsync):\/\///;
3072 if (length($title) > 50) {
3073 $title =~ s/(master|www|rsync)\.//;
3075 if (length($title) > 50) {
3076 $title =~ s/kernel.org:?//;
3078 if (length($title) > 50) {
3079 $title =~ s/\/pub\/scm//;
3082 $co{'title_short'} = chop_str($title, 50, 5);
3083 last;
3086 if (! defined $co{'title'} || $co{'title'} eq "") {
3087 $co{'title'} = $co{'title_short'} = '(no commit message)';
3089 # remove added spaces
3090 foreach my $line (@commit_lines) {
3091 $line =~ s/^ //;
3093 $co{'comment'} = \@commit_lines;
3095 my $age = time - $co{'committer_epoch'};
3096 $co{'age'} = $age;
3097 $co{'age_string'} = age_string($age);
3098 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3099 if ($age > 60*60*24*7*2) {
3100 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3101 $co{'age_string_age'} = $co{'age_string'};
3102 } else {
3103 $co{'age_string_date'} = $co{'age_string'};
3104 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3106 return %co;
3109 sub parse_commit {
3110 my ($commit_id) = @_;
3111 my %co;
3113 local $/ = "\0";
3115 open my $fd, "-|", git_cmd(), "rev-list",
3116 "--parents",
3117 "--header",
3118 "--max-count=1",
3119 $commit_id,
3120 "--",
3121 or die_error(500, "Open git-rev-list failed");
3122 %co = parse_commit_text(<$fd>, 1);
3123 close $fd;
3125 return %co;
3128 sub parse_commits {
3129 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3130 my @cos;
3132 $maxcount ||= 1;
3133 $skip ||= 0;
3135 local $/ = "\0";
3137 open my $fd, "-|", git_cmd(), "rev-list",
3138 "--header",
3139 @args,
3140 ("--max-count=" . $maxcount),
3141 ("--skip=" . $skip),
3142 @extra_options,
3143 $commit_id,
3144 "--",
3145 ($filename ? ($filename) : ())
3146 or die_error(500, "Open git-rev-list failed");
3147 while (my $line = <$fd>) {
3148 my %co = parse_commit_text($line);
3149 push @cos, \%co;
3151 close $fd;
3153 return wantarray ? @cos : \@cos;
3156 # parse line of git-diff-tree "raw" output
3157 sub parse_difftree_raw_line {
3158 my $line = shift;
3159 my %res;
3161 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3162 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3163 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3164 $res{'from_mode'} = $1;
3165 $res{'to_mode'} = $2;
3166 $res{'from_id'} = $3;
3167 $res{'to_id'} = $4;
3168 $res{'status'} = $5;
3169 $res{'similarity'} = $6;
3170 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3171 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3172 } else {
3173 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3176 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3177 # combined diff (for merge commit)
3178 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3179 $res{'nparents'} = length($1);
3180 $res{'from_mode'} = [ split(' ', $2) ];
3181 $res{'to_mode'} = pop @{$res{'from_mode'}};
3182 $res{'from_id'} = [ split(' ', $3) ];
3183 $res{'to_id'} = pop @{$res{'from_id'}};
3184 $res{'status'} = [ split('', $4) ];
3185 $res{'to_file'} = unquote($5);
3187 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3188 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3189 $res{'commit'} = $1;
3192 return wantarray ? %res : \%res;
3195 # wrapper: return parsed line of git-diff-tree "raw" output
3196 # (the argument might be raw line, or parsed info)
3197 sub parsed_difftree_line {
3198 my $line_or_ref = shift;
3200 if (ref($line_or_ref) eq "HASH") {
3201 # pre-parsed (or generated by hand)
3202 return $line_or_ref;
3203 } else {
3204 return parse_difftree_raw_line($line_or_ref);
3208 # parse line of git-ls-tree output
3209 sub parse_ls_tree_line {
3210 my $line = shift;
3211 my %opts = @_;
3212 my %res;
3214 if ($opts{'-l'}) {
3215 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3216 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3218 $res{'mode'} = $1;
3219 $res{'type'} = $2;
3220 $res{'hash'} = $3;
3221 $res{'size'} = $4;
3222 if ($opts{'-z'}) {
3223 $res{'name'} = $5;
3224 } else {
3225 $res{'name'} = unquote($5);
3227 } else {
3228 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3229 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3231 $res{'mode'} = $1;
3232 $res{'type'} = $2;
3233 $res{'hash'} = $3;
3234 if ($opts{'-z'}) {
3235 $res{'name'} = $4;
3236 } else {
3237 $res{'name'} = unquote($4);
3241 return wantarray ? %res : \%res;
3244 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3245 sub parse_from_to_diffinfo {
3246 my ($diffinfo, $from, $to, @parents) = @_;
3248 if ($diffinfo->{'nparents'}) {
3249 # combined diff
3250 $from->{'file'} = [];
3251 $from->{'href'} = [];
3252 fill_from_file_info($diffinfo, @parents)
3253 unless exists $diffinfo->{'from_file'};
3254 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3255 $from->{'file'}[$i] =
3256 defined $diffinfo->{'from_file'}[$i] ?
3257 $diffinfo->{'from_file'}[$i] :
3258 $diffinfo->{'to_file'};
3259 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3260 $from->{'href'}[$i] = href(action=>"blob",
3261 hash_base=>$parents[$i],
3262 hash=>$diffinfo->{'from_id'}[$i],
3263 file_name=>$from->{'file'}[$i]);
3264 } else {
3265 $from->{'href'}[$i] = undef;
3268 } else {
3269 # ordinary (not combined) diff
3270 $from->{'file'} = $diffinfo->{'from_file'};
3271 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3272 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3273 hash=>$diffinfo->{'from_id'},
3274 file_name=>$from->{'file'});
3275 } else {
3276 delete $from->{'href'};
3280 $to->{'file'} = $diffinfo->{'to_file'};
3281 if (!is_deleted($diffinfo)) { # file exists in result
3282 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3283 hash=>$diffinfo->{'to_id'},
3284 file_name=>$to->{'file'});
3285 } else {
3286 delete $to->{'href'};
3290 ## ......................................................................
3291 ## parse to array of hashes functions
3293 sub git_get_heads_list {
3294 my $limit = shift;
3295 my @headslist;
3297 open my $fd, '-|', git_cmd(), 'for-each-ref',
3298 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3299 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3300 'refs/heads'
3301 or return;
3302 while (my $line = <$fd>) {
3303 my %ref_item;
3305 chomp $line;
3306 my ($refinfo, $committerinfo) = split(/\0/, $line);
3307 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3308 my ($committer, $epoch, $tz) =
3309 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3310 $ref_item{'fullname'} = $name;
3311 $name =~ s!^refs/heads/!!;
3313 $ref_item{'name'} = $name;
3314 $ref_item{'id'} = $hash;
3315 $ref_item{'title'} = $title || '(no commit message)';
3316 $ref_item{'epoch'} = $epoch;
3317 if ($epoch) {
3318 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3319 } else {
3320 $ref_item{'age'} = "unknown";
3323 push @headslist, \%ref_item;
3325 close $fd;
3327 return wantarray ? @headslist : \@headslist;
3330 sub git_get_tags_list {
3331 my $limit = shift;
3332 my @tagslist;
3334 open my $fd, '-|', git_cmd(), 'for-each-ref',
3335 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3336 '--format=%(objectname) %(objecttype) %(refname) '.
3337 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3338 'refs/tags'
3339 or return;
3340 while (my $line = <$fd>) {
3341 my %ref_item;
3343 chomp $line;
3344 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3345 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3346 my ($creator, $epoch, $tz) =
3347 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3348 $ref_item{'fullname'} = $name;
3349 $name =~ s!^refs/tags/!!;
3351 $ref_item{'type'} = $type;
3352 $ref_item{'id'} = $id;
3353 $ref_item{'name'} = $name;
3354 if ($type eq "tag") {
3355 $ref_item{'subject'} = $title;
3356 $ref_item{'reftype'} = $reftype;
3357 $ref_item{'refid'} = $refid;
3358 } else {
3359 $ref_item{'reftype'} = $type;
3360 $ref_item{'refid'} = $id;
3363 if ($type eq "tag" || $type eq "commit") {
3364 $ref_item{'epoch'} = $epoch;
3365 if ($epoch) {
3366 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3367 } else {
3368 $ref_item{'age'} = "unknown";
3372 push @tagslist, \%ref_item;
3374 close $fd;
3376 return wantarray ? @tagslist : \@tagslist;
3379 ## ----------------------------------------------------------------------
3380 ## filesystem-related functions
3382 sub get_file_owner {
3383 my $path = shift;
3385 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3386 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3387 if (!defined $gcos) {
3388 return undef;
3390 my $owner = $gcos;
3391 $owner =~ s/[,;].*$//;
3392 return to_utf8($owner);
3395 # assume that file exists
3396 sub insert_file {
3397 my $filename = shift;
3399 open my $fd, '<', $filename;
3400 print map { to_utf8($_) } <$fd>;
3401 close $fd;
3404 ## ......................................................................
3405 ## mimetype related functions
3407 sub mimetype_guess_file {
3408 my $filename = shift;
3409 my $mimemap = shift;
3410 -r $mimemap or return undef;
3412 my %mimemap;
3413 open(my $mh, '<', $mimemap) or return undef;
3414 while (<$mh>) {
3415 next if m/^#/; # skip comments
3416 my ($mimetype, $exts) = split(/\t+/);
3417 if (defined $exts) {
3418 my @exts = split(/\s+/, $exts);
3419 foreach my $ext (@exts) {
3420 $mimemap{$ext} = $mimetype;
3424 close($mh);
3426 $filename =~ /\.([^.]*)$/;
3427 return $mimemap{$1};
3430 sub mimetype_guess {
3431 my $filename = shift;
3432 my $mime;
3433 $filename =~ /\./ or return undef;
3435 if ($mimetypes_file) {
3436 my $file = $mimetypes_file;
3437 if ($file !~ m!^/!) { # if it is relative path
3438 # it is relative to project
3439 $file = "$projectroot/$project/$file";
3441 $mime = mimetype_guess_file($filename, $file);
3443 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3444 return $mime;
3447 sub blob_mimetype {
3448 my $fd = shift;
3449 my $filename = shift;
3451 if ($filename) {
3452 my $mime = mimetype_guess($filename);
3453 $mime and return $mime;
3456 # just in case
3457 return $default_blob_plain_mimetype unless $fd;
3459 if (-T $fd) {
3460 return 'text/plain';
3461 } elsif (! $filename) {
3462 return 'application/octet-stream';
3463 } elsif ($filename =~ m/\.png$/i) {
3464 return 'image/png';
3465 } elsif ($filename =~ m/\.gif$/i) {
3466 return 'image/gif';
3467 } elsif ($filename =~ m/\.jpe?g$/i) {
3468 return 'image/jpeg';
3469 } else {
3470 return 'application/octet-stream';
3474 sub blob_contenttype {
3475 my ($fd, $file_name, $type) = @_;
3477 $type ||= blob_mimetype($fd, $file_name);
3478 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3479 $type .= "; charset=$default_text_plain_charset";
3482 return $type;
3485 # guess file syntax for syntax highlighting; return undef if no highlighting
3486 # the name of syntax can (in the future) depend on syntax highlighter used
3487 sub guess_file_syntax {
3488 my ($highlight, $mimetype, $file_name) = @_;
3489 return undef unless ($highlight && defined $file_name);
3490 my $basename = basename($file_name, '.in');
3491 return $highlight_basename{$basename}
3492 if exists $highlight_basename{$basename};
3494 $basename =~ /\.([^.]*)$/;
3495 my $ext = $1 or return undef;
3496 return $highlight_ext{$ext}
3497 if exists $highlight_ext{$ext};
3499 return undef;
3502 # run highlighter and return FD of its output,
3503 # or return original FD if no highlighting
3504 sub run_highlighter {
3505 my ($fd, $highlight, $syntax) = @_;
3506 return $fd unless ($highlight && defined $syntax);
3508 close $fd
3509 or die_error(404, "Reading blob failed");
3510 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3511 quote_command($highlight_bin).
3512 " --xhtml --fragment --syntax $syntax |"
3513 or die_error(500, "Couldn't open file or run syntax highlighter");
3514 return $fd;
3517 ## ======================================================================
3518 ## functions printing HTML: header, footer, error page
3520 sub get_page_title {
3521 my $title = to_utf8($site_name);
3523 return $title unless (defined $project);
3524 $title .= " - " . to_utf8($project);
3526 return $title unless (defined $action);
3527 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3529 return $title unless (defined $file_name);
3530 $title .= " - " . esc_path($file_name);
3531 if ($action eq "tree" && $file_name !~ m|/$|) {
3532 $title .= "/";
3535 return $title;
3538 sub git_header_html {
3539 my $status = shift || "200 OK";
3540 my $expires = shift;
3541 my %opts = @_;
3543 my $title = get_page_title();
3544 my $content_type;
3545 # require explicit support from the UA if we are to send the page as
3546 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3547 # we have to do this because MSIE sometimes globs '*/*', pretending to
3548 # support xhtml+xml but choking when it gets what it asked for.
3549 # Disable content-type negotiation when caching (use mimetype good for all).
3550 if (!$caching_enabled &&
3551 defined $cgi->http('HTTP_ACCEPT') &&
3552 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3553 $cgi->Accept('application/xhtml+xml') != 0) {
3554 $content_type = 'application/xhtml+xml';
3555 } else {
3556 $content_type = 'text/html';
3558 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3559 -status=> $status, -expires => $expires)
3560 unless ($opts{'-no_http_header'});
3561 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3562 print <<EOF;
3563 <?xml version="1.0" encoding="utf-8"?>
3564 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3565 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3566 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3567 <!-- git core binaries version $git_version -->
3568 <head>
3569 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3570 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3571 <meta name="robots" content="index, nofollow"/>
3572 <title>$title</title>
3574 # the stylesheet, favicon etc urls won't work correctly with path_info
3575 # unless we set the appropriate base URL
3576 # if caching is enabled we can get it from cache for path_info when it
3577 # is generated without path_info
3578 if ($ENV{'PATH_INFO'} || $caching_enabled) {
3579 print "<base href=\"".esc_url($base_url)."\" />\n";
3581 # print out each stylesheet that exist, providing backwards capability
3582 # for those people who defined $stylesheet in a config file
3583 if (defined $stylesheet) {
3584 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3585 } else {
3586 foreach my $stylesheet (@stylesheets) {
3587 next unless $stylesheet;
3588 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3591 if (defined $project) {
3592 my %href_params = get_feed_info();
3593 if (!exists $href_params{'-title'}) {
3594 $href_params{'-title'} = 'log';
3597 foreach my $format qw(RSS Atom) {
3598 my $type = lc($format);
3599 my %link_attr = (
3600 '-rel' => 'alternate',
3601 '-title' => "$project - $href_params{'-title'} - $format feed",
3602 '-type' => "application/$type+xml"
3605 $href_params{'action'} = $type;
3606 $link_attr{'-href'} = href(%href_params);
3607 print "<link ".
3608 "rel=\"$link_attr{'-rel'}\" ".
3609 "title=\"$link_attr{'-title'}\" ".
3610 "href=\"$link_attr{'-href'}\" ".
3611 "type=\"$link_attr{'-type'}\" ".
3612 "/>\n";
3614 $href_params{'extra_options'} = '--no-merges';
3615 $link_attr{'-href'} = href(%href_params);
3616 $link_attr{'-title'} .= ' (no merges)';
3617 print "<link ".
3618 "rel=\"$link_attr{'-rel'}\" ".
3619 "title=\"$link_attr{'-title'}\" ".
3620 "href=\"$link_attr{'-href'}\" ".
3621 "type=\"$link_attr{'-type'}\" ".
3622 "/>\n";
3625 } else {
3626 printf('<link rel="alternate" title="%s projects list" '.
3627 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3628 $site_name, href(project=>undef, action=>"project_index"));
3629 printf('<link rel="alternate" title="%s projects feeds" '.
3630 'href="%s" type="text/x-opml" />'."\n",
3631 $site_name, href(project=>undef, action=>"opml"));
3633 if (defined $favicon) {
3634 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3637 print "</head>\n" .
3638 "<body>\n";
3640 if (defined $site_header && -f $site_header) {
3641 insert_file($site_header);
3644 print "<div class=\"page_header\">\n" .
3645 $cgi->a({-href => esc_url($logo_url),
3646 -title => $logo_label},
3647 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3648 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3649 if (defined $project) {
3650 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3651 if (defined $action) {
3652 print " / $action";
3654 print "\n";
3656 print "</div>\n";
3658 my $have_search = gitweb_check_feature('search');
3659 if (defined $project && $have_search) {
3660 if (!defined $searchtext) {
3661 $searchtext = "";
3663 my $search_hash;
3664 if (defined $hash_base) {
3665 $search_hash = $hash_base;
3666 } elsif (defined $hash) {
3667 $search_hash = $hash;
3668 } else {
3669 $search_hash = "HEAD";
3671 my $action = $my_uri;
3672 my $use_pathinfo = gitweb_check_feature('pathinfo');
3673 if ($use_pathinfo) {
3674 $action .= "/".esc_url($project);
3676 print $cgi->startform(-method => "get", -action => $action) .
3677 "<div class=\"search\">\n" .
3678 (!$use_pathinfo &&
3679 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3680 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3681 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3682 $cgi->popup_menu(-name => 'st', -default => 'commit',
3683 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3684 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3685 " search:\n",
3686 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3687 "<span title=\"Extended regular expression\">" .
3688 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3689 -checked => $search_use_regexp) .
3690 "</span>" .
3691 "</div>" .
3692 $cgi->end_form() . "\n";
3696 sub git_footer_html {
3697 my $feed_class = 'rss_logo';
3699 print "<div class=\"page_footer\">\n";
3700 if (defined $project) {
3701 my $descr = git_get_project_description($project);
3702 if (defined $descr) {
3703 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3706 my %href_params = get_feed_info();
3707 if (!%href_params) {
3708 $feed_class .= ' generic';
3710 $href_params{'-title'} ||= 'log';
3712 foreach my $format qw(RSS Atom) {
3713 $href_params{'action'} = lc($format);
3714 print $cgi->a({-href => href(%href_params),
3715 -title => "$href_params{'-title'} $format feed",
3716 -class => $feed_class}, $format)."\n";
3719 } else {
3720 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3721 -class => $feed_class}, "OPML") . " ";
3722 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3723 -class => $feed_class}, "TXT") . "\n";
3725 print "</div>\n"; # class="page_footer"
3727 # timing info doesn't make much sense with output (response) caching,
3728 # so when caching is enabled gitweb prints the time of page generation
3729 if ((defined $t0 || $caching_enabled) &&
3730 gitweb_check_feature('timed')) {
3731 print "<div id=\"generating_info\">\n";
3732 if ($caching_enabled) {
3733 print 'This page was generated at '.
3734 gmtime( time() )." GMT\n";
3735 } else {
3736 print 'This page took '.
3737 '<span id="generating_time" class="time_span">'.
3738 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3739 ' seconds </span>'.
3740 ' and '.
3741 '<span id="generating_cmd">'.
3742 $number_of_git_cmds.
3743 '</span> git commands '.
3744 " to generate.\n";
3746 print "</div>\n"; # class="page_footer"
3749 if (defined $site_footer && -f $site_footer) {
3750 insert_file($site_footer);
3753 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3754 if (!$caching_enabled &&
3755 defined $action && $action eq 'blame_incremental') {
3756 print qq!<script type="text/javascript">\n!.
3757 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3758 qq! "!. href() .qq!");\n!.
3759 qq!</script>\n!;
3760 } elsif (gitweb_check_feature('javascript-actions')) {
3761 print qq!<script type="text/javascript">\n!.
3762 qq!window.onload = fixLinks;\n!.
3763 qq!</script>\n!;
3766 print "</body>\n" .
3767 "</html>";
3770 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3771 # Example: die_error(404, 'Hash not found')
3772 # By convention, use the following status codes (as defined in RFC 2616):
3773 # 400: Invalid or missing CGI parameters, or
3774 # requested object exists but has wrong type.
3775 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3776 # this server or project.
3777 # 404: Requested object/revision/project doesn't exist.
3778 # 500: The server isn't configured properly, or
3779 # an internal error occurred (e.g. failed assertions caused by bugs), or
3780 # an unknown error occurred (e.g. the git binary died unexpectedly).
3781 # 503: The server is currently unavailable (because it is overloaded,
3782 # or down for maintenance). Generally, this is a temporary state.
3783 sub die_error {
3784 my $status = shift || 500;
3785 my $error = esc_html(shift) || "Internal Server Error";
3786 my $extra = shift;
3787 my %opts = @_;
3789 my %http_responses = (
3790 400 => '400 Bad Request',
3791 403 => '403 Forbidden',
3792 404 => '404 Not Found',
3793 500 => '500 Internal Server Error',
3794 503 => '503 Service Unavailable',
3797 # Do not cache error pages
3798 capture_stop($cache, $capture) if ($capture && $caching_enabled);
3800 git_header_html($http_responses{$status}, undef, %opts);
3801 print <<EOF;
3802 <div class="page_body">
3803 <br /><br />
3804 $status - $error
3805 <br />
3807 if (defined $extra) {
3808 print "<hr />\n" .
3809 "$extra\n";
3811 print "</div>\n";
3813 git_footer_html();
3814 goto DONE_GITWEB
3815 unless ($opts{'-error_handler'});
3818 ## ----------------------------------------------------------------------
3819 ## functions printing or outputting HTML: navigation
3821 sub git_print_page_nav {
3822 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3823 $extra = '' if !defined $extra; # pager or formats
3825 my @navs = qw(summary shortlog log commit commitdiff tree);
3826 if ($suppress) {
3827 @navs = grep { $_ ne $suppress } @navs;
3830 my %arg = map { $_ => {action=>$_} } @navs;
3831 if (defined $head) {
3832 for (qw(commit commitdiff)) {
3833 $arg{$_}{'hash'} = $head;
3835 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3836 for (qw(shortlog log)) {
3837 $arg{$_}{'hash'} = $head;
3842 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3843 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3845 my @actions = gitweb_get_feature('actions');
3846 my %repl = (
3847 '%' => '%',
3848 'n' => $project, # project name
3849 'f' => $git_dir, # project path within filesystem
3850 'h' => $treehead || '', # current hash ('h' parameter)
3851 'b' => $treebase || '', # hash base ('hb' parameter)
3853 while (@actions) {
3854 my ($label, $link, $pos) = splice(@actions,0,3);
3855 # insert
3856 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3857 # munch munch
3858 $link =~ s/%([%nfhb])/$repl{$1}/g;
3859 $arg{$label}{'_href'} = $link;
3862 print "<div class=\"page_nav\">\n" .
3863 (join " | ",
3864 map { $_ eq $current ?
3865 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3866 } @navs);
3867 print "<br/>\n$extra<br/>\n" .
3868 "</div>\n";
3871 sub format_paging_nav {
3872 my ($action, $page, $has_next_link) = @_;
3873 my $paging_nav;
3876 if ($page > 0) {
3877 $paging_nav .=
3878 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3879 " &sdot; " .
3880 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3881 -accesskey => "p", -title => "Alt-p"}, "prev");
3882 } else {
3883 $paging_nav .= "first &sdot; prev";
3886 if ($has_next_link) {
3887 $paging_nav .= " &sdot; " .
3888 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3889 -accesskey => "n", -title => "Alt-n"}, "next");
3890 } else {
3891 $paging_nav .= " &sdot; next";
3894 return $paging_nav;
3897 ## ......................................................................
3898 ## functions printing or outputting HTML: div
3900 sub git_print_header_div {
3901 my ($action, $title, $hash, $hash_base) = @_;
3902 my %args = ();
3904 $args{'action'} = $action;
3905 $args{'hash'} = $hash if $hash;
3906 $args{'hash_base'} = $hash_base if $hash_base;
3908 print "<div class=\"header\">\n" .
3909 $cgi->a({-href => href(%args), -class => "title"},
3910 $title ? $title : $action) .
3911 "\n</div>\n";
3914 sub print_local_time {
3915 print format_local_time(@_);
3918 sub format_local_time {
3919 my $localtime = '';
3920 my %date = @_;
3921 if ($date{'hour_local'} < 6) {
3922 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3923 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3924 } else {
3925 $localtime .= sprintf(" (%02d:%02d %s)",
3926 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3929 return $localtime;
3932 # Outputs the author name and date in long form
3933 sub git_print_authorship {
3934 my $co = shift;
3935 my %opts = @_;
3936 my $tag = $opts{-tag} || 'div';
3937 my $author = $co->{'author_name'};
3939 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3940 print "<$tag class=\"author_date\">" .
3941 format_search_author($author, "author", esc_html($author)) .
3942 " [$ad{'rfc2822'}";
3943 print_local_time(%ad) if ($opts{-localtime});
3944 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3945 . "</$tag>\n";
3948 # Outputs table rows containing the full author or committer information,
3949 # in the format expected for 'commit' view (& similar).
3950 # Parameters are a commit hash reference, followed by the list of people
3951 # to output information for. If the list is empty it defaults to both
3952 # author and committer.
3953 sub git_print_authorship_rows {
3954 my $co = shift;
3955 # too bad we can't use @people = @_ || ('author', 'committer')
3956 my @people = @_;
3957 @people = ('author', 'committer') unless @people;
3958 foreach my $who (@people) {
3959 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3960 print "<tr><td>$who</td><td>" .
3961 format_search_author($co->{"${who}_name"}, $who,
3962 esc_html($co->{"${who}_name"})) . " " .
3963 format_search_author($co->{"${who}_email"}, $who,
3964 esc_html("<" . $co->{"${who}_email"} . ">")) .
3965 "</td><td rowspan=\"2\">" .
3966 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3967 "</td></tr>\n" .
3968 "<tr>" .
3969 "<td></td><td> $wd{'rfc2822'}";
3970 print_local_time(%wd);
3971 print "</td>" .
3972 "</tr>\n";
3976 sub git_print_page_path {
3977 my $name = shift;
3978 my $type = shift;
3979 my $hb = shift;
3982 print "<div class=\"page_path\">";
3983 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3984 -title => 'tree root'}, to_utf8("[$project]"));
3985 print " / ";
3986 if (defined $name) {
3987 my @dirname = split '/', $name;
3988 my $basename = pop @dirname;
3989 my $fullname = '';
3991 foreach my $dir (@dirname) {
3992 $fullname .= ($fullname ? '/' : '') . $dir;
3993 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3994 hash_base=>$hb),
3995 -title => $fullname}, esc_path($dir));
3996 print " / ";
3998 if (defined $type && $type eq 'blob') {
3999 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4000 hash_base=>$hb),
4001 -title => $name}, esc_path($basename));
4002 } elsif (defined $type && $type eq 'tree') {
4003 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4004 hash_base=>$hb),
4005 -title => $name}, esc_path($basename));
4006 print " / ";
4007 } else {
4008 print esc_path($basename);
4011 print "<br/></div>\n";
4014 sub git_print_log {
4015 my $log = shift;
4016 my %opts = @_;
4018 if ($opts{'-remove_title'}) {
4019 # remove title, i.e. first line of log
4020 shift @$log;
4022 # remove leading empty lines
4023 while (defined $log->[0] && $log->[0] eq "") {
4024 shift @$log;
4027 # print log
4028 my $signoff = 0;
4029 my $empty = 0;
4030 foreach my $line (@$log) {
4031 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4032 $signoff = 1;
4033 $empty = 0;
4034 if (! $opts{'-remove_signoff'}) {
4035 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4036 next;
4037 } else {
4038 # remove signoff lines
4039 next;
4041 } else {
4042 $signoff = 0;
4045 # print only one empty line
4046 # do not print empty line after signoff
4047 if ($line eq "") {
4048 next if ($empty || $signoff);
4049 $empty = 1;
4050 } else {
4051 $empty = 0;
4054 print format_log_line_html($line) . "<br/>\n";
4057 if ($opts{'-final_empty_line'}) {
4058 # end with single empty line
4059 print "<br/>\n" unless $empty;
4063 # return link target (what link points to)
4064 sub git_get_link_target {
4065 my $hash = shift;
4066 my $link_target;
4068 # read link
4069 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4070 or return;
4072 local $/ = undef;
4073 $link_target = <$fd>;
4075 close $fd
4076 or return;
4078 return $link_target;
4081 # given link target, and the directory (basedir) the link is in,
4082 # return target of link relative to top directory (top tree);
4083 # return undef if it is not possible (including absolute links).
4084 sub normalize_link_target {
4085 my ($link_target, $basedir) = @_;
4087 # absolute symlinks (beginning with '/') cannot be normalized
4088 return if (substr($link_target, 0, 1) eq '/');
4090 # normalize link target to path from top (root) tree (dir)
4091 my $path;
4092 if ($basedir) {
4093 $path = $basedir . '/' . $link_target;
4094 } else {
4095 # we are in top (root) tree (dir)
4096 $path = $link_target;
4099 # remove //, /./, and /../
4100 my @path_parts;
4101 foreach my $part (split('/', $path)) {
4102 # discard '.' and ''
4103 next if (!$part || $part eq '.');
4104 # handle '..'
4105 if ($part eq '..') {
4106 if (@path_parts) {
4107 pop @path_parts;
4108 } else {
4109 # link leads outside repository (outside top dir)
4110 return;
4112 } else {
4113 push @path_parts, $part;
4116 $path = join('/', @path_parts);
4118 return $path;
4121 # print tree entry (row of git_tree), but without encompassing <tr> element
4122 sub git_print_tree_entry {
4123 my ($t, $basedir, $hash_base, $have_blame) = @_;
4125 my %base_key = ();
4126 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4128 # The format of a table row is: mode list link. Where mode is
4129 # the mode of the entry, list is the name of the entry, an href,
4130 # and link is the action links of the entry.
4132 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4133 if (exists $t->{'size'}) {
4134 print "<td class=\"size\">$t->{'size'}</td>\n";
4136 if ($t->{'type'} eq "blob") {
4137 print "<td class=\"list\">" .
4138 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4139 file_name=>"$basedir$t->{'name'}", %base_key),
4140 -class => "list"}, esc_path($t->{'name'}));
4141 if (S_ISLNK(oct $t->{'mode'})) {
4142 my $link_target = git_get_link_target($t->{'hash'});
4143 if ($link_target) {
4144 my $norm_target = normalize_link_target($link_target, $basedir);
4145 if (defined $norm_target) {
4146 print " -> " .
4147 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4148 file_name=>$norm_target),
4149 -title => $norm_target}, esc_path($link_target));
4150 } else {
4151 print " -> " . esc_path($link_target);
4155 print "</td>\n";
4156 print "<td class=\"link\">";
4157 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4158 file_name=>"$basedir$t->{'name'}", %base_key)},
4159 "blob");
4160 if ($have_blame) {
4161 print " | " .
4162 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4163 file_name=>"$basedir$t->{'name'}", %base_key)},
4164 "blame");
4166 if (defined $hash_base) {
4167 print " | " .
4168 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4169 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4170 "history");
4172 print " | " .
4173 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4174 file_name=>"$basedir$t->{'name'}")},
4175 "raw");
4176 print "</td>\n";
4178 } elsif ($t->{'type'} eq "tree") {
4179 print "<td class=\"list\">";
4180 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4181 file_name=>"$basedir$t->{'name'}",
4182 %base_key)},
4183 esc_path($t->{'name'}));
4184 print "</td>\n";
4185 print "<td class=\"link\">";
4186 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4187 file_name=>"$basedir$t->{'name'}",
4188 %base_key)},
4189 "tree");
4190 if (defined $hash_base) {
4191 print " | " .
4192 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4193 file_name=>"$basedir$t->{'name'}")},
4194 "history");
4196 print "</td>\n";
4197 } else {
4198 # unknown object: we can only present history for it
4199 # (this includes 'commit' object, i.e. submodule support)
4200 print "<td class=\"list\">" .
4201 esc_path($t->{'name'}) .
4202 "</td>\n";
4203 print "<td class=\"link\">";
4204 if (defined $hash_base) {
4205 print $cgi->a({-href => href(action=>"history",
4206 hash_base=>$hash_base,
4207 file_name=>"$basedir$t->{'name'}")},
4208 "history");
4210 print "</td>\n";
4214 ## ......................................................................
4215 ## functions printing large fragments of HTML
4217 # get pre-image filenames for merge (combined) diff
4218 sub fill_from_file_info {
4219 my ($diff, @parents) = @_;
4221 $diff->{'from_file'} = [ ];
4222 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4223 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4224 if ($diff->{'status'}[$i] eq 'R' ||
4225 $diff->{'status'}[$i] eq 'C') {
4226 $diff->{'from_file'}[$i] =
4227 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4231 return $diff;
4234 # is current raw difftree line of file deletion
4235 sub is_deleted {
4236 my $diffinfo = shift;
4238 return $diffinfo->{'to_id'} eq ('0' x 40);
4241 # does patch correspond to [previous] difftree raw line
4242 # $diffinfo - hashref of parsed raw diff format
4243 # $patchinfo - hashref of parsed patch diff format
4244 # (the same keys as in $diffinfo)
4245 sub is_patch_split {
4246 my ($diffinfo, $patchinfo) = @_;
4248 return defined $diffinfo && defined $patchinfo
4249 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4253 sub git_difftree_body {
4254 my ($difftree, $hash, @parents) = @_;
4255 my ($parent) = $parents[0];
4256 my $have_blame = gitweb_check_feature('blame');
4257 print "<div class=\"list_head\">\n";
4258 if ($#{$difftree} > 10) {
4259 print(($#{$difftree} + 1) . " files changed:\n");
4261 print "</div>\n";
4263 print "<table class=\"" .
4264 (@parents > 1 ? "combined " : "") .
4265 "diff_tree\">\n";
4267 # header only for combined diff in 'commitdiff' view
4268 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4269 if ($has_header) {
4270 # table header
4271 print "<thead><tr>\n" .
4272 "<th></th><th></th>\n"; # filename, patchN link
4273 for (my $i = 0; $i < @parents; $i++) {
4274 my $par = $parents[$i];
4275 print "<th>" .
4276 $cgi->a({-href => href(action=>"commitdiff",
4277 hash=>$hash, hash_parent=>$par),
4278 -title => 'commitdiff to parent number ' .
4279 ($i+1) . ': ' . substr($par,0,7)},
4280 $i+1) .
4281 "&nbsp;</th>\n";
4283 print "</tr></thead>\n<tbody>\n";
4286 my $alternate = 1;
4287 my $patchno = 0;
4288 foreach my $line (@{$difftree}) {
4289 my $diff = parsed_difftree_line($line);
4291 if ($alternate) {
4292 print "<tr class=\"dark\">\n";
4293 } else {
4294 print "<tr class=\"light\">\n";
4296 $alternate ^= 1;
4298 if (exists $diff->{'nparents'}) { # combined diff
4300 fill_from_file_info($diff, @parents)
4301 unless exists $diff->{'from_file'};
4303 if (!is_deleted($diff)) {
4304 # file exists in the result (child) commit
4305 print "<td>" .
4306 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4307 file_name=>$diff->{'to_file'},
4308 hash_base=>$hash),
4309 -class => "list"}, esc_path($diff->{'to_file'})) .
4310 "</td>\n";
4311 } else {
4312 print "<td>" .
4313 esc_path($diff->{'to_file'}) .
4314 "</td>\n";
4317 if ($action eq 'commitdiff') {
4318 # link to patch
4319 $patchno++;
4320 print "<td class=\"link\">" .
4321 $cgi->a({-href => "#patch$patchno"}, "patch") .
4322 " | " .
4323 "</td>\n";
4326 my $has_history = 0;
4327 my $not_deleted = 0;
4328 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4329 my $hash_parent = $parents[$i];
4330 my $from_hash = $diff->{'from_id'}[$i];
4331 my $from_path = $diff->{'from_file'}[$i];
4332 my $status = $diff->{'status'}[$i];
4334 $has_history ||= ($status ne 'A');
4335 $not_deleted ||= ($status ne 'D');
4337 if ($status eq 'A') {
4338 print "<td class=\"link\" align=\"right\"> | </td>\n";
4339 } elsif ($status eq 'D') {
4340 print "<td class=\"link\">" .
4341 $cgi->a({-href => href(action=>"blob",
4342 hash_base=>$hash,
4343 hash=>$from_hash,
4344 file_name=>$from_path)},
4345 "blob" . ($i+1)) .
4346 " | </td>\n";
4347 } else {
4348 if ($diff->{'to_id'} eq $from_hash) {
4349 print "<td class=\"link nochange\">";
4350 } else {
4351 print "<td class=\"link\">";
4353 print $cgi->a({-href => href(action=>"blobdiff",
4354 hash=>$diff->{'to_id'},
4355 hash_parent=>$from_hash,
4356 hash_base=>$hash,
4357 hash_parent_base=>$hash_parent,
4358 file_name=>$diff->{'to_file'},
4359 file_parent=>$from_path)},
4360 "diff" . ($i+1)) .
4361 " | </td>\n";
4365 print "<td class=\"link\">";
4366 if ($not_deleted) {
4367 print $cgi->a({-href => href(action=>"blob",
4368 hash=>$diff->{'to_id'},
4369 file_name=>$diff->{'to_file'},
4370 hash_base=>$hash)},
4371 "blob");
4372 print " | " if ($has_history);
4374 if ($has_history) {
4375 print $cgi->a({-href => href(action=>"history",
4376 file_name=>$diff->{'to_file'},
4377 hash_base=>$hash)},
4378 "history");
4380 print "</td>\n";
4382 print "</tr>\n";
4383 next; # instead of 'else' clause, to avoid extra indent
4385 # else ordinary diff
4387 my ($to_mode_oct, $to_mode_str, $to_file_type);
4388 my ($from_mode_oct, $from_mode_str, $from_file_type);
4389 if ($diff->{'to_mode'} ne ('0' x 6)) {
4390 $to_mode_oct = oct $diff->{'to_mode'};
4391 if (S_ISREG($to_mode_oct)) { # only for regular file
4392 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4394 $to_file_type = file_type($diff->{'to_mode'});
4396 if ($diff->{'from_mode'} ne ('0' x 6)) {
4397 $from_mode_oct = oct $diff->{'from_mode'};
4398 if (S_ISREG($to_mode_oct)) { # only for regular file
4399 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4401 $from_file_type = file_type($diff->{'from_mode'});
4404 if ($diff->{'status'} eq "A") { # created
4405 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4406 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4407 $mode_chng .= "]</span>";
4408 print "<td>";
4409 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4410 hash_base=>$hash, file_name=>$diff->{'file'}),
4411 -class => "list"}, esc_path($diff->{'file'}));
4412 print "</td>\n";
4413 print "<td>$mode_chng</td>\n";
4414 print "<td class=\"link\">";
4415 if ($action eq 'commitdiff') {
4416 # link to patch
4417 $patchno++;
4418 print $cgi->a({-href => "#patch$patchno"}, "patch");
4419 print " | ";
4421 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4422 hash_base=>$hash, file_name=>$diff->{'file'})},
4423 "blob");
4424 print "</td>\n";
4426 } elsif ($diff->{'status'} eq "D") { # deleted
4427 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4428 print "<td>";
4429 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4430 hash_base=>$parent, file_name=>$diff->{'file'}),
4431 -class => "list"}, esc_path($diff->{'file'}));
4432 print "</td>\n";
4433 print "<td>$mode_chng</td>\n";
4434 print "<td class=\"link\">";
4435 if ($action eq 'commitdiff') {
4436 # link to patch
4437 $patchno++;
4438 print $cgi->a({-href => "#patch$patchno"}, "patch");
4439 print " | ";
4441 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4442 hash_base=>$parent, file_name=>$diff->{'file'})},
4443 "blob") . " | ";
4444 if ($have_blame) {
4445 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4446 file_name=>$diff->{'file'})},
4447 "blame") . " | ";
4449 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4450 file_name=>$diff->{'file'})},
4451 "history");
4452 print "</td>\n";
4454 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4455 my $mode_chnge = "";
4456 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4457 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4458 if ($from_file_type ne $to_file_type) {
4459 $mode_chnge .= " from $from_file_type to $to_file_type";
4461 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4462 if ($from_mode_str && $to_mode_str) {
4463 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4464 } elsif ($to_mode_str) {
4465 $mode_chnge .= " mode: $to_mode_str";
4468 $mode_chnge .= "]</span>\n";
4470 print "<td>";
4471 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4472 hash_base=>$hash, file_name=>$diff->{'file'}),
4473 -class => "list"}, esc_path($diff->{'file'}));
4474 print "</td>\n";
4475 print "<td>$mode_chnge</td>\n";
4476 print "<td class=\"link\">";
4477 if ($action eq 'commitdiff') {
4478 # link to patch
4479 $patchno++;
4480 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4481 " | ";
4482 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4483 # "commit" view and modified file (not onlu mode changed)
4484 print $cgi->a({-href => href(action=>"blobdiff",
4485 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4486 hash_base=>$hash, hash_parent_base=>$parent,
4487 file_name=>$diff->{'file'})},
4488 "diff") .
4489 " | ";
4491 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4492 hash_base=>$hash, file_name=>$diff->{'file'})},
4493 "blob") . " | ";
4494 if ($have_blame) {
4495 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4496 file_name=>$diff->{'file'})},
4497 "blame") . " | ";
4499 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4500 file_name=>$diff->{'file'})},
4501 "history");
4502 print "</td>\n";
4504 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4505 my %status_name = ('R' => 'moved', 'C' => 'copied');
4506 my $nstatus = $status_name{$diff->{'status'}};
4507 my $mode_chng = "";
4508 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4509 # mode also for directories, so we cannot use $to_mode_str
4510 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4512 print "<td>" .
4513 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4514 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4515 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4516 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4517 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4518 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4519 -class => "list"}, esc_path($diff->{'from_file'})) .
4520 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4521 "<td class=\"link\">";
4522 if ($action eq 'commitdiff') {
4523 # link to patch
4524 $patchno++;
4525 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4526 " | ";
4527 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4528 # "commit" view and modified file (not only pure rename or copy)
4529 print $cgi->a({-href => href(action=>"blobdiff",
4530 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4531 hash_base=>$hash, hash_parent_base=>$parent,
4532 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4533 "diff") .
4534 " | ";
4536 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4537 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4538 "blob") . " | ";
4539 if ($have_blame) {
4540 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4541 file_name=>$diff->{'to_file'})},
4542 "blame") . " | ";
4544 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4545 file_name=>$diff->{'to_file'})},
4546 "history");
4547 print "</td>\n";
4549 } # we should not encounter Unmerged (U) or Unknown (X) status
4550 print "</tr>\n";
4552 print "</tbody>" if $has_header;
4553 print "</table>\n";
4556 sub git_patchset_body {
4557 my ($fd, $difftree, $hash, @hash_parents) = @_;
4558 my ($hash_parent) = $hash_parents[0];
4560 my $is_combined = (@hash_parents > 1);
4561 my $patch_idx = 0;
4562 my $patch_number = 0;
4563 my $patch_line;
4564 my $diffinfo;
4565 my $to_name;
4566 my (%from, %to);
4568 print "<div class=\"patchset\">\n";
4570 # skip to first patch
4571 while ($patch_line = <$fd>) {
4572 chomp $patch_line;
4574 last if ($patch_line =~ m/^diff /);
4577 PATCH:
4578 while ($patch_line) {
4580 # parse "git diff" header line
4581 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4582 # $1 is from_name, which we do not use
4583 $to_name = unquote($2);
4584 $to_name =~ s!^b/!!;
4585 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4586 # $1 is 'cc' or 'combined', which we do not use
4587 $to_name = unquote($2);
4588 } else {
4589 $to_name = undef;
4592 # check if current patch belong to current raw line
4593 # and parse raw git-diff line if needed
4594 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4595 # this is continuation of a split patch
4596 print "<div class=\"patch cont\">\n";
4597 } else {
4598 # advance raw git-diff output if needed
4599 $patch_idx++ if defined $diffinfo;
4601 # read and prepare patch information
4602 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4604 # compact combined diff output can have some patches skipped
4605 # find which patch (using pathname of result) we are at now;
4606 if ($is_combined) {
4607 while ($to_name ne $diffinfo->{'to_file'}) {
4608 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4609 format_diff_cc_simplified($diffinfo, @hash_parents) .
4610 "</div>\n"; # class="patch"
4612 $patch_idx++;
4613 $patch_number++;
4615 last if $patch_idx > $#$difftree;
4616 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4620 # modifies %from, %to hashes
4621 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4623 # this is first patch for raw difftree line with $patch_idx index
4624 # we index @$difftree array from 0, but number patches from 1
4625 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4628 # git diff header
4629 #assert($patch_line =~ m/^diff /) if DEBUG;
4630 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4631 $patch_number++;
4632 # print "git diff" header
4633 print format_git_diff_header_line($patch_line, $diffinfo,
4634 \%from, \%to);
4636 # print extended diff header
4637 print "<div class=\"diff extended_header\">\n";
4638 EXTENDED_HEADER:
4639 while ($patch_line = <$fd>) {
4640 chomp $patch_line;
4642 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4644 print format_extended_diff_header_line($patch_line, $diffinfo,
4645 \%from, \%to);
4647 print "</div>\n"; # class="diff extended_header"
4649 # from-file/to-file diff header
4650 if (! $patch_line) {
4651 print "</div>\n"; # class="patch"
4652 last PATCH;
4654 next PATCH if ($patch_line =~ m/^diff /);
4655 #assert($patch_line =~ m/^---/) if DEBUG;
4657 my $last_patch_line = $patch_line;
4658 $patch_line = <$fd>;
4659 chomp $patch_line;
4660 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4662 print format_diff_from_to_header($last_patch_line, $patch_line,
4663 $diffinfo, \%from, \%to,
4664 @hash_parents);
4666 # the patch itself
4667 LINE:
4668 while ($patch_line = <$fd>) {
4669 chomp $patch_line;
4671 next PATCH if ($patch_line =~ m/^diff /);
4673 print format_diff_line($patch_line, \%from, \%to);
4676 } continue {
4677 print "</div>\n"; # class="patch"
4680 # for compact combined (--cc) format, with chunk and patch simplification
4681 # the patchset might be empty, but there might be unprocessed raw lines
4682 for (++$patch_idx if $patch_number > 0;
4683 $patch_idx < @$difftree;
4684 ++$patch_idx) {
4685 # read and prepare patch information
4686 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4688 # generate anchor for "patch" links in difftree / whatchanged part
4689 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4690 format_diff_cc_simplified($diffinfo, @hash_parents) .
4691 "</div>\n"; # class="patch"
4693 $patch_number++;
4696 if ($patch_number == 0) {
4697 if (@hash_parents > 1) {
4698 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4699 } else {
4700 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4704 print "</div>\n"; # class="patchset"
4707 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4709 # fills project list info (age, description, owner, forks) for each
4710 # project in the list, removing invalid projects from returned list
4711 # NOTE: modifies $projlist, but does not remove entries from it
4712 sub fill_project_list_info {
4713 my ($projlist, $check_forks) = @_;
4714 my @projects;
4716 my $show_ctags = gitweb_check_feature('ctags');
4717 PROJECT:
4718 foreach my $pr (@$projlist) {
4719 my (@activity) = git_get_last_activity($pr->{'path'});
4720 unless (@activity) {
4721 next PROJECT;
4723 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4724 if (!defined $pr->{'descr'}) {
4725 my $descr = git_get_project_description($pr->{'path'}) || "";
4726 $descr = to_utf8($descr);
4727 $pr->{'descr_long'} = $descr;
4728 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4730 if (!defined $pr->{'owner'}) {
4731 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4733 if ($check_forks) {
4734 my $pname = $pr->{'path'};
4735 if (($pname =~ s/\.git$//) &&
4736 ($pname !~ /\/$/) &&
4737 (-d "$projectroot/$pname")) {
4738 $pr->{'forks'} = "-d $projectroot/$pname";
4739 } else {
4740 $pr->{'forks'} = 0;
4743 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4744 push @projects, $pr;
4747 return @projects;
4750 # print 'sort by' <th> element, generating 'sort by $name' replay link
4751 # if that order is not selected
4752 sub print_sort_th {
4753 print format_sort_th(@_);
4756 sub format_sort_th {
4757 my ($name, $order, $header) = @_;
4758 my $sort_th = "";
4759 $header ||= ucfirst($name);
4761 if ($order eq $name) {
4762 $sort_th .= "<th>$header</th>\n";
4763 } else {
4764 $sort_th .= "<th>" .
4765 $cgi->a({-href => href(-replay=>1, order=>$name),
4766 -class => "header"}, $header) .
4767 "</th>\n";
4770 return $sort_th;
4773 sub git_project_list_body {
4774 # actually uses global variable $project
4775 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4777 my $check_forks = gitweb_check_feature('forks');
4778 my @projects = fill_project_list_info($projlist, $check_forks);
4780 $order ||= $default_projects_order;
4781 $from = 0 unless defined $from;
4782 $to = $#projects if (!defined $to || $#projects < $to);
4784 my %order_info = (
4785 project => { key => 'path', type => 'str' },
4786 descr => { key => 'descr_long', type => 'str' },
4787 owner => { key => 'owner', type => 'str' },
4788 age => { key => 'age', type => 'num' }
4790 my $oi = $order_info{$order};
4791 if ($oi->{'type'} eq 'str') {
4792 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4793 } else {
4794 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4797 my $show_ctags = gitweb_check_feature('ctags');
4798 if ($show_ctags) {
4799 my %ctags;
4800 foreach my $p (@projects) {
4801 foreach my $ct (keys %{$p->{'ctags'}}) {
4802 $ctags{$ct} += $p->{'ctags'}->{$ct};
4805 my $cloud = git_populate_project_tagcloud(\%ctags);
4806 print git_show_project_tagcloud($cloud, 64);
4809 print "<table class=\"project_list\">\n";
4810 unless ($no_header) {
4811 print "<tr>\n";
4812 if ($check_forks) {
4813 print "<th></th>\n";
4815 print_sort_th('project', $order, 'Project');
4816 print_sort_th('descr', $order, 'Description');
4817 print_sort_th('owner', $order, 'Owner');
4818 print_sort_th('age', $order, 'Last Change');
4819 print "<th></th>\n" . # for links
4820 "</tr>\n";
4822 my $alternate = 1;
4823 my $tagfilter = $cgi->param('by_tag');
4824 for (my $i = $from; $i <= $to; $i++) {
4825 my $pr = $projects[$i];
4827 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4828 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4829 and not $pr->{'descr_long'} =~ /$searchtext/;
4830 # Weed out forks or non-matching entries of search
4831 if ($check_forks) {
4832 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4833 $forkbase="^$forkbase" if $forkbase;
4834 next if not $searchtext and not $tagfilter and $show_ctags
4835 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4838 if ($alternate) {
4839 print "<tr class=\"dark\">\n";
4840 } else {
4841 print "<tr class=\"light\">\n";
4843 $alternate ^= 1;
4844 if ($check_forks) {
4845 print "<td>";
4846 if ($pr->{'forks'}) {
4847 print "<!-- $pr->{'forks'} -->\n";
4848 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4850 print "</td>\n";
4852 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4853 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4854 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4855 -class => "list", -title => $pr->{'descr_long'}},
4856 esc_html($pr->{'descr'})) . "</td>\n" .
4857 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4858 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4859 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4860 "<td class=\"link\">" .
4861 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4862 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4863 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4864 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4865 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4866 "</td>\n" .
4867 "</tr>\n";
4869 if (defined $extra) {
4870 print "<tr>\n";
4871 if ($check_forks) {
4872 print "<td></td>\n";
4874 print "<td colspan=\"5\">$extra</td>\n" .
4875 "</tr>\n";
4877 print "</table>\n";
4880 sub git_log_body {
4881 # uses global variable $project
4882 my ($commitlist, $from, $to, $refs, $extra) = @_;
4884 $from = 0 unless defined $from;
4885 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4887 for (my $i = 0; $i <= $to; $i++) {
4888 my %co = %{$commitlist->[$i]};
4889 next if !%co;
4890 my $commit = $co{'id'};
4891 my $ref = format_ref_marker($refs, $commit);
4892 my %ad = parse_date($co{'author_epoch'});
4893 git_print_header_div('commit',
4894 "<span class=\"age\">$co{'age_string'}</span>" .
4895 esc_html($co{'title'}) . $ref,
4896 $commit);
4897 print "<div class=\"title_text\">\n" .
4898 "<div class=\"log_link\">\n" .
4899 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4900 " | " .
4901 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4902 " | " .
4903 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4904 "<br/>\n" .
4905 "</div>\n";
4906 git_print_authorship(\%co, -tag => 'span');
4907 print "<br/>\n</div>\n";
4909 print "<div class=\"log_body\">\n";
4910 git_print_log($co{'comment'}, -final_empty_line=> 1);
4911 print "</div>\n";
4913 if ($extra) {
4914 print "<div class=\"page_nav\">\n";
4915 print "$extra\n";
4916 print "</div>\n";
4920 sub git_shortlog_body {
4921 # uses global variable $project
4922 my ($commitlist, $from, $to, $refs, $extra) = @_;
4924 $from = 0 unless defined $from;
4925 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4927 print "<table class=\"shortlog\">\n";
4928 my $alternate = 1;
4929 for (my $i = $from; $i <= $to; $i++) {
4930 my %co = %{$commitlist->[$i]};
4931 my $commit = $co{'id'};
4932 my $ref = format_ref_marker($refs, $commit);
4933 if ($alternate) {
4934 print "<tr class=\"dark\">\n";
4935 } else {
4936 print "<tr class=\"light\">\n";
4938 $alternate ^= 1;
4939 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4940 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4941 format_author_html('td', \%co, 10) . "<td>";
4942 print format_subject_html($co{'title'}, $co{'title_short'},
4943 href(action=>"commit", hash=>$commit), $ref);
4944 print "</td>\n" .
4945 "<td class=\"link\">" .
4946 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4947 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4948 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4949 my $snapshot_links = format_snapshot_links($commit);
4950 if (defined $snapshot_links) {
4951 print " | " . $snapshot_links;
4953 print "</td>\n" .
4954 "</tr>\n";
4956 if (defined $extra) {
4957 print "<tr>\n" .
4958 "<td colspan=\"4\">$extra</td>\n" .
4959 "</tr>\n";
4961 print "</table>\n";
4964 sub git_history_body {
4965 # Warning: assumes constant type (blob or tree) during history
4966 my ($commitlist, $from, $to, $refs, $extra,
4967 $file_name, $file_hash, $ftype) = @_;
4969 $from = 0 unless defined $from;
4970 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4972 print "<table class=\"history\">\n";
4973 my $alternate = 1;
4974 for (my $i = $from; $i <= $to; $i++) {
4975 my %co = %{$commitlist->[$i]};
4976 if (!%co) {
4977 next;
4979 my $commit = $co{'id'};
4981 my $ref = format_ref_marker($refs, $commit);
4983 if ($alternate) {
4984 print "<tr class=\"dark\">\n";
4985 } else {
4986 print "<tr class=\"light\">\n";
4988 $alternate ^= 1;
4989 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4990 # shortlog: format_author_html('td', \%co, 10)
4991 format_author_html('td', \%co, 15, 3) . "<td>";
4992 # originally git_history used chop_str($co{'title'}, 50)
4993 print format_subject_html($co{'title'}, $co{'title_short'},
4994 href(action=>"commit", hash=>$commit), $ref);
4995 print "</td>\n" .
4996 "<td class=\"link\">" .
4997 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4998 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5000 if ($ftype eq 'blob') {
5001 my $blob_current = $file_hash;
5002 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5003 if (defined $blob_current && defined $blob_parent &&
5004 $blob_current ne $blob_parent) {
5005 print " | " .
5006 $cgi->a({-href => href(action=>"blobdiff",
5007 hash=>$blob_current, hash_parent=>$blob_parent,
5008 hash_base=>$hash_base, hash_parent_base=>$commit,
5009 file_name=>$file_name)},
5010 "diff to current");
5013 print "</td>\n" .
5014 "</tr>\n";
5016 if (defined $extra) {
5017 print "<tr>\n" .
5018 "<td colspan=\"4\">$extra</td>\n" .
5019 "</tr>\n";
5021 print "</table>\n";
5024 sub git_tags_body {
5025 # uses global variable $project
5026 my ($taglist, $from, $to, $extra) = @_;
5027 $from = 0 unless defined $from;
5028 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5030 print "<table class=\"tags\">\n";
5031 my $alternate = 1;
5032 for (my $i = $from; $i <= $to; $i++) {
5033 my $entry = $taglist->[$i];
5034 my %tag = %$entry;
5035 my $comment = $tag{'subject'};
5036 my $comment_short;
5037 if (defined $comment) {
5038 $comment_short = chop_str($comment, 30, 5);
5040 if ($alternate) {
5041 print "<tr class=\"dark\">\n";
5042 } else {
5043 print "<tr class=\"light\">\n";
5045 $alternate ^= 1;
5046 if (defined $tag{'age'}) {
5047 print "<td><i>$tag{'age'}</i></td>\n";
5048 } else {
5049 print "<td></td>\n";
5051 print "<td>" .
5052 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5053 -class => "list name"}, esc_html($tag{'name'})) .
5054 "</td>\n" .
5055 "<td>";
5056 if (defined $comment) {
5057 print format_subject_html($comment, $comment_short,
5058 href(action=>"tag", hash=>$tag{'id'}));
5060 print "</td>\n" .
5061 "<td class=\"selflink\">";
5062 if ($tag{'type'} eq "tag") {
5063 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5064 } else {
5065 print "&nbsp;";
5067 print "</td>\n" .
5068 "<td class=\"link\">" . " | " .
5069 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5070 if ($tag{'reftype'} eq "commit") {
5071 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5072 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5073 } elsif ($tag{'reftype'} eq "blob") {
5074 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5076 print "</td>\n" .
5077 "</tr>";
5079 if (defined $extra) {
5080 print "<tr>\n" .
5081 "<td colspan=\"5\">$extra</td>\n" .
5082 "</tr>\n";
5084 print "</table>\n";
5087 sub git_heads_body {
5088 # uses global variable $project
5089 my ($headlist, $head, $from, $to, $extra) = @_;
5090 $from = 0 unless defined $from;
5091 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5093 print "<table class=\"heads\">\n";
5094 my $alternate = 1;
5095 for (my $i = $from; $i <= $to; $i++) {
5096 my $entry = $headlist->[$i];
5097 my %ref = %$entry;
5098 my $curr = $ref{'id'} eq $head;
5099 if ($alternate) {
5100 print "<tr class=\"dark\">\n";
5101 } else {
5102 print "<tr class=\"light\">\n";
5104 $alternate ^= 1;
5105 print "<td><i>$ref{'age'}</i></td>\n" .
5106 ($curr ? "<td class=\"current_head\">" : "<td>") .
5107 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5108 -class => "list name"},esc_html($ref{'name'})) .
5109 "</td>\n" .
5110 "<td class=\"link\">" .
5111 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5112 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5113 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
5114 "</td>\n" .
5115 "</tr>";
5117 if (defined $extra) {
5118 print "<tr>\n" .
5119 "<td colspan=\"3\">$extra</td>\n" .
5120 "</tr>\n";
5122 print "</table>\n";
5125 sub git_search_grep_body {
5126 my ($commitlist, $from, $to, $extra) = @_;
5127 $from = 0 unless defined $from;
5128 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5130 print "<table class=\"commit_search\">\n";
5131 my $alternate = 1;
5132 for (my $i = $from; $i <= $to; $i++) {
5133 my %co = %{$commitlist->[$i]};
5134 if (!%co) {
5135 next;
5137 my $commit = $co{'id'};
5138 if ($alternate) {
5139 print "<tr class=\"dark\">\n";
5140 } else {
5141 print "<tr class=\"light\">\n";
5143 $alternate ^= 1;
5144 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5145 format_author_html('td', \%co, 15, 5) .
5146 "<td>" .
5147 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5148 -class => "list subject"},
5149 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5150 my $comment = $co{'comment'};
5151 foreach my $line (@$comment) {
5152 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5153 my ($lead, $match, $trail) = ($1, $2, $3);
5154 $match = chop_str($match, 70, 5, 'center');
5155 my $contextlen = int((80 - length($match))/2);
5156 $contextlen = 30 if ($contextlen > 30);
5157 $lead = chop_str($lead, $contextlen, 10, 'left');
5158 $trail = chop_str($trail, $contextlen, 10, 'right');
5160 $lead = esc_html($lead);
5161 $match = esc_html($match);
5162 $trail = esc_html($trail);
5164 print "$lead<span class=\"match\">$match</span>$trail<br />";
5167 print "</td>\n" .
5168 "<td class=\"link\">" .
5169 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5170 " | " .
5171 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5172 " | " .
5173 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5174 print "</td>\n" .
5175 "</tr>\n";
5177 if (defined $extra) {
5178 print "<tr>\n" .
5179 "<td colspan=\"3\">$extra</td>\n" .
5180 "</tr>\n";
5182 print "</table>\n";
5185 ## ======================================================================
5186 ## ======================================================================
5187 ## actions
5189 sub git_project_list {
5190 my $order = $input_params{'order'};
5191 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5192 die_error(400, "Unknown order parameter");
5195 my @list = git_get_projects_list();
5196 if (!@list) {
5197 die_error(404, "No projects found");
5200 git_header_html();
5201 if (defined $home_text && -f $home_text) {
5202 print "<div class=\"index_include\">\n";
5203 insert_file($home_text);
5204 print "</div>\n";
5206 print $cgi->startform(-method => "get") .
5207 "<p class=\"projsearch\">Search:\n" .
5208 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5209 "</p>" .
5210 $cgi->end_form() . "\n";
5211 git_project_list_body(\@list, $order);
5212 git_footer_html();
5215 sub git_forks {
5216 my $order = $input_params{'order'};
5217 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5218 die_error(400, "Unknown order parameter");
5221 my @list = git_get_projects_list($project);
5222 if (!@list) {
5223 die_error(404, "No forks found");
5226 git_header_html();
5227 git_print_page_nav('','');
5228 git_print_header_div('summary', "$project forks");
5229 git_project_list_body(\@list, $order);
5230 git_footer_html();
5233 sub git_project_index {
5234 my @projects = git_get_projects_list($project);
5236 print $cgi->header(
5237 -type => 'text/plain',
5238 -charset => 'utf-8',
5239 -content_disposition => 'inline; filename="index.aux"');
5241 foreach my $pr (@projects) {
5242 if (!exists $pr->{'owner'}) {
5243 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5246 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5247 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5248 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5249 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5250 $path =~ s/ /\+/g;
5251 $owner =~ s/ /\+/g;
5253 print "$path $owner\n";
5257 sub git_summary {
5258 my $descr = git_get_project_description($project) || "none";
5259 my %co = parse_commit("HEAD");
5260 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5261 my $head = $co{'id'};
5263 my $owner = git_get_project_owner($project);
5265 my $refs = git_get_references();
5266 # These get_*_list functions return one more to allow us to see if
5267 # there are more ...
5268 my @taglist = git_get_tags_list(16);
5269 my @headlist = git_get_heads_list(16);
5270 my @forklist;
5271 my $check_forks = gitweb_check_feature('forks');
5273 if ($check_forks) {
5274 @forklist = git_get_projects_list($project);
5277 git_header_html();
5278 git_print_page_nav('summary','', $head);
5280 print "<div class=\"title\">&nbsp;</div>\n";
5281 print "<table class=\"projects_list\">\n" .
5282 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5283 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5284 if (defined $cd{'rfc2822'}) {
5285 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5288 # use per project git URL list in $projectroot/$project/cloneurl
5289 # or make project git URL from git base URL and project name
5290 my $url_tag = "URL";
5291 my @url_list = git_get_project_url_list($project);
5292 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5293 foreach my $git_url (@url_list) {
5294 next unless $git_url;
5295 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5296 $url_tag = "";
5299 # Tag cloud
5300 my $show_ctags = gitweb_check_feature('ctags');
5301 if ($show_ctags) {
5302 my $ctags = git_get_project_ctags($project);
5303 my $cloud = git_populate_project_tagcloud($ctags);
5304 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5305 print "</td>\n<td>" unless %$ctags;
5306 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5307 print "</td>\n<td>" if %$ctags;
5308 print git_show_project_tagcloud($cloud, 48);
5309 print "</td></tr>";
5312 print "</table>\n";
5314 # If XSS prevention is on, we don't include README.html.
5315 # TODO: Allow a readme in some safe format.
5316 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5317 print "<div class=\"title\">readme</div>\n" .
5318 "<div class=\"readme\">\n";
5319 insert_file("$projectroot/$project/README.html");
5320 print "\n</div>\n"; # class="readme"
5323 # we need to request one more than 16 (0..15) to check if
5324 # those 16 are all
5325 my @commitlist = $head ? parse_commits($head, 17) : ();
5326 if (@commitlist) {
5327 git_print_header_div('shortlog');
5328 git_shortlog_body(\@commitlist, 0, 15, $refs,
5329 $#commitlist <= 15 ? undef :
5330 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5333 if (@taglist) {
5334 git_print_header_div('tags');
5335 git_tags_body(\@taglist, 0, 15,
5336 $#taglist <= 15 ? undef :
5337 $cgi->a({-href => href(action=>"tags")}, "..."));
5340 if (@headlist) {
5341 git_print_header_div('heads');
5342 git_heads_body(\@headlist, $head, 0, 15,
5343 $#headlist <= 15 ? undef :
5344 $cgi->a({-href => href(action=>"heads")}, "..."));
5347 if (@forklist) {
5348 git_print_header_div('forks');
5349 git_project_list_body(\@forklist, 'age', 0, 15,
5350 $#forklist <= 15 ? undef :
5351 $cgi->a({-href => href(action=>"forks")}, "..."),
5352 'no_header');
5355 git_footer_html();
5358 sub git_tag {
5359 my %tag = parse_tag($hash);
5361 if (! %tag) {
5362 die_error(404, "Unknown tag object");
5365 my $head = git_get_head_hash($project);
5366 git_header_html();
5367 git_print_page_nav('','', $head,undef,$head);
5368 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5369 print "<div class=\"title_text\">\n" .
5370 "<table class=\"object_header\">\n" .
5371 "<tr>\n" .
5372 "<td>object</td>\n" .
5373 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5374 $tag{'object'}) . "</td>\n" .
5375 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5376 $tag{'type'}) . "</td>\n" .
5377 "</tr>\n";
5378 if (defined($tag{'author'})) {
5379 git_print_authorship_rows(\%tag, 'author');
5381 print "</table>\n\n" .
5382 "</div>\n";
5383 print "<div class=\"page_body\">";
5384 my $comment = $tag{'comment'};
5385 foreach my $line (@$comment) {
5386 chomp $line;
5387 print esc_html($line, -nbsp=>1) . "<br/>\n";
5389 print "</div>\n";
5390 git_footer_html();
5393 sub git_blame_common {
5394 my $format = shift || 'porcelain';
5395 if ($format eq 'porcelain' && $cgi->param('js') &&
5396 !$caching_enabled) {
5397 $format = 'incremental';
5398 $action = 'blame_incremental'; # for page title etc
5401 # permissions
5402 gitweb_check_feature('blame')
5403 or die_error(403, "Blame view not allowed");
5405 # error checking
5406 die_error(400, "No file name given") unless $file_name;
5407 $hash_base ||= git_get_head_hash($project);
5408 die_error(404, "Couldn't find base commit") unless $hash_base;
5409 my %co = parse_commit($hash_base)
5410 or die_error(404, "Commit not found");
5411 my $ftype = "blob";
5412 if (!defined $hash) {
5413 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5414 or die_error(404, "Error looking up file");
5415 } else {
5416 $ftype = git_get_type($hash);
5417 if ($ftype !~ "blob") {
5418 die_error(400, "Object is not a blob");
5422 my $fd;
5423 if ($format eq 'incremental') {
5424 # get file contents (as base)
5425 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5426 or die_error(500, "Open git-cat-file failed");
5427 } elsif ($format eq 'data') {
5428 # run git-blame --incremental
5429 open $fd, "-|", git_cmd(), "blame", "--incremental",
5430 $hash_base, "--", $file_name
5431 or die_error(500, "Open git-blame --incremental failed");
5432 } else {
5433 # run git-blame --porcelain
5434 open $fd, "-|", git_cmd(), "blame", '-p',
5435 $hash_base, '--', $file_name
5436 or die_error(500, "Open git-blame --porcelain failed");
5439 # incremental blame data returns early
5440 if ($format eq 'data') {
5441 print $cgi->header(
5442 -type=>"text/plain", -charset => "utf-8",
5443 -status=> "200 OK");
5444 local $| = 1; # output autoflush
5445 print while <$fd>;
5446 close $fd
5447 or print "ERROR $!\n";
5449 print 'END';
5450 if (!$caching_enabled &&
5451 defined $t0 && gitweb_check_feature('timed')) {
5452 print ' '.
5453 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5454 ' '.$number_of_git_cmds;
5456 print "\n";
5458 return;
5461 # page header
5462 git_header_html();
5463 my $formats_nav =
5464 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5465 "blob") .
5466 " | ";
5467 if ($format eq 'incremental') {
5468 $formats_nav .=
5469 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5470 "blame") . " (non-incremental)";
5471 } elsif (!$caching_enabled) {
5472 $formats_nav .=
5473 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5474 "blame") . " (incremental)";
5476 $formats_nav .=
5477 " | " .
5478 $cgi->a({-href => href(action=>"history", -replay=>1)},
5479 "history") .
5480 " | " .
5481 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5482 "HEAD");
5483 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5484 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5485 git_print_page_path($file_name, $ftype, $hash_base);
5487 # page body
5488 if ($format eq 'incremental') {
5489 print "<noscript>\n<div class=\"error\"><center><b>\n".
5490 "This page requires JavaScript to run.\n Use ".
5491 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5492 'this page').
5493 " instead.\n".
5494 "</b></center></div>\n</noscript>\n";
5496 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5499 print qq!<div class="page_body">\n!;
5500 print qq!<div id="progress_info">... / ...</div>\n!
5501 if ($format eq 'incremental');
5502 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5503 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5504 qq!<thead>\n!.
5505 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5506 qq!</thead>\n!.
5507 qq!<tbody>\n!;
5509 my @rev_color = qw(light dark);
5510 my $num_colors = scalar(@rev_color);
5511 my $current_color = 0;
5513 if ($format eq 'incremental') {
5514 my $color_class = $rev_color[$current_color];
5516 #contents of a file
5517 my $linenr = 0;
5518 LINE:
5519 while (my $line = <$fd>) {
5520 chomp $line;
5521 $linenr++;
5523 print qq!<tr id="l$linenr" class="$color_class">!.
5524 qq!<td class="sha1"><a href=""> </a></td>!.
5525 qq!<td class="linenr">!.
5526 qq!<a class="linenr" href="">$linenr</a></td>!;
5527 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5528 print qq!</tr>\n!;
5531 } else { # porcelain, i.e. ordinary blame
5532 my %metainfo = (); # saves information about commits
5534 # blame data
5535 LINE:
5536 while (my $line = <$fd>) {
5537 chomp $line;
5538 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5539 # no <lines in group> for subsequent lines in group of lines
5540 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5541 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5542 if (!exists $metainfo{$full_rev}) {
5543 $metainfo{$full_rev} = { 'nprevious' => 0 };
5545 my $meta = $metainfo{$full_rev};
5546 my $data;
5547 while ($data = <$fd>) {
5548 chomp $data;
5549 last if ($data =~ s/^\t//); # contents of line
5550 if ($data =~ /^(\S+)(?: (.*))?$/) {
5551 $meta->{$1} = $2 unless exists $meta->{$1};
5553 if ($data =~ /^previous /) {
5554 $meta->{'nprevious'}++;
5557 my $short_rev = substr($full_rev, 0, 8);
5558 my $author = $meta->{'author'};
5559 my %date =
5560 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5561 my $date = $date{'iso-tz'};
5562 if ($group_size) {
5563 $current_color = ($current_color + 1) % $num_colors;
5565 my $tr_class = $rev_color[$current_color];
5566 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5567 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5568 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5569 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5570 if ($group_size) {
5571 print "<td class=\"sha1\"";
5572 print " title=\"". esc_html($author) . ", $date\"";
5573 print " rowspan=\"$group_size\"" if ($group_size > 1);
5574 print ">";
5575 print $cgi->a({-href => href(action=>"commit",
5576 hash=>$full_rev,
5577 file_name=>$file_name)},
5578 esc_html($short_rev));
5579 if ($group_size >= 2) {
5580 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5581 if (@author_initials) {
5582 print "<br />" .
5583 esc_html(join('', @author_initials));
5584 # or join('.', ...)
5587 print "</td>\n";
5589 # 'previous' <sha1 of parent commit> <filename at commit>
5590 if (exists $meta->{'previous'} &&
5591 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5592 $meta->{'parent'} = $1;
5593 $meta->{'file_parent'} = unquote($2);
5595 my $linenr_commit =
5596 exists($meta->{'parent'}) ?
5597 $meta->{'parent'} : $full_rev;
5598 my $linenr_filename =
5599 exists($meta->{'file_parent'}) ?
5600 $meta->{'file_parent'} : unquote($meta->{'filename'});
5601 my $blamed = href(action => 'blame',
5602 file_name => $linenr_filename,
5603 hash_base => $linenr_commit);
5604 print "<td class=\"linenr\">";
5605 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5606 -class => "linenr" },
5607 esc_html($lineno));
5608 print "</td>";
5609 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5610 print "</tr>\n";
5611 } # end while
5615 # footer
5616 print "</tbody>\n".
5617 "</table>\n"; # class="blame"
5618 print "</div>\n"; # class="blame_body"
5619 close $fd
5620 or print "Reading blob failed\n";
5622 git_footer_html();
5625 sub git_blame {
5626 git_blame_common();
5629 sub git_blame_incremental {
5630 git_blame_common(!$caching_enabled ? 'incremental' : undef);
5633 sub git_blame_data {
5634 git_blame_common('data');
5637 sub git_tags {
5638 my $head = git_get_head_hash($project);
5639 git_header_html();
5640 git_print_page_nav('','', $head,undef,$head);
5641 git_print_header_div('summary', $project);
5643 my @tagslist = git_get_tags_list();
5644 if (@tagslist) {
5645 git_tags_body(\@tagslist);
5647 git_footer_html();
5650 sub git_heads {
5651 my $head = git_get_head_hash($project);
5652 git_header_html();
5653 git_print_page_nav('','', $head,undef,$head);
5654 git_print_header_div('summary', $project);
5656 my @headslist = git_get_heads_list();
5657 if (@headslist) {
5658 git_heads_body(\@headslist, $head);
5660 git_footer_html();
5663 sub git_blob_plain {
5664 my $type = shift;
5665 my $expires;
5667 if (!defined $hash) {
5668 if (defined $file_name) {
5669 my $base = $hash_base || git_get_head_hash($project);
5670 $hash = git_get_hash_by_path($base, $file_name, "blob")
5671 or die_error(404, "Cannot find file");
5672 } else {
5673 die_error(400, "No file name defined");
5675 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5676 # blobs defined by non-textual hash id's can be cached
5677 $expires = "+1d";
5680 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5681 or die_error(500, "Open git-cat-file blob '$hash' failed");
5683 # content-type (can include charset)
5684 $type = blob_contenttype($fd, $file_name, $type);
5686 # "save as" filename, even when no $file_name is given
5687 my $save_as = "$hash";
5688 if (defined $file_name) {
5689 $save_as = $file_name;
5690 } elsif ($type =~ m/^text\//) {
5691 $save_as .= '.txt';
5694 # With XSS prevention on, blobs of all types except a few known safe
5695 # ones are served with "Content-Disposition: attachment" to make sure
5696 # they don't run in our security domain. For certain image types,
5697 # blob view writes an <img> tag referring to blob_plain view, and we
5698 # want to be sure not to break that by serving the image as an
5699 # attachment (though Firefox 3 doesn't seem to care).
5700 my $sandbox = $prevent_xss &&
5701 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5703 print $cgi->header(
5704 -type => $type,
5705 -expires => $expires,
5706 -content_disposition =>
5707 ($sandbox ? 'attachment' : 'inline')
5708 . '; filename="' . $save_as . '"');
5709 local $/ = undef;
5710 binmode STDOUT, ':raw';
5711 print <$fd>;
5712 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5713 close $fd;
5716 sub git_blob {
5717 my $expires;
5719 if (!defined $hash) {
5720 if (defined $file_name) {
5721 my $base = $hash_base || git_get_head_hash($project);
5722 $hash = git_get_hash_by_path($base, $file_name, "blob")
5723 or die_error(404, "Cannot find file");
5724 } else {
5725 die_error(400, "No file name defined");
5727 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5728 # blobs defined by non-textual hash id's can be cached
5729 $expires = "+1d";
5732 my $have_blame = gitweb_check_feature('blame');
5733 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5734 or die_error(500, "Couldn't cat $file_name, $hash");
5735 my $mimetype = blob_mimetype($fd, $file_name);
5736 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5737 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5738 close $fd;
5739 return git_blob_plain($mimetype);
5741 # we can have blame only for text/* mimetype
5742 $have_blame &&= ($mimetype =~ m!^text/!);
5744 my $highlight = gitweb_check_feature('highlight');
5745 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5746 $fd = run_highlighter($fd, $highlight, $syntax)
5747 if $syntax;
5749 git_header_html(undef, $expires);
5750 my $formats_nav = '';
5751 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5752 if (defined $file_name) {
5753 if ($have_blame) {
5754 $formats_nav .=
5755 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5756 "blame") .
5757 " | ";
5759 $formats_nav .=
5760 $cgi->a({-href => href(action=>"history", -replay=>1)},
5761 "history") .
5762 " | " .
5763 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5764 "raw") .
5765 " | " .
5766 $cgi->a({-href => href(action=>"blob",
5767 hash_base=>"HEAD", file_name=>$file_name)},
5768 "HEAD");
5769 } else {
5770 $formats_nav .=
5771 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5772 "raw");
5774 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5775 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5776 } else {
5777 print "<div class=\"page_nav\">\n" .
5778 "<br/><br/></div>\n" .
5779 "<div class=\"title\">$hash</div>\n";
5781 git_print_page_path($file_name, "blob", $hash_base);
5782 print "<div class=\"page_body\">\n";
5783 if ($mimetype =~ m!^image/!) {
5784 print qq!<img type="$mimetype"!;
5785 if ($file_name) {
5786 print qq! alt="$file_name" title="$file_name"!;
5788 print qq! src="! .
5789 href(action=>"blob_plain", hash=>$hash,
5790 hash_base=>$hash_base, file_name=>$file_name) .
5791 qq!" />\n!;
5792 } else {
5793 my $nr;
5794 while (my $line = <$fd>) {
5795 chomp $line;
5796 $nr++;
5797 $line = untabify($line);
5798 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5799 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5802 close $fd
5803 or print "Reading blob failed.\n";
5804 print "</div>";
5805 git_footer_html();
5808 sub git_tree {
5809 if (!defined $hash_base) {
5810 $hash_base = "HEAD";
5812 if (!defined $hash) {
5813 if (defined $file_name) {
5814 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5815 } else {
5816 $hash = $hash_base;
5819 die_error(404, "No such tree") unless defined($hash);
5821 my $show_sizes = gitweb_check_feature('show-sizes');
5822 my $have_blame = gitweb_check_feature('blame');
5824 my @entries = ();
5826 local $/ = "\0";
5827 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5828 ($show_sizes ? '-l' : ()), @extra_options, $hash
5829 or die_error(500, "Open git-ls-tree failed");
5830 @entries = map { chomp; $_ } <$fd>;
5831 close $fd
5832 or die_error(404, "Reading tree failed");
5835 my $refs = git_get_references();
5836 my $ref = format_ref_marker($refs, $hash_base);
5837 git_header_html();
5838 my $basedir = '';
5839 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5840 my @views_nav = ();
5841 if (defined $file_name) {
5842 push @views_nav,
5843 $cgi->a({-href => href(action=>"history", -replay=>1)},
5844 "history"),
5845 $cgi->a({-href => href(action=>"tree",
5846 hash_base=>"HEAD", file_name=>$file_name)},
5847 "HEAD"),
5849 my $snapshot_links = format_snapshot_links($hash);
5850 if (defined $snapshot_links) {
5851 # FIXME: Should be available when we have no hash base as well.
5852 push @views_nav, $snapshot_links;
5854 git_print_page_nav('tree','', $hash_base, undef, undef,
5855 join(' | ', @views_nav));
5856 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5857 } else {
5858 undef $hash_base;
5859 print "<div class=\"page_nav\">\n";
5860 print "<br/><br/></div>\n";
5861 print "<div class=\"title\">$hash</div>\n";
5863 if (defined $file_name) {
5864 $basedir = $file_name;
5865 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5866 $basedir .= '/';
5868 git_print_page_path($file_name, 'tree', $hash_base);
5870 print "<div class=\"page_body\">\n";
5871 print "<table class=\"tree\">\n";
5872 my $alternate = 1;
5873 # '..' (top directory) link if possible
5874 if (defined $hash_base &&
5875 defined $file_name && $file_name =~ m![^/]+$!) {
5876 if ($alternate) {
5877 print "<tr class=\"dark\">\n";
5878 } else {
5879 print "<tr class=\"light\">\n";
5881 $alternate ^= 1;
5883 my $up = $file_name;
5884 $up =~ s!/?[^/]+$!!;
5885 undef $up unless $up;
5886 # based on git_print_tree_entry
5887 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5888 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5889 print '<td class="list">';
5890 print $cgi->a({-href => href(action=>"tree",
5891 hash_base=>$hash_base,
5892 file_name=>$up)},
5893 "..");
5894 print "</td>\n";
5895 print "<td class=\"link\"></td>\n";
5897 print "</tr>\n";
5899 foreach my $line (@entries) {
5900 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5902 if ($alternate) {
5903 print "<tr class=\"dark\">\n";
5904 } else {
5905 print "<tr class=\"light\">\n";
5907 $alternate ^= 1;
5909 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5911 print "</tr>\n";
5913 print "</table>\n" .
5914 "</div>";
5915 git_footer_html();
5918 sub snapshot_name {
5919 my ($project, $hash) = @_;
5921 # path/to/project.git -> project
5922 # path/to/project/.git -> project
5923 my $name = to_utf8($project);
5924 $name =~ s,([^/])/*\.git$,$1,;
5925 $name = basename($name);
5926 # sanitize name
5927 $name =~ s/[[:cntrl:]]/?/g;
5929 my $ver = $hash;
5930 if ($hash =~ /^[0-9a-fA-F]+$/) {
5931 # shorten SHA-1 hash
5932 my $full_hash = git_get_full_hash($project, $hash);
5933 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5934 $ver = git_get_short_hash($project, $hash);
5936 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5937 # tags don't need shortened SHA-1 hash
5938 $ver = $1;
5939 } else {
5940 # branches and other need shortened SHA-1 hash
5941 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5942 $ver = $1;
5944 $ver .= '-' . git_get_short_hash($project, $hash);
5946 # in case of hierarchical branch names
5947 $ver =~ s!/!.!g;
5949 # name = project-version_string
5950 $name = "$name-$ver";
5952 return wantarray ? ($name, $name) : $name;
5955 sub git_snapshot {
5956 my $format = $input_params{'snapshot_format'};
5957 if (!@snapshot_fmts) {
5958 die_error(403, "Snapshots not allowed");
5960 # default to first supported snapshot format
5961 $format ||= $snapshot_fmts[0];
5962 if ($format !~ m/^[a-z0-9]+$/) {
5963 die_error(400, "Invalid snapshot format parameter");
5964 } elsif (!exists($known_snapshot_formats{$format})) {
5965 die_error(400, "Unknown snapshot format");
5966 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5967 die_error(403, "Snapshot format not allowed");
5968 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5969 die_error(403, "Unsupported snapshot format");
5972 my $type = git_get_type("$hash^{}");
5973 if (!$type) {
5974 die_error(404, 'Object does not exist');
5975 } elsif ($type eq 'blob') {
5976 die_error(400, 'Object is not a tree-ish');
5979 my ($name, $prefix) = snapshot_name($project, $hash);
5980 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
5981 my $cmd = quote_command(
5982 git_cmd(), 'archive',
5983 "--format=$known_snapshot_formats{$format}{'format'}",
5984 "--prefix=$prefix/", $hash);
5985 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5986 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5989 $filename =~ s/(["\\])/\\$1/g;
5990 print $cgi->header(
5991 -type => $known_snapshot_formats{$format}{'type'},
5992 -content_disposition => 'inline; filename="' . $filename . '"',
5993 -status => '200 OK');
5995 open my $fd, "-|", $cmd
5996 or die_error(500, "Execute git-archive failed");
5997 binmode STDOUT, ':raw';
5998 print <$fd>;
5999 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6000 close $fd;
6003 sub git_log_generic {
6004 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6006 my $head = git_get_head_hash($project);
6007 if (!defined $base) {
6008 $base = $head;
6010 if (!defined $page) {
6011 $page = 0;
6013 my $refs = git_get_references();
6015 my $commit_hash = $base;
6016 if (defined $parent) {
6017 $commit_hash = "$parent..$base";
6019 my @commitlist =
6020 parse_commits($commit_hash, 101, (100 * $page),
6021 defined $file_name ? ($file_name, "--full-history") : ());
6023 my $ftype;
6024 if (!defined $file_hash && defined $file_name) {
6025 # some commits could have deleted file in question,
6026 # and not have it in tree, but one of them has to have it
6027 for (my $i = 0; $i < @commitlist; $i++) {
6028 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6029 last if defined $file_hash;
6032 if (defined $file_hash) {
6033 $ftype = git_get_type($file_hash);
6035 if (defined $file_name && !defined $ftype) {
6036 die_error(500, "Unknown type of object");
6038 my %co;
6039 if (defined $file_name) {
6040 %co = parse_commit($base)
6041 or die_error(404, "Unknown commit object");
6045 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6046 my $next_link = '';
6047 if ($#commitlist >= 100) {
6048 $next_link =
6049 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6050 -accesskey => "n", -title => "Alt-n"}, "next");
6052 my $patch_max = gitweb_get_feature('patches');
6053 if ($patch_max && !defined $file_name) {
6054 if ($patch_max < 0 || @commitlist <= $patch_max) {
6055 $paging_nav .= " &sdot; " .
6056 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6057 "patches");
6061 git_header_html();
6062 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6063 if (defined $file_name) {
6064 git_print_header_div('commit', esc_html($co{'title'}), $base);
6065 } else {
6066 git_print_header_div('summary', $project)
6068 git_print_page_path($file_name, $ftype, $hash_base)
6069 if (defined $file_name);
6071 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6072 $file_name, $file_hash, $ftype);
6074 git_footer_html();
6077 sub git_log {
6078 git_log_generic('log', \&git_log_body,
6079 $hash, $hash_parent);
6082 sub git_commit {
6083 $hash ||= $hash_base || "HEAD";
6084 my %co = parse_commit($hash)
6085 or die_error(404, "Unknown commit object");
6087 my $parent = $co{'parent'};
6088 my $parents = $co{'parents'}; # listref
6090 # we need to prepare $formats_nav before any parameter munging
6091 my $formats_nav;
6092 if (!defined $parent) {
6093 # --root commitdiff
6094 $formats_nav .= '(initial)';
6095 } elsif (@$parents == 1) {
6096 # single parent commit
6097 $formats_nav .=
6098 '(parent: ' .
6099 $cgi->a({-href => href(action=>"commit",
6100 hash=>$parent)},
6101 esc_html(substr($parent, 0, 7))) .
6102 ')';
6103 } else {
6104 # merge commit
6105 $formats_nav .=
6106 '(merge: ' .
6107 join(' ', map {
6108 $cgi->a({-href => href(action=>"commit",
6109 hash=>$_)},
6110 esc_html(substr($_, 0, 7)));
6111 } @$parents ) .
6112 ')';
6114 if (gitweb_check_feature('patches') && @$parents <= 1) {
6115 $formats_nav .= " | " .
6116 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6117 "patch");
6120 if (!defined $parent) {
6121 $parent = "--root";
6123 my @difftree;
6124 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6125 @diff_opts,
6126 (@$parents <= 1 ? $parent : '-c'),
6127 $hash, "--"
6128 or die_error(500, "Open git-diff-tree failed");
6129 @difftree = map { chomp; $_ } <$fd>;
6130 close $fd or die_error(404, "Reading git-diff-tree failed");
6132 # non-textual hash id's can be cached
6133 my $expires;
6134 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6135 $expires = "+1d";
6137 my $refs = git_get_references();
6138 my $ref = format_ref_marker($refs, $co{'id'});
6140 git_header_html(undef, $expires);
6141 git_print_page_nav('commit', '',
6142 $hash, $co{'tree'}, $hash,
6143 $formats_nav);
6145 if (defined $co{'parent'}) {
6146 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6147 } else {
6148 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6150 print "<div class=\"title_text\">\n" .
6151 "<table class=\"object_header\">\n";
6152 git_print_authorship_rows(\%co);
6153 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6154 print "<tr>" .
6155 "<td>tree</td>" .
6156 "<td class=\"sha1\">" .
6157 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6158 class => "list"}, $co{'tree'}) .
6159 "</td>" .
6160 "<td class=\"link\">" .
6161 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6162 "tree");
6163 my $snapshot_links = format_snapshot_links($hash);
6164 if (defined $snapshot_links) {
6165 print " | " . $snapshot_links;
6167 print "</td>" .
6168 "</tr>\n";
6170 foreach my $par (@$parents) {
6171 print "<tr>" .
6172 "<td>parent</td>" .
6173 "<td class=\"sha1\">" .
6174 $cgi->a({-href => href(action=>"commit", hash=>$par),
6175 class => "list"}, $par) .
6176 "</td>" .
6177 "<td class=\"link\">" .
6178 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6179 " | " .
6180 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6181 "</td>" .
6182 "</tr>\n";
6184 print "</table>".
6185 "</div>\n";
6187 print "<div class=\"page_body\">\n";
6188 git_print_log($co{'comment'});
6189 print "</div>\n";
6191 git_difftree_body(\@difftree, $hash, @$parents);
6193 git_footer_html();
6196 sub git_object {
6197 # object is defined by:
6198 # - hash or hash_base alone
6199 # - hash_base and file_name
6200 my $type;
6202 # - hash or hash_base alone
6203 if ($hash || ($hash_base && !defined $file_name)) {
6204 my $object_id = $hash || $hash_base;
6206 open my $fd, "-|", quote_command(
6207 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6208 or die_error(404, "Object does not exist");
6209 $type = <$fd>;
6210 chomp $type;
6211 close $fd
6212 or die_error(404, "Object does not exist");
6214 # - hash_base and file_name
6215 } elsif ($hash_base && defined $file_name) {
6216 $file_name =~ s,/+$,,;
6218 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6219 or die_error(404, "Base object does not exist");
6221 # here errors should not hapen
6222 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6223 or die_error(500, "Open git-ls-tree failed");
6224 my $line = <$fd>;
6225 close $fd;
6227 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6228 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6229 die_error(404, "File or directory for given base does not exist");
6231 $type = $2;
6232 $hash = $3;
6233 } else {
6234 die_error(400, "Not enough information to find object");
6237 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6238 hash=>$hash, hash_base=>$hash_base,
6239 file_name=>$file_name),
6240 -status => '302 Found');
6243 sub git_blobdiff {
6244 my $format = shift || 'html';
6246 my $fd;
6247 my @difftree;
6248 my %diffinfo;
6249 my $expires;
6251 # preparing $fd and %diffinfo for git_patchset_body
6252 # new style URI
6253 if (defined $hash_base && defined $hash_parent_base) {
6254 if (defined $file_name) {
6255 # read raw output
6256 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6257 $hash_parent_base, $hash_base,
6258 "--", (defined $file_parent ? $file_parent : ()), $file_name
6259 or die_error(500, "Open git-diff-tree failed");
6260 @difftree = map { chomp; $_ } <$fd>;
6261 close $fd
6262 or die_error(404, "Reading git-diff-tree failed");
6263 @difftree
6264 or die_error(404, "Blob diff not found");
6266 } elsif (defined $hash &&
6267 $hash =~ /[0-9a-fA-F]{40}/) {
6268 # try to find filename from $hash
6270 # read filtered raw output
6271 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6272 $hash_parent_base, $hash_base, "--"
6273 or die_error(500, "Open git-diff-tree failed");
6274 @difftree =
6275 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6276 # $hash == to_id
6277 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6278 map { chomp; $_ } <$fd>;
6279 close $fd
6280 or die_error(404, "Reading git-diff-tree failed");
6281 @difftree
6282 or die_error(404, "Blob diff not found");
6284 } else {
6285 die_error(400, "Missing one of the blob diff parameters");
6288 if (@difftree > 1) {
6289 die_error(400, "Ambiguous blob diff specification");
6292 %diffinfo = parse_difftree_raw_line($difftree[0]);
6293 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6294 $file_name ||= $diffinfo{'to_file'};
6296 $hash_parent ||= $diffinfo{'from_id'};
6297 $hash ||= $diffinfo{'to_id'};
6299 # non-textual hash id's can be cached
6300 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6301 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6302 $expires = '+1d';
6305 # open patch output
6306 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6307 '-p', ($format eq 'html' ? "--full-index" : ()),
6308 $hash_parent_base, $hash_base,
6309 "--", (defined $file_parent ? $file_parent : ()), $file_name
6310 or die_error(500, "Open git-diff-tree failed");
6313 # old/legacy style URI -- not generated anymore since 1.4.3.
6314 if (!%diffinfo) {
6315 die_error('404 Not Found', "Missing one of the blob diff parameters")
6318 # header
6319 if ($format eq 'html') {
6320 my $formats_nav =
6321 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6322 "raw");
6323 git_header_html(undef, $expires);
6324 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6325 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6326 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6327 } else {
6328 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6329 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6331 if (defined $file_name) {
6332 git_print_page_path($file_name, "blob", $hash_base);
6333 } else {
6334 print "<div class=\"page_path\"></div>\n";
6337 } elsif ($format eq 'plain') {
6338 print $cgi->header(
6339 -type => 'text/plain',
6340 -charset => 'utf-8',
6341 -expires => $expires,
6342 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6344 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6346 } else {
6347 die_error(400, "Unknown blobdiff format");
6350 # patch
6351 if ($format eq 'html') {
6352 print "<div class=\"page_body\">\n";
6354 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6355 close $fd;
6357 print "</div>\n"; # class="page_body"
6358 git_footer_html();
6360 } else {
6361 while (my $line = <$fd>) {
6362 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6363 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6365 print $line;
6367 last if $line =~ m!^\+\+\+!;
6369 local $/ = undef;
6370 print <$fd>;
6371 close $fd;
6375 sub git_blobdiff_plain {
6376 git_blobdiff('plain');
6379 sub git_commitdiff {
6380 my %params = @_;
6381 my $format = $params{-format} || 'html';
6383 my ($patch_max) = gitweb_get_feature('patches');
6384 if ($format eq 'patch') {
6385 die_error(403, "Patch view not allowed") unless $patch_max;
6388 $hash ||= $hash_base || "HEAD";
6389 my %co = parse_commit($hash)
6390 or die_error(404, "Unknown commit object");
6392 # choose format for commitdiff for merge
6393 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6394 $hash_parent = '--cc';
6396 # we need to prepare $formats_nav before almost any parameter munging
6397 my $formats_nav;
6398 if ($format eq 'html') {
6399 $formats_nav =
6400 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6401 "raw");
6402 if ($patch_max && @{$co{'parents'}} <= 1) {
6403 $formats_nav .= " | " .
6404 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6405 "patch");
6408 if (defined $hash_parent &&
6409 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6410 # commitdiff with two commits given
6411 my $hash_parent_short = $hash_parent;
6412 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6413 $hash_parent_short = substr($hash_parent, 0, 7);
6415 $formats_nav .=
6416 ' (from';
6417 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6418 if ($co{'parents'}[$i] eq $hash_parent) {
6419 $formats_nav .= ' parent ' . ($i+1);
6420 last;
6423 $formats_nav .= ': ' .
6424 $cgi->a({-href => href(action=>"commitdiff",
6425 hash=>$hash_parent)},
6426 esc_html($hash_parent_short)) .
6427 ')';
6428 } elsif (!$co{'parent'}) {
6429 # --root commitdiff
6430 $formats_nav .= ' (initial)';
6431 } elsif (scalar @{$co{'parents'}} == 1) {
6432 # single parent commit
6433 $formats_nav .=
6434 ' (parent: ' .
6435 $cgi->a({-href => href(action=>"commitdiff",
6436 hash=>$co{'parent'})},
6437 esc_html(substr($co{'parent'}, 0, 7))) .
6438 ')';
6439 } else {
6440 # merge commit
6441 if ($hash_parent eq '--cc') {
6442 $formats_nav .= ' | ' .
6443 $cgi->a({-href => href(action=>"commitdiff",
6444 hash=>$hash, hash_parent=>'-c')},
6445 'combined');
6446 } else { # $hash_parent eq '-c'
6447 $formats_nav .= ' | ' .
6448 $cgi->a({-href => href(action=>"commitdiff",
6449 hash=>$hash, hash_parent=>'--cc')},
6450 'compact');
6452 $formats_nav .=
6453 ' (merge: ' .
6454 join(' ', map {
6455 $cgi->a({-href => href(action=>"commitdiff",
6456 hash=>$_)},
6457 esc_html(substr($_, 0, 7)));
6458 } @{$co{'parents'}} ) .
6459 ')';
6463 my $hash_parent_param = $hash_parent;
6464 if (!defined $hash_parent_param) {
6465 # --cc for multiple parents, --root for parentless
6466 $hash_parent_param =
6467 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6470 # read commitdiff
6471 my $fd;
6472 my @difftree;
6473 if ($format eq 'html') {
6474 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6475 "--no-commit-id", "--patch-with-raw", "--full-index",
6476 $hash_parent_param, $hash, "--"
6477 or die_error(500, "Open git-diff-tree failed");
6479 while (my $line = <$fd>) {
6480 chomp $line;
6481 # empty line ends raw part of diff-tree output
6482 last unless $line;
6483 push @difftree, scalar parse_difftree_raw_line($line);
6486 } elsif ($format eq 'plain') {
6487 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6488 '-p', $hash_parent_param, $hash, "--"
6489 or die_error(500, "Open git-diff-tree failed");
6490 } elsif ($format eq 'patch') {
6491 # For commit ranges, we limit the output to the number of
6492 # patches specified in the 'patches' feature.
6493 # For single commits, we limit the output to a single patch,
6494 # diverging from the git-format-patch default.
6495 my @commit_spec = ();
6496 if ($hash_parent) {
6497 if ($patch_max > 0) {
6498 push @commit_spec, "-$patch_max";
6500 push @commit_spec, '-n', "$hash_parent..$hash";
6501 } else {
6502 if ($params{-single}) {
6503 push @commit_spec, '-1';
6504 } else {
6505 if ($patch_max > 0) {
6506 push @commit_spec, "-$patch_max";
6508 push @commit_spec, "-n";
6510 push @commit_spec, '--root', $hash;
6512 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6513 '--encoding=utf8', '--stdout', @commit_spec
6514 or die_error(500, "Open git-format-patch failed");
6515 } else {
6516 die_error(400, "Unknown commitdiff format");
6519 # non-textual hash id's can be cached
6520 my $expires;
6521 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6522 $expires = "+1d";
6525 # write commit message
6526 if ($format eq 'html') {
6527 my $refs = git_get_references();
6528 my $ref = format_ref_marker($refs, $co{'id'});
6530 git_header_html(undef, $expires);
6531 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6532 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6533 print "<div class=\"title_text\">\n" .
6534 "<table class=\"object_header\">\n";
6535 git_print_authorship_rows(\%co);
6536 print "</table>".
6537 "</div>\n";
6538 print "<div class=\"page_body\">\n";
6539 if (@{$co{'comment'}} > 1) {
6540 print "<div class=\"log\">\n";
6541 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6542 print "</div>\n"; # class="log"
6545 } elsif ($format eq 'plain') {
6546 my $refs = git_get_references("tags");
6547 my $tagname = git_get_rev_name_tags($hash);
6548 my $filename = basename($project) . "-$hash.patch";
6550 print $cgi->header(
6551 -type => 'text/plain',
6552 -charset => 'utf-8',
6553 -expires => $expires,
6554 -content_disposition => 'inline; filename="' . "$filename" . '"');
6555 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6556 print "From: " . to_utf8($co{'author'}) . "\n";
6557 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6558 print "Subject: " . to_utf8($co{'title'}) . "\n";
6560 print "X-Git-Tag: $tagname\n" if $tagname;
6561 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6563 foreach my $line (@{$co{'comment'}}) {
6564 print to_utf8($line) . "\n";
6566 print "---\n\n";
6567 } elsif ($format eq 'patch') {
6568 my $filename = basename($project) . "-$hash.patch";
6570 print $cgi->header(
6571 -type => 'text/plain',
6572 -charset => 'utf-8',
6573 -expires => $expires,
6574 -content_disposition => 'inline; filename="' . "$filename" . '"');
6577 # write patch
6578 if ($format eq 'html') {
6579 my $use_parents = !defined $hash_parent ||
6580 $hash_parent eq '-c' || $hash_parent eq '--cc';
6581 git_difftree_body(\@difftree, $hash,
6582 $use_parents ? @{$co{'parents'}} : $hash_parent);
6583 print "<br/>\n";
6585 git_patchset_body($fd, \@difftree, $hash,
6586 $use_parents ? @{$co{'parents'}} : $hash_parent);
6587 close $fd;
6588 print "</div>\n"; # class="page_body"
6589 git_footer_html();
6591 } elsif ($format eq 'plain') {
6592 local $/ = undef;
6593 print <$fd>;
6594 close $fd
6595 or print "Reading git-diff-tree failed\n";
6596 } elsif ($format eq 'patch') {
6597 local $/ = undef;
6598 print <$fd>;
6599 close $fd
6600 or print "Reading git-format-patch failed\n";
6604 sub git_commitdiff_plain {
6605 git_commitdiff(-format => 'plain');
6608 # format-patch-style patches
6609 sub git_patch {
6610 git_commitdiff(-format => 'patch', -single => 1);
6613 sub git_patches {
6614 git_commitdiff(-format => 'patch');
6617 sub git_history {
6618 git_log_generic('history', \&git_history_body,
6619 $hash_base, $hash_parent_base,
6620 $file_name, $hash);
6623 sub git_search {
6624 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6625 if (!defined $searchtext) {
6626 die_error(400, "Text field is empty");
6628 if (!defined $hash) {
6629 $hash = git_get_head_hash($project);
6631 my %co = parse_commit($hash);
6632 if (!%co) {
6633 die_error(404, "Unknown commit object");
6635 if (!defined $page) {
6636 $page = 0;
6639 $searchtype ||= 'commit';
6640 if ($searchtype eq 'pickaxe') {
6641 # pickaxe may take all resources of your box and run for several minutes
6642 # with every query - so decide by yourself how public you make this feature
6643 gitweb_check_feature('pickaxe')
6644 or die_error(403, "Pickaxe is disabled");
6646 if ($searchtype eq 'grep') {
6647 gitweb_check_feature('grep')
6648 or die_error(403, "Grep is disabled");
6651 git_header_html();
6653 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6654 my $greptype;
6655 if ($searchtype eq 'commit') {
6656 $greptype = "--grep=";
6657 } elsif ($searchtype eq 'author') {
6658 $greptype = "--author=";
6659 } elsif ($searchtype eq 'committer') {
6660 $greptype = "--committer=";
6662 $greptype .= $searchtext;
6663 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6664 $greptype, '--regexp-ignore-case',
6665 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6667 my $paging_nav = '';
6668 if ($page > 0) {
6669 $paging_nav .=
6670 $cgi->a({-href => href(action=>"search", hash=>$hash,
6671 searchtext=>$searchtext,
6672 searchtype=>$searchtype)},
6673 "first");
6674 $paging_nav .= " &sdot; " .
6675 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6676 -accesskey => "p", -title => "Alt-p"}, "prev");
6677 } else {
6678 $paging_nav .= "first";
6679 $paging_nav .= " &sdot; prev";
6681 my $next_link = '';
6682 if ($#commitlist >= 100) {
6683 $next_link =
6684 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6685 -accesskey => "n", -title => "Alt-n"}, "next");
6686 $paging_nav .= " &sdot; $next_link";
6687 } else {
6688 $paging_nav .= " &sdot; next";
6691 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6692 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6693 if ($page == 0 && !@commitlist) {
6694 print "<p>No match.</p>\n";
6695 } else {
6696 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6700 if ($searchtype eq 'pickaxe') {
6701 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6702 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6704 print "<table class=\"pickaxe search\">\n";
6705 my $alternate = 1;
6706 local $/ = "\n";
6707 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6708 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6709 ($search_use_regexp ? '--pickaxe-regex' : ());
6710 undef %co;
6711 my @files;
6712 while (my $line = <$fd>) {
6713 chomp $line;
6714 next unless $line;
6716 my %set = parse_difftree_raw_line($line);
6717 if (defined $set{'commit'}) {
6718 # finish previous commit
6719 if (%co) {
6720 print "</td>\n" .
6721 "<td class=\"link\">" .
6722 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6723 " | " .
6724 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6725 print "</td>\n" .
6726 "</tr>\n";
6729 if ($alternate) {
6730 print "<tr class=\"dark\">\n";
6731 } else {
6732 print "<tr class=\"light\">\n";
6734 $alternate ^= 1;
6735 %co = parse_commit($set{'commit'});
6736 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6737 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6738 "<td><i>$author</i></td>\n" .
6739 "<td>" .
6740 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6741 -class => "list subject"},
6742 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6743 } elsif (defined $set{'to_id'}) {
6744 next if ($set{'to_id'} =~ m/^0{40}$/);
6746 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6747 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6748 -class => "list"},
6749 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6750 "<br/>\n";
6753 close $fd;
6755 # finish last commit (warning: repetition!)
6756 if (%co) {
6757 print "</td>\n" .
6758 "<td class=\"link\">" .
6759 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6760 " | " .
6761 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6762 print "</td>\n" .
6763 "</tr>\n";
6766 print "</table>\n";
6769 if ($searchtype eq 'grep') {
6770 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6771 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6773 print "<table class=\"grep_search\">\n";
6774 my $alternate = 1;
6775 my $matches = 0;
6776 local $/ = "\n";
6777 open my $fd, "-|", git_cmd(), 'grep', '-n',
6778 $search_use_regexp ? ('-E', '-i') : '-F',
6779 $searchtext, $co{'tree'};
6780 my $lastfile = '';
6781 while (my $line = <$fd>) {
6782 chomp $line;
6783 my ($file, $lno, $ltext, $binary);
6784 last if ($matches++ > 1000);
6785 if ($line =~ /^Binary file (.+) matches$/) {
6786 $file = $1;
6787 $binary = 1;
6788 } else {
6789 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6791 if ($file ne $lastfile) {
6792 $lastfile and print "</td></tr>\n";
6793 if ($alternate++) {
6794 print "<tr class=\"dark\">\n";
6795 } else {
6796 print "<tr class=\"light\">\n";
6798 print "<td class=\"list\">".
6799 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6800 file_name=>"$file"),
6801 -class => "list"}, esc_path($file));
6802 print "</td><td>\n";
6803 $lastfile = $file;
6805 if ($binary) {
6806 print "<div class=\"binary\">Binary file</div>\n";
6807 } else {
6808 $ltext = untabify($ltext);
6809 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6810 $ltext = esc_html($1, -nbsp=>1);
6811 $ltext .= '<span class="match">';
6812 $ltext .= esc_html($2, -nbsp=>1);
6813 $ltext .= '</span>';
6814 $ltext .= esc_html($3, -nbsp=>1);
6815 } else {
6816 $ltext = esc_html($ltext, -nbsp=>1);
6818 print "<div class=\"pre\">" .
6819 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6820 file_name=>"$file").'#l'.$lno,
6821 -class => "linenr"}, sprintf('%4i', $lno))
6822 . ' ' . $ltext . "</div>\n";
6825 if ($lastfile) {
6826 print "</td></tr>\n";
6827 if ($matches > 1000) {
6828 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6830 } else {
6831 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6833 close $fd;
6835 print "</table>\n";
6837 git_footer_html();
6840 sub git_search_help {
6841 git_header_html();
6842 git_print_page_nav('','', $hash,$hash,$hash);
6843 print <<EOT;
6844 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6845 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6846 the pattern entered is recognized as the POSIX extended
6847 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6848 insensitive).</p>
6849 <dl>
6850 <dt><b>commit</b></dt>
6851 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6853 my $have_grep = gitweb_check_feature('grep');
6854 if ($have_grep) {
6855 print <<EOT;
6856 <dt><b>grep</b></dt>
6857 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6858 a different one) are searched for the given pattern. On large trees, this search can take
6859 a while and put some strain on the server, so please use it with some consideration. Note that
6860 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6861 case-sensitive.</dd>
6864 print <<EOT;
6865 <dt><b>author</b></dt>
6866 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6867 <dt><b>committer</b></dt>
6868 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6870 my $have_pickaxe = gitweb_check_feature('pickaxe');
6871 if ($have_pickaxe) {
6872 print <<EOT;
6873 <dt><b>pickaxe</b></dt>
6874 <dd>All commits that caused the string to appear or disappear from any file (changes that
6875 added, removed or "modified" the string) will be listed. This search can take a while and
6876 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6877 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6880 print "</dl>\n";
6881 git_footer_html();
6884 sub git_shortlog {
6885 git_log_generic('shortlog', \&git_shortlog_body,
6886 $hash, $hash_parent);
6889 ## ......................................................................
6890 ## feeds (RSS, Atom; OPML)
6892 sub git_feed {
6893 my $format = shift || 'atom';
6894 my $have_blame = gitweb_check_feature('blame');
6896 # Atom: http://www.atomenabled.org/developers/syndication/
6897 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6898 if ($format ne 'rss' && $format ne 'atom') {
6899 die_error(400, "Unknown web feed format");
6902 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6903 my $head = $hash || 'HEAD';
6904 my @commitlist = parse_commits($head, 150, 0, $file_name);
6906 my %latest_commit;
6907 my %latest_date;
6908 my $content_type = "application/$format+xml";
6909 if (defined $cgi->http('HTTP_ACCEPT') &&
6910 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6911 # browser (feed reader) prefers text/xml
6912 $content_type = 'text/xml';
6914 if (defined($commitlist[0])) {
6915 %latest_commit = %{$commitlist[0]};
6916 my $latest_epoch = $latest_commit{'committer_epoch'};
6917 %latest_date = parse_date($latest_epoch);
6918 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6919 if (defined $if_modified) {
6920 my $since;
6921 if (eval { require HTTP::Date; 1; }) {
6922 $since = HTTP::Date::str2time($if_modified);
6923 } elsif (eval { require Time::ParseDate; 1; }) {
6924 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6926 if (defined $since && $latest_epoch <= $since) {
6927 print $cgi->header(
6928 -type => $content_type,
6929 -charset => 'utf-8',
6930 -last_modified => $latest_date{'rfc2822'},
6931 -status => '304 Not Modified');
6932 return;
6935 print $cgi->header(
6936 -type => $content_type,
6937 -charset => 'utf-8',
6938 -last_modified => $latest_date{'rfc2822'});
6939 } else {
6940 print $cgi->header(
6941 -type => $content_type,
6942 -charset => 'utf-8');
6945 # Optimization: skip generating the body if client asks only
6946 # for Last-Modified date.
6947 return if ($cgi->request_method() eq 'HEAD');
6949 # header variables
6950 my $title = "$site_name - $project/$action";
6951 my $feed_type = 'log';
6952 if (defined $hash) {
6953 $title .= " - '$hash'";
6954 $feed_type = 'branch log';
6955 if (defined $file_name) {
6956 $title .= " :: $file_name";
6957 $feed_type = 'history';
6959 } elsif (defined $file_name) {
6960 $title .= " - $file_name";
6961 $feed_type = 'history';
6963 $title .= " $feed_type";
6964 my $descr = git_get_project_description($project);
6965 if (defined $descr) {
6966 $descr = esc_html($descr);
6967 } else {
6968 $descr = "$project " .
6969 ($format eq 'rss' ? 'RSS' : 'Atom') .
6970 " feed";
6972 my $owner = git_get_project_owner($project);
6973 $owner = esc_html($owner);
6975 #header
6976 my $alt_url;
6977 if (defined $file_name) {
6978 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6979 } elsif (defined $hash) {
6980 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6981 } else {
6982 $alt_url = href(-full=>1, action=>"summary");
6984 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6985 if ($format eq 'rss') {
6986 print <<XML;
6987 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6988 <channel>
6990 print "<title>$title</title>\n" .
6991 "<link>$alt_url</link>\n" .
6992 "<description>$descr</description>\n" .
6993 "<language>en</language>\n" .
6994 # project owner is responsible for 'editorial' content
6995 "<managingEditor>$owner</managingEditor>\n";
6996 if (defined $logo || defined $favicon) {
6997 # prefer the logo to the favicon, since RSS
6998 # doesn't allow both
6999 my $img = esc_url($logo || $favicon);
7000 print "<image>\n" .
7001 "<url>$img</url>\n" .
7002 "<title>$title</title>\n" .
7003 "<link>$alt_url</link>\n" .
7004 "</image>\n";
7006 if (%latest_date) {
7007 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7008 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7010 print "<generator>gitweb v.$version/$git_version</generator>\n";
7011 } elsif ($format eq 'atom') {
7012 print <<XML;
7013 <feed xmlns="http://www.w3.org/2005/Atom">
7015 print "<title>$title</title>\n" .
7016 "<subtitle>$descr</subtitle>\n" .
7017 '<link rel="alternate" type="text/html" href="' .
7018 $alt_url . '" />' . "\n" .
7019 '<link rel="self" type="' . $content_type . '" href="' .
7020 $cgi->self_url() . '" />' . "\n" .
7021 "<id>" . href(-full=>1) . "</id>\n" .
7022 # use project owner for feed author
7023 "<author><name>$owner</name></author>\n";
7024 if (defined $favicon) {
7025 print "<icon>" . esc_url($favicon) . "</icon>\n";
7027 if (defined $logo_url) {
7028 # not twice as wide as tall: 72 x 27 pixels
7029 print "<logo>" . esc_url($logo) . "</logo>\n";
7031 if (! %latest_date) {
7032 # dummy date to keep the feed valid until commits trickle in:
7033 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7034 } else {
7035 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7037 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7040 # contents
7041 for (my $i = 0; $i <= $#commitlist; $i++) {
7042 my %co = %{$commitlist[$i]};
7043 my $commit = $co{'id'};
7044 # we read 150, we always show 30 and the ones more recent than 48 hours
7045 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7046 last;
7048 my %cd = parse_date($co{'author_epoch'});
7050 # get list of changed files
7051 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7052 $co{'parent'} || "--root",
7053 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7054 or next;
7055 my @difftree = map { chomp; $_ } <$fd>;
7056 close $fd
7057 or next;
7059 # print element (entry, item)
7060 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7061 if ($format eq 'rss') {
7062 print "<item>\n" .
7063 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7064 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7065 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7066 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7067 "<link>$co_url</link>\n" .
7068 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7069 "<content:encoded>" .
7070 "<![CDATA[\n";
7071 } elsif ($format eq 'atom') {
7072 print "<entry>\n" .
7073 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7074 "<updated>$cd{'iso-8601'}</updated>\n" .
7075 "<author>\n" .
7076 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7077 if ($co{'author_email'}) {
7078 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7080 print "</author>\n" .
7081 # use committer for contributor
7082 "<contributor>\n" .
7083 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7084 if ($co{'committer_email'}) {
7085 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7087 print "</contributor>\n" .
7088 "<published>$cd{'iso-8601'}</published>\n" .
7089 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7090 "<id>$co_url</id>\n" .
7091 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7092 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7094 my $comment = $co{'comment'};
7095 print "<pre>\n";
7096 foreach my $line (@$comment) {
7097 $line = esc_html($line);
7098 print "$line\n";
7100 print "</pre><ul>\n";
7101 foreach my $difftree_line (@difftree) {
7102 my %difftree = parse_difftree_raw_line($difftree_line);
7103 next if !$difftree{'from_id'};
7105 my $file = $difftree{'file'} || $difftree{'to_file'};
7107 print "<li>" .
7108 "[" .
7109 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7110 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7111 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7112 file_name=>$file, file_parent=>$difftree{'from_file'}),
7113 -title => "diff"}, 'D');
7114 if ($have_blame) {
7115 print $cgi->a({-href => href(-full=>1, action=>"blame",
7116 file_name=>$file, hash_base=>$commit),
7117 -title => "blame"}, 'B');
7119 # if this is not a feed of a file history
7120 if (!defined $file_name || $file_name ne $file) {
7121 print $cgi->a({-href => href(-full=>1, action=>"history",
7122 file_name=>$file, hash=>$commit),
7123 -title => "history"}, 'H');
7125 $file = esc_path($file);
7126 print "] ".
7127 "$file</li>\n";
7129 if ($format eq 'rss') {
7130 print "</ul>]]>\n" .
7131 "</content:encoded>\n" .
7132 "</item>\n";
7133 } elsif ($format eq 'atom') {
7134 print "</ul>\n</div>\n" .
7135 "</content>\n" .
7136 "</entry>\n";
7140 # end of feed
7141 if ($format eq 'rss') {
7142 print "</channel>\n</rss>\n";
7143 } elsif ($format eq 'atom') {
7144 print "</feed>\n";
7148 sub git_rss {
7149 git_feed('rss');
7152 sub git_atom {
7153 git_feed('atom');
7156 sub git_opml {
7157 my @list = git_get_projects_list();
7159 print $cgi->header(
7160 -type => 'text/xml',
7161 -charset => 'utf-8',
7162 -content_disposition => 'inline; filename="opml.xml"');
7164 print <<XML;
7165 <?xml version="1.0" encoding="utf-8"?>
7166 <opml version="1.0">
7167 <head>
7168 <title>$site_name OPML Export</title>
7169 </head>
7170 <body>
7171 <outline text="git RSS feeds">
7174 foreach my $pr (@list) {
7175 my %proj = %$pr;
7176 my $head = git_get_head_hash($proj{'path'});
7177 if (!defined $head) {
7178 next;
7180 $git_dir = "$projectroot/$proj{'path'}";
7181 my %co = parse_commit($head);
7182 if (!%co) {
7183 next;
7186 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7187 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7188 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7189 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7191 print <<XML;
7192 </outline>
7193 </body>
7194 </opml>