f6932319ad5caf7e6aad999b2e6eed7e586bdcd8
[git/jnareb-git.git] / gitweb / gitweb.perl
blobf6932319ad5caf7e6aad999b2e6eed7e586bdcd8
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 # Set to _initialized_ instance of GitwebCache::Capture compatibile capturing
340 # engine, i.e. one implementing ->new() constructor, and ->capture($code)
341 # method. If unset (default), the GitwebCache::Capture::Simple would be used.
342 our $capture;
344 # You define site-wide feature defaults here; override them with
345 # $GITWEB_CONFIG as necessary.
346 our %feature = (
347 # feature => {
348 # 'sub' => feature-sub (subroutine),
349 # 'override' => allow-override (boolean),
350 # 'default' => [ default options...] (array reference)}
352 # if feature is overridable (it means that allow-override has true value),
353 # then feature-sub will be called with default options as parameters;
354 # return value of feature-sub indicates if to enable specified feature
356 # if there is no 'sub' key (no feature-sub), then feature cannot be
357 # overridden
359 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
360 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
361 # is enabled
363 # Enable the 'blame' blob view, showing the last commit that modified
364 # each line in the file. This can be very CPU-intensive.
366 # To enable system wide have in $GITWEB_CONFIG
367 # $feature{'blame'}{'default'} = [1];
368 # To have project specific config enable override in $GITWEB_CONFIG
369 # $feature{'blame'}{'override'} = 1;
370 # and in project config gitweb.blame = 0|1;
371 'blame' => {
372 'sub' => sub { feature_bool('blame', @_) },
373 'override' => 0,
374 'default' => [0]},
376 # Enable the 'snapshot' link, providing a compressed archive of any
377 # tree. This can potentially generate high traffic if you have large
378 # project.
380 # Value is a list of formats defined in %known_snapshot_formats that
381 # you wish to offer.
382 # To disable system wide have in $GITWEB_CONFIG
383 # $feature{'snapshot'}{'default'} = [];
384 # To have project specific config enable override in $GITWEB_CONFIG
385 # $feature{'snapshot'}{'override'} = 1;
386 # and in project config, a comma-separated list of formats or "none"
387 # to disable. Example: gitweb.snapshot = tbz2,zip;
388 'snapshot' => {
389 'sub' => \&feature_snapshot,
390 'override' => 0,
391 'default' => ['tgz']},
393 # Enable text search, which will list the commits which match author,
394 # committer or commit text to a given string. Enabled by default.
395 # Project specific override is not supported.
396 'search' => {
397 'override' => 0,
398 'default' => [1]},
400 # Enable grep search, which will list the files in currently selected
401 # tree containing the given string. Enabled by default. This can be
402 # potentially CPU-intensive, of course.
404 # To enable system wide have in $GITWEB_CONFIG
405 # $feature{'grep'}{'default'} = [1];
406 # To have project specific config enable override in $GITWEB_CONFIG
407 # $feature{'grep'}{'override'} = 1;
408 # and in project config gitweb.grep = 0|1;
409 'grep' => {
410 'sub' => sub { feature_bool('grep', @_) },
411 'override' => 0,
412 'default' => [1]},
414 # Enable the pickaxe search, which will list the commits that modified
415 # a given string in a file. This can be practical and quite faster
416 # alternative to 'blame', but still potentially CPU-intensive.
418 # To enable system wide have in $GITWEB_CONFIG
419 # $feature{'pickaxe'}{'default'} = [1];
420 # To have project specific config enable override in $GITWEB_CONFIG
421 # $feature{'pickaxe'}{'override'} = 1;
422 # and in project config gitweb.pickaxe = 0|1;
423 'pickaxe' => {
424 'sub' => sub { feature_bool('pickaxe', @_) },
425 'override' => 0,
426 'default' => [1]},
428 # Enable showing size of blobs in a 'tree' view, in a separate
429 # column, similar to what 'ls -l' does. This cost a bit of IO.
431 # To disable system wide have in $GITWEB_CONFIG
432 # $feature{'show-sizes'}{'default'} = [0];
433 # To have project specific config enable override in $GITWEB_CONFIG
434 # $feature{'show-sizes'}{'override'} = 1;
435 # and in project config gitweb.showsizes = 0|1;
436 'show-sizes' => {
437 'sub' => sub { feature_bool('showsizes', @_) },
438 'override' => 0,
439 'default' => [1]},
441 # Make gitweb use an alternative format of the URLs which can be
442 # more readable and natural-looking: project name is embedded
443 # directly in the path and the query string contains other
444 # auxiliary information. All gitweb installations recognize
445 # URL in either format; this configures in which formats gitweb
446 # generates links.
448 # To enable system wide have in $GITWEB_CONFIG
449 # $feature{'pathinfo'}{'default'} = [1];
450 # Project specific override is not supported.
452 # Note that you will need to change the default location of CSS,
453 # favicon, logo and possibly other files to an absolute URL. Also,
454 # if gitweb.cgi serves as your indexfile, you will need to force
455 # $my_uri to contain the script name in your $GITWEB_CONFIG.
456 'pathinfo' => {
457 'override' => 0,
458 'default' => [0]},
460 # Make gitweb consider projects in project root subdirectories
461 # to be forks of existing projects. Given project $projname.git,
462 # projects matching $projname/*.git will not be shown in the main
463 # projects list, instead a '+' mark will be added to $projname
464 # there and a 'forks' view will be enabled for the project, listing
465 # all the forks. If project list is taken from a file, forks have
466 # to be listed after the main project.
468 # To enable system wide have in $GITWEB_CONFIG
469 # $feature{'forks'}{'default'} = [1];
470 # Project specific override is not supported.
471 'forks' => {
472 'override' => 0,
473 'default' => [0]},
475 # Insert custom links to the action bar of all project pages.
476 # This enables you mainly to link to third-party scripts integrating
477 # into gitweb; e.g. git-browser for graphical history representation
478 # or custom web-based repository administration interface.
480 # The 'default' value consists of a list of triplets in the form
481 # (label, link, position) where position is the label after which
482 # to insert the link and link is a format string where %n expands
483 # to the project name, %f to the project path within the filesystem,
484 # %h to the current hash (h gitweb parameter) and %b to the current
485 # hash base (hb gitweb parameter); %% expands to %.
487 # To enable system wide have in $GITWEB_CONFIG e.g.
488 # $feature{'actions'}{'default'} = [('graphiclog',
489 # '/git-browser/by-commit.html?r=%n', 'summary')];
490 # Project specific override is not supported.
491 'actions' => {
492 'override' => 0,
493 'default' => []},
495 # Allow gitweb scan project content tags described in ctags/
496 # of project repository, and display the popular Web 2.0-ish
497 # "tag cloud" near the project list. Note that this is something
498 # COMPLETELY different from the normal Git tags.
500 # gitweb by itself can show existing tags, but it does not handle
501 # tagging itself; you need an external application for that.
502 # For an example script, check Girocco's cgi/tagproj.cgi.
503 # You may want to install the HTML::TagCloud Perl module to get
504 # a pretty tag cloud instead of just a list of tags.
506 # To enable system wide have in $GITWEB_CONFIG
507 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
508 # Project specific override is not supported.
509 'ctags' => {
510 'override' => 0,
511 'default' => [0]},
513 # The maximum number of patches in a patchset generated in patch
514 # view. Set this to 0 or undef to disable patch view, or to a
515 # negative number to remove any limit.
517 # To disable system wide have in $GITWEB_CONFIG
518 # $feature{'patches'}{'default'} = [0];
519 # To have project specific config enable override in $GITWEB_CONFIG
520 # $feature{'patches'}{'override'} = 1;
521 # and in project config gitweb.patches = 0|n;
522 # where n is the maximum number of patches allowed in a patchset.
523 'patches' => {
524 'sub' => \&feature_patches,
525 'override' => 0,
526 'default' => [16]},
528 # Avatar support. When this feature is enabled, views such as
529 # shortlog or commit will display an avatar associated with
530 # the email of the committer(s) and/or author(s).
532 # Currently available providers are gravatar and picon.
533 # If an unknown provider is specified, the feature is disabled.
535 # Gravatar depends on Digest::MD5.
536 # Picon currently relies on the indiana.edu database.
538 # To enable system wide have in $GITWEB_CONFIG
539 # $feature{'avatar'}{'default'} = ['<provider>'];
540 # where <provider> is either gravatar or picon.
541 # To have project specific config enable override in $GITWEB_CONFIG
542 # $feature{'avatar'}{'override'} = 1;
543 # and in project config gitweb.avatar = <provider>;
544 'avatar' => {
545 'sub' => \&feature_avatar,
546 'override' => 0,
547 'default' => ['']},
549 # Enable displaying how much time and how many git commands
550 # it took to generate and display page. Disabled by default.
551 # Project specific override is not supported.
552 'timed' => {
553 'override' => 0,
554 'default' => [0]},
556 # Enable turning some links into links to actions which require
557 # JavaScript to run (like 'blame_incremental'). Not enabled by
558 # default. Project specific override is currently not supported.
559 'javascript-actions' => {
560 'override' => 0,
561 'default' => [0]},
563 # Syntax highlighting support. This is based on Daniel Svensson's
564 # and Sham Chukoury's work in gitweb-xmms2.git.
565 # It requires the 'highlight' program present in $PATH,
566 # and therefore is disabled by default.
568 # To enable system wide have in $GITWEB_CONFIG
569 # $feature{'highlight'}{'default'} = [1];
571 'highlight' => {
572 'sub' => sub { feature_bool('highlight', @_) },
573 'override' => 0,
574 'default' => [0]},
577 sub gitweb_get_feature {
578 my ($name) = @_;
579 return unless exists $feature{$name};
580 my ($sub, $override, @defaults) = (
581 $feature{$name}{'sub'},
582 $feature{$name}{'override'},
583 @{$feature{$name}{'default'}});
584 # project specific override is possible only if we have project
585 our $git_dir; # global variable, declared later
586 if (!$override || !defined $git_dir) {
587 return @defaults;
589 if (!defined $sub) {
590 warn "feature $name is not overridable";
591 return @defaults;
593 return $sub->(@defaults);
596 # A wrapper to check if a given feature is enabled.
597 # With this, you can say
599 # my $bool_feat = gitweb_check_feature('bool_feat');
600 # gitweb_check_feature('bool_feat') or somecode;
602 # instead of
604 # my ($bool_feat) = gitweb_get_feature('bool_feat');
605 # (gitweb_get_feature('bool_feat'))[0] or somecode;
607 sub gitweb_check_feature {
608 return (gitweb_get_feature(@_))[0];
612 sub feature_bool {
613 my $key = shift;
614 my ($val) = git_get_project_config($key, '--bool');
616 if (!defined $val) {
617 return ($_[0]);
618 } elsif ($val eq 'true') {
619 return (1);
620 } elsif ($val eq 'false') {
621 return (0);
625 sub feature_snapshot {
626 my (@fmts) = @_;
628 my ($val) = git_get_project_config('snapshot');
630 if ($val) {
631 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
634 return @fmts;
637 sub feature_patches {
638 my @val = (git_get_project_config('patches', '--int'));
640 if (@val) {
641 return @val;
644 return ($_[0]);
647 sub feature_avatar {
648 my @val = (git_get_project_config('avatar'));
650 return @val ? @val : @_;
653 # checking HEAD file with -e is fragile if the repository was
654 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
655 # and then pruned.
656 sub check_head_link {
657 my ($dir) = @_;
658 my $headfile = "$dir/HEAD";
659 return ((-e $headfile) ||
660 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
663 sub check_export_ok {
664 my ($dir) = @_;
665 return (check_head_link($dir) &&
666 (!$export_ok || -e "$dir/$export_ok") &&
667 (!$export_auth_hook || $export_auth_hook->($dir)));
670 # process alternate names for backward compatibility
671 # filter out unsupported (unknown) snapshot formats
672 sub filter_snapshot_fmts {
673 my @fmts = @_;
675 @fmts = map {
676 exists $known_snapshot_format_aliases{$_} ?
677 $known_snapshot_format_aliases{$_} : $_} @fmts;
678 @fmts = grep {
679 exists $known_snapshot_formats{$_} &&
680 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
683 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
684 sub evaluate_gitweb_config {
685 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
686 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
687 # die if there are errors parsing config file
688 if (-e $GITWEB_CONFIG) {
689 do $GITWEB_CONFIG;
690 die $@ if $@;
691 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
692 do $GITWEB_CONFIG_SYSTEM;
693 die $@ if $@;
697 # Get loadavg of system, to compare against $maxload.
698 # Currently it requires '/proc/loadavg' present to get loadavg;
699 # if it is not present it returns 0, which means no load checking.
700 sub get_loadavg {
701 if( -e '/proc/loadavg' ){
702 open my $fd, '<', '/proc/loadavg'
703 or return 0;
704 my @load = split(/\s+/, scalar <$fd>);
705 close $fd;
707 # The first three columns measure CPU and IO utilization of the last one,
708 # five, and 10 minute periods. The fourth column shows the number of
709 # currently running processes and the total number of processes in the m/n
710 # format. The last column displays the last process ID used.
711 return $load[0] || 0;
713 # additional checks for load average should go here for things that don't export
714 # /proc/loadavg
716 return 0;
719 # version of the core git binary
720 our $git_version;
721 sub evaluate_git_version {
722 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
723 $number_of_git_cmds++;
726 sub check_loadavg {
727 if (defined $maxload && get_loadavg() > $maxload) {
728 die_error(503, "The load average on the server is too high");
732 # ======================================================================
733 # input validation and dispatch
735 # input parameters can be collected from a variety of sources (presently, CGI
736 # and PATH_INFO), so we define an %input_params hash that collects them all
737 # together during validation: this allows subsequent uses (e.g. href()) to be
738 # agnostic of the parameter origin
740 our %input_params = ();
742 # input parameters are stored with the long parameter name as key. This will
743 # also be used in the href subroutine to convert parameters to their CGI
744 # equivalent, and since the href() usage is the most frequent one, we store
745 # the name -> CGI key mapping here, instead of the reverse.
747 # XXX: Warning: If you touch this, check the search form for updating,
748 # too.
750 our @cgi_param_mapping = (
751 project => "p",
752 action => "a",
753 file_name => "f",
754 file_parent => "fp",
755 hash => "h",
756 hash_parent => "hp",
757 hash_base => "hb",
758 hash_parent_base => "hpb",
759 page => "pg",
760 order => "o",
761 searchtext => "s",
762 searchtype => "st",
763 snapshot_format => "sf",
764 extra_options => "opt",
765 search_use_regexp => "sr",
766 # this must be last entry (for manipulation from JavaScript)
767 javascript => "js"
769 our %cgi_param_mapping = @cgi_param_mapping;
771 # we will also need to know the possible actions, for validation
772 our %actions = (
773 "blame" => \&git_blame,
774 "blame_incremental" => \&git_blame_incremental,
775 "blame_data" => \&git_blame_data,
776 "blobdiff" => \&git_blobdiff,
777 "blobdiff_plain" => \&git_blobdiff_plain,
778 "blob" => \&git_blob,
779 "blob_plain" => \&git_blob_plain,
780 "commitdiff" => \&git_commitdiff,
781 "commitdiff_plain" => \&git_commitdiff_plain,
782 "commit" => \&git_commit,
783 "forks" => \&git_forks,
784 "heads" => \&git_heads,
785 "history" => \&git_history,
786 "log" => \&git_log,
787 "patch" => \&git_patch,
788 "patches" => \&git_patches,
789 "rss" => \&git_rss,
790 "atom" => \&git_atom,
791 "search" => \&git_search,
792 "search_help" => \&git_search_help,
793 "shortlog" => \&git_shortlog,
794 "summary" => \&git_summary,
795 "tag" => \&git_tag,
796 "tags" => \&git_tags,
797 "tree" => \&git_tree,
798 "snapshot" => \&git_snapshot,
799 "object" => \&git_object,
800 # those below don't need $project
801 "opml" => \&git_opml,
802 "project_list" => \&git_project_list,
803 "project_index" => \&git_project_index,
806 # finally, we have the hash of allowed extra_options for the commands that
807 # allow them
808 our %allowed_options = (
809 "--no-merges" => [ qw(rss atom log shortlog history) ],
812 # fill %input_params with the CGI parameters. All values except for 'opt'
813 # should be single values, but opt can be an array. We should probably
814 # build an array of parameters that can be multi-valued, but since for the time
815 # being it's only this one, we just single it out
816 sub evaluate_query_params {
817 our $cgi;
819 while (my ($name, $symbol) = each %cgi_param_mapping) {
820 if ($symbol eq 'opt') {
821 $input_params{$name} = [ $cgi->param($symbol) ];
822 } else {
823 $input_params{$name} = $cgi->param($symbol);
828 # now read PATH_INFO and update the parameter list for missing parameters
829 sub evaluate_path_info {
830 return if defined $input_params{'project'};
831 return if !$path_info;
832 $path_info =~ s,^/+,,;
833 return if !$path_info;
835 # find which part of PATH_INFO is project
836 my $project = $path_info;
837 $project =~ s,/+$,,;
838 while ($project && !check_head_link("$projectroot/$project")) {
839 $project =~ s,/*[^/]*$,,;
841 return unless $project;
842 $input_params{'project'} = $project;
844 # do not change any parameters if an action is given using the query string
845 return if $input_params{'action'};
846 $path_info =~ s,^\Q$project\E/*,,;
848 # next, check if we have an action
849 my $action = $path_info;
850 $action =~ s,/.*$,,;
851 if (exists $actions{$action}) {
852 $path_info =~ s,^$action/*,,;
853 $input_params{'action'} = $action;
856 # list of actions that want hash_base instead of hash, but can have no
857 # pathname (f) parameter
858 my @wants_base = (
859 'tree',
860 'history',
863 # we want to catch, among others
864 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
865 my ($parentrefname, $parentpathname, $refname, $pathname) =
866 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
868 # first, analyze the 'current' part
869 if (defined $pathname) {
870 # we got "branch:filename" or "branch:dir/"
871 # we could use git_get_type(branch:pathname), but:
872 # - it needs $git_dir
873 # - it does a git() call
874 # - the convention of terminating directories with a slash
875 # makes it superfluous
876 # - embedding the action in the PATH_INFO would make it even
877 # more superfluous
878 $pathname =~ s,^/+,,;
879 if (!$pathname || substr($pathname, -1) eq "/") {
880 $input_params{'action'} ||= "tree";
881 $pathname =~ s,/$,,;
882 } else {
883 # the default action depends on whether we had parent info
884 # or not
885 if ($parentrefname) {
886 $input_params{'action'} ||= "blobdiff_plain";
887 } else {
888 $input_params{'action'} ||= "blob_plain";
891 $input_params{'hash_base'} ||= $refname;
892 $input_params{'file_name'} ||= $pathname;
893 } elsif (defined $refname) {
894 # we got "branch". In this case we have to choose if we have to
895 # set hash or hash_base.
897 # Most of the actions without a pathname only want hash to be
898 # set, except for the ones specified in @wants_base that want
899 # hash_base instead. It should also be noted that hand-crafted
900 # links having 'history' as an action and no pathname or hash
901 # set will fail, but that happens regardless of PATH_INFO.
902 if (defined $parentrefname) {
903 # if there is parent let the default be 'shortlog' action
904 # (for http://git.example.com/repo.git/A..B links); if there
905 # is no parent, dispatch will detect type of object and set
906 # action appropriately if required (if action is not set)
907 $input_params{'action'} ||= "shortlog";
909 if ($input_params{'action'} &&
910 grep { $_ eq $input_params{'action'} } @wants_base) {
911 $input_params{'hash_base'} ||= $refname;
912 } else {
913 $input_params{'hash'} ||= $refname;
917 # next, handle the 'parent' part, if present
918 if (defined $parentrefname) {
919 # a missing pathspec defaults to the 'current' filename, allowing e.g.
920 # someproject/blobdiff/oldrev..newrev:/filename
921 if ($parentpathname) {
922 $parentpathname =~ s,^/+,,;
923 $parentpathname =~ s,/$,,;
924 $input_params{'file_parent'} ||= $parentpathname;
925 } else {
926 $input_params{'file_parent'} ||= $input_params{'file_name'};
928 # we assume that hash_parent_base is wanted if a path was specified,
929 # or if the action wants hash_base instead of hash
930 if (defined $input_params{'file_parent'} ||
931 grep { $_ eq $input_params{'action'} } @wants_base) {
932 $input_params{'hash_parent_base'} ||= $parentrefname;
933 } else {
934 $input_params{'hash_parent'} ||= $parentrefname;
938 # for the snapshot action, we allow URLs in the form
939 # $project/snapshot/$hash.ext
940 # where .ext determines the snapshot and gets removed from the
941 # passed $refname to provide the $hash.
943 # To be able to tell that $refname includes the format extension, we
944 # require the following two conditions to be satisfied:
945 # - the hash input parameter MUST have been set from the $refname part
946 # of the URL (i.e. they must be equal)
947 # - the snapshot format MUST NOT have been defined already (e.g. from
948 # CGI parameter sf)
949 # It's also useless to try any matching unless $refname has a dot,
950 # so we check for that too
951 if (defined $input_params{'action'} &&
952 $input_params{'action'} eq 'snapshot' &&
953 defined $refname && index($refname, '.') != -1 &&
954 $refname eq $input_params{'hash'} &&
955 !defined $input_params{'snapshot_format'}) {
956 # We loop over the known snapshot formats, checking for
957 # extensions. Allowed extensions are both the defined suffix
958 # (which includes the initial dot already) and the snapshot
959 # format key itself, with a prepended dot
960 while (my ($fmt, $opt) = each %known_snapshot_formats) {
961 my $hash = $refname;
962 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
963 next;
965 my $sfx = $1;
966 # a valid suffix was found, so set the snapshot format
967 # and reset the hash parameter
968 $input_params{'snapshot_format'} = $fmt;
969 $input_params{'hash'} = $hash;
970 # we also set the format suffix to the one requested
971 # in the URL: this way a request for e.g. .tgz returns
972 # a .tgz instead of a .tar.gz
973 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
974 last;
979 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
980 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
981 $searchtext, $search_regexp);
982 sub evaluate_and_validate_params {
983 our $action = $input_params{'action'};
984 if (defined $action) {
985 if (!validate_action($action)) {
986 die_error(400, "Invalid action parameter");
990 # parameters which are pathnames
991 our $project = $input_params{'project'};
992 if (defined $project) {
993 if (!validate_project($project)) {
994 undef $project;
995 die_error(404, "No such project");
999 our $file_name = $input_params{'file_name'};
1000 if (defined $file_name) {
1001 if (!validate_pathname($file_name)) {
1002 die_error(400, "Invalid file parameter");
1006 our $file_parent = $input_params{'file_parent'};
1007 if (defined $file_parent) {
1008 if (!validate_pathname($file_parent)) {
1009 die_error(400, "Invalid file parent parameter");
1013 # parameters which are refnames
1014 our $hash = $input_params{'hash'};
1015 if (defined $hash) {
1016 if (!validate_refname($hash)) {
1017 die_error(400, "Invalid hash parameter");
1021 our $hash_parent = $input_params{'hash_parent'};
1022 if (defined $hash_parent) {
1023 if (!validate_refname($hash_parent)) {
1024 die_error(400, "Invalid hash parent parameter");
1028 our $hash_base = $input_params{'hash_base'};
1029 if (defined $hash_base) {
1030 if (!validate_refname($hash_base)) {
1031 die_error(400, "Invalid hash base parameter");
1035 our @extra_options = @{$input_params{'extra_options'}};
1036 # @extra_options is always defined, since it can only be (currently) set from
1037 # CGI, and $cgi->param() returns the empty array in array context if the param
1038 # is not set
1039 foreach my $opt (@extra_options) {
1040 if (not exists $allowed_options{$opt}) {
1041 die_error(400, "Invalid option parameter");
1043 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1044 die_error(400, "Invalid option parameter for this action");
1048 our $hash_parent_base = $input_params{'hash_parent_base'};
1049 if (defined $hash_parent_base) {
1050 if (!validate_refname($hash_parent_base)) {
1051 die_error(400, "Invalid hash parent base parameter");
1055 # other parameters
1056 our $page = $input_params{'page'};
1057 if (defined $page) {
1058 if ($page =~ m/[^0-9]/) {
1059 die_error(400, "Invalid page parameter");
1063 our $searchtype = $input_params{'searchtype'};
1064 if (defined $searchtype) {
1065 if ($searchtype =~ m/[^a-z]/) {
1066 die_error(400, "Invalid searchtype parameter");
1070 our $search_use_regexp = $input_params{'search_use_regexp'};
1072 our $searchtext = $input_params{'searchtext'};
1073 our $search_regexp;
1074 if (defined $searchtext) {
1075 if (length($searchtext) < 2) {
1076 die_error(403, "At least two characters are required for search parameter");
1078 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1082 # path to the current git repository
1083 our $git_dir;
1084 sub evaluate_git_dir {
1085 our $git_dir = "$projectroot/$project" if $project;
1088 our (@snapshot_fmts, $git_avatar);
1089 sub configure_gitweb_features {
1090 # list of supported snapshot formats
1091 our @snapshot_fmts = gitweb_get_feature('snapshot');
1092 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1094 # check that the avatar feature is set to a known provider name,
1095 # and for each provider check if the dependencies are satisfied.
1096 # if the provider name is invalid or the dependencies are not met,
1097 # reset $git_avatar to the empty string.
1098 our ($git_avatar) = gitweb_get_feature('avatar');
1099 if ($git_avatar eq 'gravatar') {
1100 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1101 } elsif ($git_avatar eq 'picon') {
1102 # no dependencies
1103 } else {
1104 $git_avatar = '';
1108 # custom error handler: 'die <message>' is Internal Server Error
1109 sub handle_errors_html {
1110 my $msg = shift; # it is already HTML escaped
1112 # to avoid infinite loop where error occurs in die_error,
1113 # change handler to default handler, disabling handle_errors_html
1114 set_message("Error occured when inside die_error:\n$msg");
1116 # you cannot jump out of die_error when called as error handler;
1117 # the subroutine set via CGI::Carp::set_message is called _after_
1118 # HTTP headers are already written, so it cannot write them itself
1119 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1121 set_message(\&handle_errors_html);
1123 # dispatch
1124 sub dispatch {
1125 if (!defined $action) {
1126 if (defined $hash) {
1127 $action = git_get_type($hash);
1128 } elsif (defined $hash_base && defined $file_name) {
1129 $action = git_get_type("$hash_base:$file_name");
1130 } elsif (defined $project) {
1131 $action = 'summary';
1132 } else {
1133 $action = 'project_list';
1136 if (!defined($actions{$action})) {
1137 die_error(400, "Unknown action");
1139 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1140 !$project) {
1141 die_error(400, "Project needed");
1144 if ($caching_enabled) {
1145 # human readable key identifying gitweb output
1146 my $output_key = href(-replay => 1, -full => 1, -path_info => 0);
1148 cache_output($cache, $capture, $output_key, $actions{$action});
1149 } else {
1150 $actions{$action}->();
1154 sub reset_timer {
1155 our $t0 = [Time::HiRes::gettimeofday()]
1156 if defined $t0;
1157 our $number_of_git_cmds = 0;
1160 sub run_request {
1161 reset_timer();
1163 evaluate_uri();
1164 evaluate_gitweb_config();
1165 evaluate_git_version();
1166 check_loadavg();
1167 configure_caching()
1168 if ($caching_enabled);
1170 # $projectroot and $projects_list might be set in gitweb config file
1171 $projects_list ||= $projectroot;
1173 evaluate_query_params();
1174 evaluate_path_info();
1175 evaluate_and_validate_params();
1176 evaluate_git_dir();
1178 configure_gitweb_features();
1180 dispatch();
1183 our $is_last_request = sub { 1 };
1184 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1185 our $CGI = 'CGI';
1186 our $cgi;
1187 sub configure_as_fcgi {
1188 require CGI::Fast;
1189 our $CGI = 'CGI::Fast';
1191 my $request_number = 0;
1192 # let each child service 100 requests
1193 our $is_last_request = sub { ++$request_number > 100 };
1195 sub evaluate_argv {
1196 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1197 configure_as_fcgi()
1198 if $script_name =~ /\.fcgi$/;
1200 return unless (@ARGV);
1202 require Getopt::Long;
1203 Getopt::Long::GetOptions(
1204 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1205 'nproc|n=i' => sub {
1206 my ($arg, $val) = @_;
1207 return unless eval { require FCGI::ProcManager; 1; };
1208 my $proc_manager = FCGI::ProcManager->new({
1209 n_processes => $val,
1211 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1212 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1213 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1218 sub run {
1219 evaluate_argv();
1221 $pre_listen_hook->()
1222 if $pre_listen_hook;
1224 REQUEST:
1225 while ($cgi = $CGI->new()) {
1226 $pre_dispatch_hook->()
1227 if $pre_dispatch_hook;
1229 run_request();
1231 $post_dispatch_hook->()
1232 if $post_dispatch_hook;
1234 last REQUEST if ($is_last_request->());
1237 DONE_GITWEB:
1241 sub configure_caching {
1242 if (!eval { require GitwebCache::CacheOutput; 1; }) {
1243 # cache is configured _before_ handling request, so $cgi is not defined,
1244 # so we can't just "die" with sending error message to web browser
1245 #die_error(500, "Caching enabled and GitwebCache::CacheOutput not found");
1247 # turn off caching and warn instead
1248 $caching_enabled = 0;
1249 warn "Caching enabled and GitwebCache::CacheOutput not found";
1251 GitwebCache::CacheOutput->import();
1253 # $cache might be initialized (instantiated) cache, i.e. cache object,
1254 # or it might be name of class, or it might be undefined
1255 unless (defined $cache && ref($cache)) {
1256 $cache ||= 'GitwebCache::FileCacheWithLocking';
1257 eval "require $cache";
1258 die $@ if $@;
1259 $cache = $cache->new({
1260 %cache_options,
1261 #'cache_root' => '/tmp/cache',
1262 #'cache_depth' => 2,
1263 #'expires_in' => 20, # in seconds (CHI compatibile)
1264 # (Cache::Cache compatibile initialization)
1265 'default_expires_in' => $cache_options{'expires_in'},
1266 # (CHI compatibile initialization)
1267 'root_dir' => $cache_options{'cache_root'},
1268 'depth' => $cache_options{'cache_depth'},
1271 unless (defined $capture && ref($capture)) {
1272 require GitwebCache::Capture::Simple;
1273 $capture = GitwebCache::Capture::Simple->new();
1277 run();
1279 if (defined caller) {
1280 # wrapped in a subroutine processing requests,
1281 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1282 return;
1283 } else {
1284 # pure CGI script, serving single request
1285 exit;
1288 ## ======================================================================
1289 ## action links
1291 # possible values of extra options
1292 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1293 # -replay => 1 - start from a current view (replay with modifications)
1294 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1295 sub href {
1296 my %params = @_;
1297 # default is to use -absolute url() i.e. $my_uri
1298 my $href = $params{-full} ? $my_url : $my_uri;
1300 $params{'project'} = $project unless exists $params{'project'};
1302 if ($params{-replay}) {
1303 while (my ($name, $symbol) = each %cgi_param_mapping) {
1304 if (!exists $params{$name}) {
1305 $params{$name} = $input_params{$name};
1310 my $use_pathinfo = gitweb_check_feature('pathinfo');
1311 if (defined $params{'project'} &&
1312 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1313 # try to put as many parameters as possible in PATH_INFO:
1314 # - project name
1315 # - action
1316 # - hash_parent or hash_parent_base:/file_parent
1317 # - hash or hash_base:/filename
1318 # - the snapshot_format as an appropriate suffix
1320 # When the script is the root DirectoryIndex for the domain,
1321 # $href here would be something like http://gitweb.example.com/
1322 # Thus, we strip any trailing / from $href, to spare us double
1323 # slashes in the final URL
1324 $href =~ s,/$,,;
1326 # Then add the project name, if present
1327 $href .= "/".esc_url($params{'project'});
1328 delete $params{'project'};
1330 # since we destructively absorb parameters, we keep this
1331 # boolean that remembers if we're handling a snapshot
1332 my $is_snapshot = $params{'action'} eq 'snapshot';
1334 # Summary just uses the project path URL, any other action is
1335 # added to the URL
1336 if (defined $params{'action'}) {
1337 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1338 delete $params{'action'};
1341 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1342 # stripping nonexistent or useless pieces
1343 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1344 || $params{'hash_parent'} || $params{'hash'});
1345 if (defined $params{'hash_base'}) {
1346 if (defined $params{'hash_parent_base'}) {
1347 $href .= esc_url($params{'hash_parent_base'});
1348 # skip the file_parent if it's the same as the file_name
1349 if (defined $params{'file_parent'}) {
1350 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1351 delete $params{'file_parent'};
1352 } elsif ($params{'file_parent'} !~ /\.\./) {
1353 $href .= ":/".esc_url($params{'file_parent'});
1354 delete $params{'file_parent'};
1357 $href .= "..";
1358 delete $params{'hash_parent'};
1359 delete $params{'hash_parent_base'};
1360 } elsif (defined $params{'hash_parent'}) {
1361 $href .= esc_url($params{'hash_parent'}). "..";
1362 delete $params{'hash_parent'};
1365 $href .= esc_url($params{'hash_base'});
1366 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1367 $href .= ":/".esc_url($params{'file_name'});
1368 delete $params{'file_name'};
1370 delete $params{'hash'};
1371 delete $params{'hash_base'};
1372 } elsif (defined $params{'hash'}) {
1373 $href .= esc_url($params{'hash'});
1374 delete $params{'hash'};
1377 # If the action was a snapshot, we can absorb the
1378 # snapshot_format parameter too
1379 if ($is_snapshot) {
1380 my $fmt = $params{'snapshot_format'};
1381 # snapshot_format should always be defined when href()
1382 # is called, but just in case some code forgets, we
1383 # fall back to the default
1384 $fmt ||= $snapshot_fmts[0];
1385 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1386 delete $params{'snapshot_format'};
1390 # now encode the parameters explicitly
1391 my @result = ();
1392 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1393 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1394 if (defined $params{$name}) {
1395 if (ref($params{$name}) eq "ARRAY") {
1396 foreach my $par (@{$params{$name}}) {
1397 push @result, $symbol . "=" . esc_param($par);
1399 } else {
1400 push @result, $symbol . "=" . esc_param($params{$name});
1404 $href .= "?" . join(';', @result) if scalar @result;
1406 return $href;
1410 ## ======================================================================
1411 ## validation, quoting/unquoting and escaping
1413 sub validate_action {
1414 my $input = shift || return undef;
1415 return undef unless exists $actions{$input};
1416 return $input;
1419 sub validate_project {
1420 my $input = shift || return undef;
1421 if (!validate_pathname($input) ||
1422 !(-d "$projectroot/$input") ||
1423 !check_export_ok("$projectroot/$input") ||
1424 ($strict_export && !project_in_list($input))) {
1425 return undef;
1426 } else {
1427 return $input;
1431 sub validate_pathname {
1432 my $input = shift || return undef;
1434 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1435 # at the beginning, at the end, and between slashes.
1436 # also this catches doubled slashes
1437 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1438 return undef;
1440 # no null characters
1441 if ($input =~ m!\0!) {
1442 return undef;
1444 return $input;
1447 sub validate_refname {
1448 my $input = shift || return undef;
1450 # textual hashes are O.K.
1451 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1452 return $input;
1454 # it must be correct pathname
1455 $input = validate_pathname($input)
1456 or return undef;
1457 # restrictions on ref name according to git-check-ref-format
1458 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1459 return undef;
1461 return $input;
1464 # decode sequences of octets in utf8 into Perl's internal form,
1465 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1466 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1467 sub to_utf8 {
1468 my $str = shift;
1469 return undef unless defined $str;
1470 if (utf8::valid($str)) {
1471 utf8::decode($str);
1472 return $str;
1473 } else {
1474 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1478 # quote unsafe chars, but keep the slash, even when it's not
1479 # correct, but quoted slashes look too horrible in bookmarks
1480 sub esc_param {
1481 my $str = shift;
1482 return undef unless defined $str;
1483 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1484 $str =~ s/ /\+/g;
1485 return $str;
1488 # quote unsafe chars in whole URL, so some characters cannot be quoted
1489 sub esc_url {
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 # replace invalid utf8 character with SUBSTITUTION sequence
1498 sub esc_html {
1499 my $str = shift;
1500 my %opts = @_;
1502 return undef unless defined $str;
1504 $str = to_utf8($str);
1505 $str = $cgi->escapeHTML($str);
1506 if ($opts{'-nbsp'}) {
1507 $str =~ s/ /&nbsp;/g;
1509 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1510 return $str;
1513 # quote control characters and escape filename to HTML
1514 sub esc_path {
1515 my $str = shift;
1516 my %opts = @_;
1518 return undef unless defined $str;
1520 $str = to_utf8($str);
1521 $str = $cgi->escapeHTML($str);
1522 if ($opts{'-nbsp'}) {
1523 $str =~ s/ /&nbsp;/g;
1525 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1526 return $str;
1529 # Make control characters "printable", using character escape codes (CEC)
1530 sub quot_cec {
1531 my $cntrl = shift;
1532 my %opts = @_;
1533 my %es = ( # character escape codes, aka escape sequences
1534 "\t" => '\t', # tab (HT)
1535 "\n" => '\n', # line feed (LF)
1536 "\r" => '\r', # carrige return (CR)
1537 "\f" => '\f', # form feed (FF)
1538 "\b" => '\b', # backspace (BS)
1539 "\a" => '\a', # alarm (bell) (BEL)
1540 "\e" => '\e', # escape (ESC)
1541 "\013" => '\v', # vertical tab (VT)
1542 "\000" => '\0', # nul character (NUL)
1544 my $chr = ( (exists $es{$cntrl})
1545 ? $es{$cntrl}
1546 : sprintf('\%2x', ord($cntrl)) );
1547 if ($opts{-nohtml}) {
1548 return $chr;
1549 } else {
1550 return "<span class=\"cntrl\">$chr</span>";
1554 # Alternatively use unicode control pictures codepoints,
1555 # Unicode "printable representation" (PR)
1556 sub quot_upr {
1557 my $cntrl = shift;
1558 my %opts = @_;
1560 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1561 if ($opts{-nohtml}) {
1562 return $chr;
1563 } else {
1564 return "<span class=\"cntrl\">$chr</span>";
1568 # git may return quoted and escaped filenames
1569 sub unquote {
1570 my $str = shift;
1572 sub unq {
1573 my $seq = shift;
1574 my %es = ( # character escape codes, aka escape sequences
1575 't' => "\t", # tab (HT, TAB)
1576 'n' => "\n", # newline (NL)
1577 'r' => "\r", # return (CR)
1578 'f' => "\f", # form feed (FF)
1579 'b' => "\b", # backspace (BS)
1580 'a' => "\a", # alarm (bell) (BEL)
1581 'e' => "\e", # escape (ESC)
1582 'v' => "\013", # vertical tab (VT)
1585 if ($seq =~ m/^[0-7]{1,3}$/) {
1586 # octal char sequence
1587 return chr(oct($seq));
1588 } elsif (exists $es{$seq}) {
1589 # C escape sequence, aka character escape code
1590 return $es{$seq};
1592 # quoted ordinary character
1593 return $seq;
1596 if ($str =~ m/^"(.*)"$/) {
1597 # needs unquoting
1598 $str = $1;
1599 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1601 return $str;
1604 # escape tabs (convert tabs to spaces)
1605 sub untabify {
1606 my $line = shift;
1608 while ((my $pos = index($line, "\t")) != -1) {
1609 if (my $count = (8 - ($pos % 8))) {
1610 my $spaces = ' ' x $count;
1611 $line =~ s/\t/$spaces/;
1615 return $line;
1618 sub project_in_list {
1619 my $project = shift;
1620 my @list = git_get_projects_list();
1621 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1624 ## ----------------------------------------------------------------------
1625 ## HTML aware string manipulation
1627 # Try to chop given string on a word boundary between position
1628 # $len and $len+$add_len. If there is no word boundary there,
1629 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1630 # (marking chopped part) would be longer than given string.
1631 sub chop_str {
1632 my $str = shift;
1633 my $len = shift;
1634 my $add_len = shift || 10;
1635 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1637 # Make sure perl knows it is utf8 encoded so we don't
1638 # cut in the middle of a utf8 multibyte char.
1639 $str = to_utf8($str);
1641 # allow only $len chars, but don't cut a word if it would fit in $add_len
1642 # if it doesn't fit, cut it if it's still longer than the dots we would add
1643 # remove chopped character entities entirely
1645 # when chopping in the middle, distribute $len into left and right part
1646 # return early if chopping wouldn't make string shorter
1647 if ($where eq 'center') {
1648 return $str if ($len + 5 >= length($str)); # filler is length 5
1649 $len = int($len/2);
1650 } else {
1651 return $str if ($len + 4 >= length($str)); # filler is length 4
1654 # regexps: ending and beginning with word part up to $add_len
1655 my $endre = qr/.{$len}\w{0,$add_len}/;
1656 my $begre = qr/\w{0,$add_len}.{$len}/;
1658 if ($where eq 'left') {
1659 $str =~ m/^(.*?)($begre)$/;
1660 my ($lead, $body) = ($1, $2);
1661 if (length($lead) > 4) {
1662 $lead = " ...";
1664 return "$lead$body";
1666 } elsif ($where eq 'center') {
1667 $str =~ m/^($endre)(.*)$/;
1668 my ($left, $str) = ($1, $2);
1669 $str =~ m/^(.*?)($begre)$/;
1670 my ($mid, $right) = ($1, $2);
1671 if (length($mid) > 5) {
1672 $mid = " ... ";
1674 return "$left$mid$right";
1676 } else {
1677 $str =~ m/^($endre)(.*)$/;
1678 my $body = $1;
1679 my $tail = $2;
1680 if (length($tail) > 4) {
1681 $tail = "... ";
1683 return "$body$tail";
1687 # takes the same arguments as chop_str, but also wraps a <span> around the
1688 # result with a title attribute if it does get chopped. Additionally, the
1689 # string is HTML-escaped.
1690 sub chop_and_escape_str {
1691 my ($str) = @_;
1693 my $chopped = chop_str(@_);
1694 if ($chopped eq $str) {
1695 return esc_html($chopped);
1696 } else {
1697 $str =~ s/[[:cntrl:]]/?/g;
1698 return $cgi->span({-title=>$str}, esc_html($chopped));
1702 ## ----------------------------------------------------------------------
1703 ## functions returning short strings
1705 # CSS class for given age value (in seconds)
1706 sub age_class {
1707 my $age = shift;
1709 if (!defined $age) {
1710 return "noage";
1711 } elsif ($age < 60*60*2) {
1712 return "age0";
1713 } elsif ($age < 60*60*24*2) {
1714 return "age1";
1715 } else {
1716 return "age2";
1720 # convert age in seconds to "nn units ago" string
1721 sub age_string {
1722 my $age = shift;
1723 my $age_str;
1725 if ($age > 60*60*24*365*2) {
1726 $age_str = (int $age/60/60/24/365);
1727 $age_str .= " years ago";
1728 } elsif ($age > 60*60*24*(365/12)*2) {
1729 $age_str = int $age/60/60/24/(365/12);
1730 $age_str .= " months ago";
1731 } elsif ($age > 60*60*24*7*2) {
1732 $age_str = int $age/60/60/24/7;
1733 $age_str .= " weeks ago";
1734 } elsif ($age > 60*60*24*2) {
1735 $age_str = int $age/60/60/24;
1736 $age_str .= " days ago";
1737 } elsif ($age > 60*60*2) {
1738 $age_str = int $age/60/60;
1739 $age_str .= " hours ago";
1740 } elsif ($age > 60*2) {
1741 $age_str = int $age/60;
1742 $age_str .= " min ago";
1743 } elsif ($age > 2) {
1744 $age_str = int $age;
1745 $age_str .= " sec ago";
1746 } else {
1747 $age_str .= " right now";
1749 return $age_str;
1752 use constant {
1753 S_IFINVALID => 0030000,
1754 S_IFGITLINK => 0160000,
1757 # submodule/subproject, a commit object reference
1758 sub S_ISGITLINK {
1759 my $mode = shift;
1761 return (($mode & S_IFMT) == S_IFGITLINK)
1764 # convert file mode in octal to symbolic file mode string
1765 sub mode_str {
1766 my $mode = oct shift;
1768 if (S_ISGITLINK($mode)) {
1769 return 'm---------';
1770 } elsif (S_ISDIR($mode & S_IFMT)) {
1771 return 'drwxr-xr-x';
1772 } elsif (S_ISLNK($mode)) {
1773 return 'lrwxrwxrwx';
1774 } elsif (S_ISREG($mode)) {
1775 # git cares only about the executable bit
1776 if ($mode & S_IXUSR) {
1777 return '-rwxr-xr-x';
1778 } else {
1779 return '-rw-r--r--';
1781 } else {
1782 return '----------';
1786 # convert file mode in octal to file type string
1787 sub file_type {
1788 my $mode = shift;
1790 if ($mode !~ m/^[0-7]+$/) {
1791 return $mode;
1792 } else {
1793 $mode = oct $mode;
1796 if (S_ISGITLINK($mode)) {
1797 return "submodule";
1798 } elsif (S_ISDIR($mode & S_IFMT)) {
1799 return "directory";
1800 } elsif (S_ISLNK($mode)) {
1801 return "symlink";
1802 } elsif (S_ISREG($mode)) {
1803 return "file";
1804 } else {
1805 return "unknown";
1809 # convert file mode in octal to file type description string
1810 sub file_type_long {
1811 my $mode = shift;
1813 if ($mode !~ m/^[0-7]+$/) {
1814 return $mode;
1815 } else {
1816 $mode = oct $mode;
1819 if (S_ISGITLINK($mode)) {
1820 return "submodule";
1821 } elsif (S_ISDIR($mode & S_IFMT)) {
1822 return "directory";
1823 } elsif (S_ISLNK($mode)) {
1824 return "symlink";
1825 } elsif (S_ISREG($mode)) {
1826 if ($mode & S_IXUSR) {
1827 return "executable";
1828 } else {
1829 return "file";
1831 } else {
1832 return "unknown";
1837 ## ----------------------------------------------------------------------
1838 ## functions returning short HTML fragments, or transforming HTML fragments
1839 ## which don't belong to other sections
1841 # format line of commit message.
1842 sub format_log_line_html {
1843 my $line = shift;
1845 $line = esc_html($line, -nbsp=>1);
1846 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1847 $cgi->a({-href => href(action=>"object", hash=>$1),
1848 -class => "text"}, $1);
1849 }eg;
1851 return $line;
1854 # format marker of refs pointing to given object
1856 # the destination action is chosen based on object type and current context:
1857 # - for annotated tags, we choose the tag view unless it's the current view
1858 # already, in which case we go to shortlog view
1859 # - for other refs, we keep the current view if we're in history, shortlog or
1860 # log view, and select shortlog otherwise
1861 sub format_ref_marker {
1862 my ($refs, $id) = @_;
1863 my $markers = '';
1865 if (defined $refs->{$id}) {
1866 foreach my $ref (@{$refs->{$id}}) {
1867 # this code exploits the fact that non-lightweight tags are the
1868 # only indirect objects, and that they are the only objects for which
1869 # we want to use tag instead of shortlog as action
1870 my ($type, $name) = qw();
1871 my $indirect = ($ref =~ s/\^\{\}$//);
1872 # e.g. tags/v2.6.11 or heads/next
1873 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1874 $type = $1;
1875 $name = $2;
1876 } else {
1877 $type = "ref";
1878 $name = $ref;
1881 my $class = $type;
1882 $class .= " indirect" if $indirect;
1884 my $dest_action = "shortlog";
1886 if ($indirect) {
1887 $dest_action = "tag" unless $action eq "tag";
1888 } elsif ($action =~ /^(history|(short)?log)$/) {
1889 $dest_action = $action;
1892 my $dest = "";
1893 $dest .= "refs/" unless $ref =~ m!^refs/!;
1894 $dest .= $ref;
1896 my $link = $cgi->a({
1897 -href => href(
1898 action=>$dest_action,
1899 hash=>$dest
1900 )}, $name);
1902 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1903 $link . "</span>";
1907 if ($markers) {
1908 return ' <span class="refs">'. $markers . '</span>';
1909 } else {
1910 return "";
1914 # format, perhaps shortened and with markers, title line
1915 sub format_subject_html {
1916 my ($long, $short, $href, $extra) = @_;
1917 $extra = '' unless defined($extra);
1919 if (length($short) < length($long)) {
1920 $long =~ s/[[:cntrl:]]/?/g;
1921 return $cgi->a({-href => $href, -class => "list subject",
1922 -title => to_utf8($long)},
1923 esc_html($short)) . $extra;
1924 } else {
1925 return $cgi->a({-href => $href, -class => "list subject"},
1926 esc_html($long)) . $extra;
1930 # Rather than recomputing the url for an email multiple times, we cache it
1931 # after the first hit. This gives a visible benefit in views where the avatar
1932 # for the same email is used repeatedly (e.g. shortlog).
1933 # The cache is shared by all avatar engines (currently gravatar only), which
1934 # are free to use it as preferred. Since only one avatar engine is used for any
1935 # given page, there's no risk for cache conflicts.
1936 our %avatar_cache = ();
1938 # Compute the picon url for a given email, by using the picon search service over at
1939 # http://www.cs.indiana.edu/picons/search.html
1940 sub picon_url {
1941 my $email = lc shift;
1942 if (!$avatar_cache{$email}) {
1943 my ($user, $domain) = split('@', $email);
1944 $avatar_cache{$email} =
1945 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1946 "$domain/$user/" .
1947 "users+domains+unknown/up/single";
1949 return $avatar_cache{$email};
1952 # Compute the gravatar url for a given email, if it's not in the cache already.
1953 # Gravatar stores only the part of the URL before the size, since that's the
1954 # one computationally more expensive. This also allows reuse of the cache for
1955 # different sizes (for this particular engine).
1956 sub gravatar_url {
1957 my $email = lc shift;
1958 my $size = shift;
1959 $avatar_cache{$email} ||=
1960 "http://www.gravatar.com/avatar/" .
1961 Digest::MD5::md5_hex($email) . "?s=";
1962 return $avatar_cache{$email} . $size;
1965 # Insert an avatar for the given $email at the given $size if the feature
1966 # is enabled.
1967 sub git_get_avatar {
1968 my ($email, %opts) = @_;
1969 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1970 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1971 $opts{-size} ||= 'default';
1972 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1973 my $url = "";
1974 if ($git_avatar eq 'gravatar') {
1975 $url = gravatar_url($email, $size);
1976 } elsif ($git_avatar eq 'picon') {
1977 $url = picon_url($email);
1979 # Other providers can be added by extending the if chain, defining $url
1980 # as needed. If no variant puts something in $url, we assume avatars
1981 # are completely disabled/unavailable.
1982 if ($url) {
1983 return $pre_white .
1984 "<img width=\"$size\" " .
1985 "class=\"avatar\" " .
1986 "src=\"$url\" " .
1987 "alt=\"\" " .
1988 "/>" . $post_white;
1989 } else {
1990 return "";
1994 sub format_search_author {
1995 my ($author, $searchtype, $displaytext) = @_;
1996 my $have_search = gitweb_check_feature('search');
1998 if ($have_search) {
1999 my $performed = "";
2000 if ($searchtype eq 'author') {
2001 $performed = "authored";
2002 } elsif ($searchtype eq 'committer') {
2003 $performed = "committed";
2006 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2007 searchtext=>$author,
2008 searchtype=>$searchtype), class=>"list",
2009 title=>"Search for commits $performed by $author"},
2010 $displaytext);
2012 } else {
2013 return $displaytext;
2017 # format the author name of the given commit with the given tag
2018 # the author name is chopped and escaped according to the other
2019 # optional parameters (see chop_str).
2020 sub format_author_html {
2021 my $tag = shift;
2022 my $co = shift;
2023 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2024 return "<$tag class=\"author\">" .
2025 format_search_author($co->{'author_name'}, "author",
2026 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2027 $author) .
2028 "</$tag>";
2031 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2032 sub format_git_diff_header_line {
2033 my $line = shift;
2034 my $diffinfo = shift;
2035 my ($from, $to) = @_;
2037 if ($diffinfo->{'nparents'}) {
2038 # combined diff
2039 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2040 if ($to->{'href'}) {
2041 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2042 esc_path($to->{'file'}));
2043 } else { # file was deleted (no href)
2044 $line .= esc_path($to->{'file'});
2046 } else {
2047 # "ordinary" diff
2048 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2049 if ($from->{'href'}) {
2050 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2051 'a/' . esc_path($from->{'file'}));
2052 } else { # file was added (no href)
2053 $line .= 'a/' . esc_path($from->{'file'});
2055 $line .= ' ';
2056 if ($to->{'href'}) {
2057 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2058 'b/' . esc_path($to->{'file'}));
2059 } else { # file was deleted
2060 $line .= 'b/' . esc_path($to->{'file'});
2064 return "<div class=\"diff header\">$line</div>\n";
2067 # format extended diff header line, before patch itself
2068 sub format_extended_diff_header_line {
2069 my $line = shift;
2070 my $diffinfo = shift;
2071 my ($from, $to) = @_;
2073 # match <path>
2074 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2075 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2076 esc_path($from->{'file'}));
2078 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2079 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2080 esc_path($to->{'file'}));
2082 # match single <mode>
2083 if ($line =~ m/\s(\d{6})$/) {
2084 $line .= '<span class="info"> (' .
2085 file_type_long($1) .
2086 ')</span>';
2088 # match <hash>
2089 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2090 # can match only for combined diff
2091 $line = 'index ';
2092 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2093 if ($from->{'href'}[$i]) {
2094 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2095 -class=>"hash"},
2096 substr($diffinfo->{'from_id'}[$i],0,7));
2097 } else {
2098 $line .= '0' x 7;
2100 # separator
2101 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2103 $line .= '..';
2104 if ($to->{'href'}) {
2105 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2106 substr($diffinfo->{'to_id'},0,7));
2107 } else {
2108 $line .= '0' x 7;
2111 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2112 # can match only for ordinary diff
2113 my ($from_link, $to_link);
2114 if ($from->{'href'}) {
2115 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2116 substr($diffinfo->{'from_id'},0,7));
2117 } else {
2118 $from_link = '0' x 7;
2120 if ($to->{'href'}) {
2121 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2122 substr($diffinfo->{'to_id'},0,7));
2123 } else {
2124 $to_link = '0' x 7;
2126 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2127 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2130 return $line . "<br/>\n";
2133 # format from-file/to-file diff header
2134 sub format_diff_from_to_header {
2135 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2136 my $line;
2137 my $result = '';
2139 $line = $from_line;
2140 #assert($line =~ m/^---/) if DEBUG;
2141 # no extra formatting for "^--- /dev/null"
2142 if (! $diffinfo->{'nparents'}) {
2143 # ordinary (single parent) diff
2144 if ($line =~ m!^--- "?a/!) {
2145 if ($from->{'href'}) {
2146 $line = '--- a/' .
2147 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2148 esc_path($from->{'file'}));
2149 } else {
2150 $line = '--- a/' .
2151 esc_path($from->{'file'});
2154 $result .= qq!<div class="diff from_file">$line</div>\n!;
2156 } else {
2157 # combined diff (merge commit)
2158 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2159 if ($from->{'href'}[$i]) {
2160 $line = '--- ' .
2161 $cgi->a({-href=>href(action=>"blobdiff",
2162 hash_parent=>$diffinfo->{'from_id'}[$i],
2163 hash_parent_base=>$parents[$i],
2164 file_parent=>$from->{'file'}[$i],
2165 hash=>$diffinfo->{'to_id'},
2166 hash_base=>$hash,
2167 file_name=>$to->{'file'}),
2168 -class=>"path",
2169 -title=>"diff" . ($i+1)},
2170 $i+1) .
2171 '/' .
2172 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2173 esc_path($from->{'file'}[$i]));
2174 } else {
2175 $line = '--- /dev/null';
2177 $result .= qq!<div class="diff from_file">$line</div>\n!;
2181 $line = $to_line;
2182 #assert($line =~ m/^\+\+\+/) if DEBUG;
2183 # no extra formatting for "^+++ /dev/null"
2184 if ($line =~ m!^\+\+\+ "?b/!) {
2185 if ($to->{'href'}) {
2186 $line = '+++ b/' .
2187 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2188 esc_path($to->{'file'}));
2189 } else {
2190 $line = '+++ b/' .
2191 esc_path($to->{'file'});
2194 $result .= qq!<div class="diff to_file">$line</div>\n!;
2196 return $result;
2199 # create note for patch simplified by combined diff
2200 sub format_diff_cc_simplified {
2201 my ($diffinfo, @parents) = @_;
2202 my $result = '';
2204 $result .= "<div class=\"diff header\">" .
2205 "diff --cc ";
2206 if (!is_deleted($diffinfo)) {
2207 $result .= $cgi->a({-href => href(action=>"blob",
2208 hash_base=>$hash,
2209 hash=>$diffinfo->{'to_id'},
2210 file_name=>$diffinfo->{'to_file'}),
2211 -class => "path"},
2212 esc_path($diffinfo->{'to_file'}));
2213 } else {
2214 $result .= esc_path($diffinfo->{'to_file'});
2216 $result .= "</div>\n" . # class="diff header"
2217 "<div class=\"diff nodifferences\">" .
2218 "Simple merge" .
2219 "</div>\n"; # class="diff nodifferences"
2221 return $result;
2224 # format patch (diff) line (not to be used for diff headers)
2225 sub format_diff_line {
2226 my $line = shift;
2227 my ($from, $to) = @_;
2228 my $diff_class = "";
2230 chomp $line;
2232 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2233 # combined diff
2234 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2235 if ($line =~ m/^\@{3}/) {
2236 $diff_class = " chunk_header";
2237 } elsif ($line =~ m/^\\/) {
2238 $diff_class = " incomplete";
2239 } elsif ($prefix =~ tr/+/+/) {
2240 $diff_class = " add";
2241 } elsif ($prefix =~ tr/-/-/) {
2242 $diff_class = " rem";
2244 } else {
2245 # assume ordinary diff
2246 my $char = substr($line, 0, 1);
2247 if ($char eq '+') {
2248 $diff_class = " add";
2249 } elsif ($char eq '-') {
2250 $diff_class = " rem";
2251 } elsif ($char eq '@') {
2252 $diff_class = " chunk_header";
2253 } elsif ($char eq "\\") {
2254 $diff_class = " incomplete";
2257 $line = untabify($line);
2258 if ($from && $to && $line =~ m/^\@{2} /) {
2259 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2260 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2262 $from_lines = 0 unless defined $from_lines;
2263 $to_lines = 0 unless defined $to_lines;
2265 if ($from->{'href'}) {
2266 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2267 -class=>"list"}, $from_text);
2269 if ($to->{'href'}) {
2270 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2271 -class=>"list"}, $to_text);
2273 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2274 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2275 return "<div class=\"diff$diff_class\">$line</div>\n";
2276 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2277 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2278 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2280 @from_text = split(' ', $ranges);
2281 for (my $i = 0; $i < @from_text; ++$i) {
2282 ($from_start[$i], $from_nlines[$i]) =
2283 (split(',', substr($from_text[$i], 1)), 0);
2286 $to_text = pop @from_text;
2287 $to_start = pop @from_start;
2288 $to_nlines = pop @from_nlines;
2290 $line = "<span class=\"chunk_info\">$prefix ";
2291 for (my $i = 0; $i < @from_text; ++$i) {
2292 if ($from->{'href'}[$i]) {
2293 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2294 -class=>"list"}, $from_text[$i]);
2295 } else {
2296 $line .= $from_text[$i];
2298 $line .= " ";
2300 if ($to->{'href'}) {
2301 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2302 -class=>"list"}, $to_text);
2303 } else {
2304 $line .= $to_text;
2306 $line .= " $prefix</span>" .
2307 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2308 return "<div class=\"diff$diff_class\">$line</div>\n";
2310 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2313 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2314 # linked. Pass the hash of the tree/commit to snapshot.
2315 sub format_snapshot_links {
2316 my ($hash) = @_;
2317 my $num_fmts = @snapshot_fmts;
2318 if ($num_fmts > 1) {
2319 # A parenthesized list of links bearing format names.
2320 # e.g. "snapshot (_tar.gz_ _zip_)"
2321 return "snapshot (" . join(' ', map
2322 $cgi->a({
2323 -href => href(
2324 action=>"snapshot",
2325 hash=>$hash,
2326 snapshot_format=>$_
2328 }, $known_snapshot_formats{$_}{'display'})
2329 , @snapshot_fmts) . ")";
2330 } elsif ($num_fmts == 1) {
2331 # A single "snapshot" link whose tooltip bears the format name.
2332 # i.e. "_snapshot_"
2333 my ($fmt) = @snapshot_fmts;
2334 return
2335 $cgi->a({
2336 -href => href(
2337 action=>"snapshot",
2338 hash=>$hash,
2339 snapshot_format=>$fmt
2341 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2342 }, "snapshot");
2343 } else { # $num_fmts == 0
2344 return undef;
2348 ## ......................................................................
2349 ## functions returning values to be passed, perhaps after some
2350 ## transformation, to other functions; e.g. returning arguments to href()
2352 # returns hash to be passed to href to generate gitweb URL
2353 # in -title key it returns description of link
2354 sub get_feed_info {
2355 my $format = shift || 'Atom';
2356 my %res = (action => lc($format));
2358 # feed links are possible only for project views
2359 return unless (defined $project);
2360 # some views should link to OPML, or to generic project feed,
2361 # or don't have specific feed yet (so they should use generic)
2362 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2364 my $branch;
2365 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2366 # from tag links; this also makes possible to detect branch links
2367 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2368 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2369 $branch = $1;
2371 # find log type for feed description (title)
2372 my $type = 'log';
2373 if (defined $file_name) {
2374 $type = "history of $file_name";
2375 $type .= "/" if ($action eq 'tree');
2376 $type .= " on '$branch'" if (defined $branch);
2377 } else {
2378 $type = "log of $branch" if (defined $branch);
2381 $res{-title} = $type;
2382 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2383 $res{'file_name'} = $file_name;
2385 return %res;
2388 ## ----------------------------------------------------------------------
2389 ## git utility subroutines, invoking git commands
2391 # returns path to the core git executable and the --git-dir parameter as list
2392 sub git_cmd {
2393 $number_of_git_cmds++;
2394 return $GIT, '--git-dir='.$git_dir;
2397 # quote the given arguments for passing them to the shell
2398 # quote_command("command", "arg 1", "arg with ' and ! characters")
2399 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2400 # Try to avoid using this function wherever possible.
2401 sub quote_command {
2402 return join(' ',
2403 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2406 # get HEAD ref of given project as hash
2407 sub git_get_head_hash {
2408 return git_get_full_hash(shift, 'HEAD');
2411 sub git_get_full_hash {
2412 return git_get_hash(@_);
2415 sub git_get_short_hash {
2416 return git_get_hash(@_, '--short=7');
2419 sub git_get_hash {
2420 my ($project, $hash, @options) = @_;
2421 my $o_git_dir = $git_dir;
2422 my $retval = undef;
2423 $git_dir = "$projectroot/$project";
2424 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2425 '--verify', '-q', @options, $hash) {
2426 $retval = <$fd>;
2427 chomp $retval if defined $retval;
2428 close $fd;
2430 if (defined $o_git_dir) {
2431 $git_dir = $o_git_dir;
2433 return $retval;
2436 # get type of given object
2437 sub git_get_type {
2438 my $hash = shift;
2440 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2441 my $type = <$fd>;
2442 close $fd or return;
2443 chomp $type;
2444 return $type;
2447 # repository configuration
2448 our $config_file = '';
2449 our %config;
2451 # store multiple values for single key as anonymous array reference
2452 # single values stored directly in the hash, not as [ <value> ]
2453 sub hash_set_multi {
2454 my ($hash, $key, $value) = @_;
2456 if (!exists $hash->{$key}) {
2457 $hash->{$key} = $value;
2458 } elsif (!ref $hash->{$key}) {
2459 $hash->{$key} = [ $hash->{$key}, $value ];
2460 } else {
2461 push @{$hash->{$key}}, $value;
2465 # return hash of git project configuration
2466 # optionally limited to some section, e.g. 'gitweb'
2467 sub git_parse_project_config {
2468 my $section_regexp = shift;
2469 my %config;
2471 local $/ = "\0";
2473 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2474 or return;
2476 while (my $keyval = <$fh>) {
2477 chomp $keyval;
2478 my ($key, $value) = split(/\n/, $keyval, 2);
2480 hash_set_multi(\%config, $key, $value)
2481 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2483 close $fh;
2485 return %config;
2488 # convert config value to boolean: 'true' or 'false'
2489 # no value, number > 0, 'true' and 'yes' values are true
2490 # rest of values are treated as false (never as error)
2491 sub config_to_bool {
2492 my $val = shift;
2494 return 1 if !defined $val; # section.key
2496 # strip leading and trailing whitespace
2497 $val =~ s/^\s+//;
2498 $val =~ s/\s+$//;
2500 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2501 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2504 # convert config value to simple decimal number
2505 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2506 # to be multiplied by 1024, 1048576, or 1073741824
2507 sub config_to_int {
2508 my $val = shift;
2510 # strip leading and trailing whitespace
2511 $val =~ s/^\s+//;
2512 $val =~ s/\s+$//;
2514 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2515 $unit = lc($unit);
2516 # unknown unit is treated as 1
2517 return $num * ($unit eq 'g' ? 1073741824 :
2518 $unit eq 'm' ? 1048576 :
2519 $unit eq 'k' ? 1024 : 1);
2521 return $val;
2524 # convert config value to array reference, if needed
2525 sub config_to_multi {
2526 my $val = shift;
2528 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2531 sub git_get_project_config {
2532 my ($key, $type) = @_;
2534 return unless defined $git_dir;
2536 # key sanity check
2537 return unless ($key);
2538 $key =~ s/^gitweb\.//;
2539 return if ($key =~ m/\W/);
2541 # type sanity check
2542 if (defined $type) {
2543 $type =~ s/^--//;
2544 $type = undef
2545 unless ($type eq 'bool' || $type eq 'int');
2548 # get config
2549 if (!defined $config_file ||
2550 $config_file ne "$git_dir/config") {
2551 %config = git_parse_project_config('gitweb');
2552 $config_file = "$git_dir/config";
2555 # check if config variable (key) exists
2556 return unless exists $config{"gitweb.$key"};
2558 # ensure given type
2559 if (!defined $type) {
2560 return $config{"gitweb.$key"};
2561 } elsif ($type eq 'bool') {
2562 # backward compatibility: 'git config --bool' returns true/false
2563 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2564 } elsif ($type eq 'int') {
2565 return config_to_int($config{"gitweb.$key"});
2567 return $config{"gitweb.$key"};
2570 # get hash of given path at given ref
2571 sub git_get_hash_by_path {
2572 my $base = shift;
2573 my $path = shift || return undef;
2574 my $type = shift;
2576 $path =~ s,/+$,,;
2578 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2579 or die_error(500, "Open git-ls-tree failed");
2580 my $line = <$fd>;
2581 close $fd or return undef;
2583 if (!defined $line) {
2584 # there is no tree or hash given by $path at $base
2585 return undef;
2588 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2589 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2590 if (defined $type && $type ne $2) {
2591 # type doesn't match
2592 return undef;
2594 return $3;
2597 # get path of entry with given hash at given tree-ish (ref)
2598 # used to get 'from' filename for combined diff (merge commit) for renames
2599 sub git_get_path_by_hash {
2600 my $base = shift || return;
2601 my $hash = shift || return;
2603 local $/ = "\0";
2605 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2606 or return undef;
2607 while (my $line = <$fd>) {
2608 chomp $line;
2610 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2611 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2612 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2613 close $fd;
2614 return $1;
2617 close $fd;
2618 return undef;
2621 ## ......................................................................
2622 ## git utility functions, directly accessing git repository
2624 sub git_get_project_description {
2625 my $path = shift;
2627 $git_dir = "$projectroot/$path";
2628 open my $fd, '<', "$git_dir/description"
2629 or return git_get_project_config('description');
2630 my $descr = <$fd>;
2631 close $fd;
2632 if (defined $descr) {
2633 chomp $descr;
2635 return $descr;
2638 sub git_get_project_ctags {
2639 my $path = shift;
2640 my $ctags = {};
2642 $git_dir = "$projectroot/$path";
2643 opendir my $dh, "$git_dir/ctags"
2644 or return $ctags;
2645 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2646 open my $ct, '<', $_ or next;
2647 my $val = <$ct>;
2648 chomp $val;
2649 close $ct;
2650 my $ctag = $_; $ctag =~ s#.*/##;
2651 $ctags->{$ctag} = $val;
2653 closedir $dh;
2654 $ctags;
2657 sub git_populate_project_tagcloud {
2658 my $ctags = shift;
2660 # First, merge different-cased tags; tags vote on casing
2661 my %ctags_lc;
2662 foreach (keys %$ctags) {
2663 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2664 if (not $ctags_lc{lc $_}->{topcount}
2665 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2666 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2667 $ctags_lc{lc $_}->{topname} = $_;
2671 my $cloud;
2672 if (eval { require HTML::TagCloud; 1; }) {
2673 $cloud = HTML::TagCloud->new;
2674 foreach (sort keys %ctags_lc) {
2675 # Pad the title with spaces so that the cloud looks
2676 # less crammed.
2677 my $title = $ctags_lc{$_}->{topname};
2678 $title =~ s/ /&nbsp;/g;
2679 $title =~ s/^/&nbsp;/g;
2680 $title =~ s/$/&nbsp;/g;
2681 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2683 } else {
2684 $cloud = \%ctags_lc;
2686 $cloud;
2689 sub git_show_project_tagcloud {
2690 my ($cloud, $count) = @_;
2691 print STDERR ref($cloud)."..\n";
2692 if (ref $cloud eq 'HTML::TagCloud') {
2693 return $cloud->html_and_css($count);
2694 } else {
2695 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2696 return '<p align="center">' . join (', ', map {
2697 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2698 } splice(@tags, 0, $count)) . '</p>';
2702 sub git_get_project_url_list {
2703 my $path = shift;
2705 $git_dir = "$projectroot/$path";
2706 open my $fd, '<', "$git_dir/cloneurl"
2707 or return wantarray ?
2708 @{ config_to_multi(git_get_project_config('url')) } :
2709 config_to_multi(git_get_project_config('url'));
2710 my @git_project_url_list = map { chomp; $_ } <$fd>;
2711 close $fd;
2713 return wantarray ? @git_project_url_list : \@git_project_url_list;
2716 sub git_get_projects_list {
2717 my ($filter) = @_;
2718 my @list;
2720 $filter ||= '';
2721 $filter =~ s/\.git$//;
2723 my $check_forks = gitweb_check_feature('forks');
2725 if (-d $projects_list) {
2726 # search in directory
2727 my $dir = $projects_list . ($filter ? "/$filter" : '');
2728 # remove the trailing "/"
2729 $dir =~ s!/+$!!;
2730 my $pfxlen = length("$dir");
2731 my $pfxdepth = ($dir =~ tr!/!!);
2733 File::Find::find({
2734 follow_fast => 1, # follow symbolic links
2735 follow_skip => 2, # ignore duplicates
2736 dangling_symlinks => 0, # ignore dangling symlinks, silently
2737 wanted => sub {
2738 # global variables
2739 our $project_maxdepth;
2740 our $projectroot;
2741 # skip project-list toplevel, if we get it.
2742 return if (m!^[/.]$!);
2743 # only directories can be git repositories
2744 return unless (-d $_);
2745 # don't traverse too deep (Find is super slow on os x)
2746 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2747 $File::Find::prune = 1;
2748 return;
2751 my $subdir = substr($File::Find::name, $pfxlen + 1);
2752 # we check related file in $projectroot
2753 my $path = ($filter ? "$filter/" : '') . $subdir;
2754 if (check_export_ok("$projectroot/$path")) {
2755 push @list, { path => $path };
2756 $File::Find::prune = 1;
2759 }, "$dir");
2761 } elsif (-f $projects_list) {
2762 # read from file(url-encoded):
2763 # 'git%2Fgit.git Linus+Torvalds'
2764 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2765 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2766 my %paths;
2767 open my $fd, '<', $projects_list or return;
2768 PROJECT:
2769 while (my $line = <$fd>) {
2770 chomp $line;
2771 my ($path, $owner) = split ' ', $line;
2772 $path = unescape($path);
2773 $owner = unescape($owner);
2774 if (!defined $path) {
2775 next;
2777 if ($filter ne '') {
2778 # looking for forks;
2779 my $pfx = substr($path, 0, length($filter));
2780 if ($pfx ne $filter) {
2781 next PROJECT;
2783 my $sfx = substr($path, length($filter));
2784 if ($sfx !~ /^\/.*\.git$/) {
2785 next PROJECT;
2787 } elsif ($check_forks) {
2788 PATH:
2789 foreach my $filter (keys %paths) {
2790 # looking for forks;
2791 my $pfx = substr($path, 0, length($filter));
2792 if ($pfx ne $filter) {
2793 next PATH;
2795 my $sfx = substr($path, length($filter));
2796 if ($sfx !~ /^\/.*\.git$/) {
2797 next PATH;
2799 # is a fork, don't include it in
2800 # the list
2801 next PROJECT;
2804 if (check_export_ok("$projectroot/$path")) {
2805 my $pr = {
2806 path => $path,
2807 owner => to_utf8($owner),
2809 push @list, $pr;
2810 (my $forks_path = $path) =~ s/\.git$//;
2811 $paths{$forks_path}++;
2814 close $fd;
2816 return @list;
2819 our $gitweb_project_owner = undef;
2820 sub git_get_project_list_from_file {
2822 return if (defined $gitweb_project_owner);
2824 $gitweb_project_owner = {};
2825 # read from file (url-encoded):
2826 # 'git%2Fgit.git Linus+Torvalds'
2827 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2828 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2829 if (-f $projects_list) {
2830 open(my $fd, '<', $projects_list);
2831 while (my $line = <$fd>) {
2832 chomp $line;
2833 my ($pr, $ow) = split ' ', $line;
2834 $pr = unescape($pr);
2835 $ow = unescape($ow);
2836 $gitweb_project_owner->{$pr} = to_utf8($ow);
2838 close $fd;
2842 sub git_get_project_owner {
2843 my $project = shift;
2844 my $owner;
2846 return undef unless $project;
2847 $git_dir = "$projectroot/$project";
2849 if (!defined $gitweb_project_owner) {
2850 git_get_project_list_from_file();
2853 if (exists $gitweb_project_owner->{$project}) {
2854 $owner = $gitweb_project_owner->{$project};
2856 if (!defined $owner){
2857 $owner = git_get_project_config('owner');
2859 if (!defined $owner) {
2860 $owner = get_file_owner("$git_dir");
2863 return $owner;
2866 sub git_get_last_activity {
2867 my ($path) = @_;
2868 my $fd;
2870 $git_dir = "$projectroot/$path";
2871 open($fd, "-|", git_cmd(), 'for-each-ref',
2872 '--format=%(committer)',
2873 '--sort=-committerdate',
2874 '--count=1',
2875 'refs/heads') or return;
2876 my $most_recent = <$fd>;
2877 close $fd or return;
2878 if (defined $most_recent &&
2879 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2880 my $timestamp = $1;
2881 my $age = time - $timestamp;
2882 return ($age, age_string($age));
2884 return (undef, undef);
2887 sub git_get_references {
2888 my $type = shift || "";
2889 my %refs;
2890 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2891 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2892 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2893 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2894 or return;
2896 while (my $line = <$fd>) {
2897 chomp $line;
2898 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2899 if (defined $refs{$1}) {
2900 push @{$refs{$1}}, $2;
2901 } else {
2902 $refs{$1} = [ $2 ];
2906 close $fd or return;
2907 return \%refs;
2910 sub git_get_rev_name_tags {
2911 my $hash = shift || return undef;
2913 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2914 or return;
2915 my $name_rev = <$fd>;
2916 close $fd;
2918 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2919 return $1;
2920 } else {
2921 # catches also '$hash undefined' output
2922 return undef;
2926 ## ----------------------------------------------------------------------
2927 ## parse to hash functions
2929 sub parse_date {
2930 my $epoch = shift;
2931 my $tz = shift || "-0000";
2933 my %date;
2934 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2935 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2936 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2937 $date{'hour'} = $hour;
2938 $date{'minute'} = $min;
2939 $date{'mday'} = $mday;
2940 $date{'day'} = $days[$wday];
2941 $date{'month'} = $months[$mon];
2942 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2943 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2944 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2945 $mday, $months[$mon], $hour ,$min;
2946 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2947 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2949 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2950 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2951 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2952 $date{'hour_local'} = $hour;
2953 $date{'minute_local'} = $min;
2954 $date{'tz_local'} = $tz;
2955 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2956 1900+$year, $mon+1, $mday,
2957 $hour, $min, $sec, $tz);
2958 return %date;
2961 sub parse_tag {
2962 my $tag_id = shift;
2963 my %tag;
2964 my @comment;
2966 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2967 $tag{'id'} = $tag_id;
2968 while (my $line = <$fd>) {
2969 chomp $line;
2970 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2971 $tag{'object'} = $1;
2972 } elsif ($line =~ m/^type (.+)$/) {
2973 $tag{'type'} = $1;
2974 } elsif ($line =~ m/^tag (.+)$/) {
2975 $tag{'name'} = $1;
2976 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2977 $tag{'author'} = $1;
2978 $tag{'author_epoch'} = $2;
2979 $tag{'author_tz'} = $3;
2980 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2981 $tag{'author_name'} = $1;
2982 $tag{'author_email'} = $2;
2983 } else {
2984 $tag{'author_name'} = $tag{'author'};
2986 } elsif ($line =~ m/--BEGIN/) {
2987 push @comment, $line;
2988 last;
2989 } elsif ($line eq "") {
2990 last;
2993 push @comment, <$fd>;
2994 $tag{'comment'} = \@comment;
2995 close $fd or return;
2996 if (!defined $tag{'name'}) {
2997 return
2999 return %tag
3002 sub parse_commit_text {
3003 my ($commit_text, $withparents) = @_;
3004 my @commit_lines = split '\n', $commit_text;
3005 my %co;
3007 pop @commit_lines; # Remove '\0'
3009 if (! @commit_lines) {
3010 return;
3013 my $header = shift @commit_lines;
3014 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3015 return;
3017 ($co{'id'}, my @parents) = split ' ', $header;
3018 while (my $line = shift @commit_lines) {
3019 last if $line eq "\n";
3020 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3021 $co{'tree'} = $1;
3022 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3023 push @parents, $1;
3024 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3025 $co{'author'} = to_utf8($1);
3026 $co{'author_epoch'} = $2;
3027 $co{'author_tz'} = $3;
3028 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3029 $co{'author_name'} = $1;
3030 $co{'author_email'} = $2;
3031 } else {
3032 $co{'author_name'} = $co{'author'};
3034 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3035 $co{'committer'} = to_utf8($1);
3036 $co{'committer_epoch'} = $2;
3037 $co{'committer_tz'} = $3;
3038 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3039 $co{'committer_name'} = $1;
3040 $co{'committer_email'} = $2;
3041 } else {
3042 $co{'committer_name'} = $co{'committer'};
3046 if (!defined $co{'tree'}) {
3047 return;
3049 $co{'parents'} = \@parents;
3050 $co{'parent'} = $parents[0];
3052 foreach my $title (@commit_lines) {
3053 $title =~ s/^ //;
3054 if ($title ne "") {
3055 $co{'title'} = chop_str($title, 80, 5);
3056 # remove leading stuff of merges to make the interesting part visible
3057 if (length($title) > 50) {
3058 $title =~ s/^Automatic //;
3059 $title =~ s/^merge (of|with) /Merge ... /i;
3060 if (length($title) > 50) {
3061 $title =~ s/(http|rsync):\/\///;
3063 if (length($title) > 50) {
3064 $title =~ s/(master|www|rsync)\.//;
3066 if (length($title) > 50) {
3067 $title =~ s/kernel.org:?//;
3069 if (length($title) > 50) {
3070 $title =~ s/\/pub\/scm//;
3073 $co{'title_short'} = chop_str($title, 50, 5);
3074 last;
3077 if (! defined $co{'title'} || $co{'title'} eq "") {
3078 $co{'title'} = $co{'title_short'} = '(no commit message)';
3080 # remove added spaces
3081 foreach my $line (@commit_lines) {
3082 $line =~ s/^ //;
3084 $co{'comment'} = \@commit_lines;
3086 my $age = time - $co{'committer_epoch'};
3087 $co{'age'} = $age;
3088 $co{'age_string'} = age_string($age);
3089 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3090 if ($age > 60*60*24*7*2) {
3091 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3092 $co{'age_string_age'} = $co{'age_string'};
3093 } else {
3094 $co{'age_string_date'} = $co{'age_string'};
3095 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3097 return %co;
3100 sub parse_commit {
3101 my ($commit_id) = @_;
3102 my %co;
3104 local $/ = "\0";
3106 open my $fd, "-|", git_cmd(), "rev-list",
3107 "--parents",
3108 "--header",
3109 "--max-count=1",
3110 $commit_id,
3111 "--",
3112 or die_error(500, "Open git-rev-list failed");
3113 %co = parse_commit_text(<$fd>, 1);
3114 close $fd;
3116 return %co;
3119 sub parse_commits {
3120 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3121 my @cos;
3123 $maxcount ||= 1;
3124 $skip ||= 0;
3126 local $/ = "\0";
3128 open my $fd, "-|", git_cmd(), "rev-list",
3129 "--header",
3130 @args,
3131 ("--max-count=" . $maxcount),
3132 ("--skip=" . $skip),
3133 @extra_options,
3134 $commit_id,
3135 "--",
3136 ($filename ? ($filename) : ())
3137 or die_error(500, "Open git-rev-list failed");
3138 while (my $line = <$fd>) {
3139 my %co = parse_commit_text($line);
3140 push @cos, \%co;
3142 close $fd;
3144 return wantarray ? @cos : \@cos;
3147 # parse line of git-diff-tree "raw" output
3148 sub parse_difftree_raw_line {
3149 my $line = shift;
3150 my %res;
3152 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3153 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3154 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3155 $res{'from_mode'} = $1;
3156 $res{'to_mode'} = $2;
3157 $res{'from_id'} = $3;
3158 $res{'to_id'} = $4;
3159 $res{'status'} = $5;
3160 $res{'similarity'} = $6;
3161 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3162 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3163 } else {
3164 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3167 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3168 # combined diff (for merge commit)
3169 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3170 $res{'nparents'} = length($1);
3171 $res{'from_mode'} = [ split(' ', $2) ];
3172 $res{'to_mode'} = pop @{$res{'from_mode'}};
3173 $res{'from_id'} = [ split(' ', $3) ];
3174 $res{'to_id'} = pop @{$res{'from_id'}};
3175 $res{'status'} = [ split('', $4) ];
3176 $res{'to_file'} = unquote($5);
3178 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3179 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3180 $res{'commit'} = $1;
3183 return wantarray ? %res : \%res;
3186 # wrapper: return parsed line of git-diff-tree "raw" output
3187 # (the argument might be raw line, or parsed info)
3188 sub parsed_difftree_line {
3189 my $line_or_ref = shift;
3191 if (ref($line_or_ref) eq "HASH") {
3192 # pre-parsed (or generated by hand)
3193 return $line_or_ref;
3194 } else {
3195 return parse_difftree_raw_line($line_or_ref);
3199 # parse line of git-ls-tree output
3200 sub parse_ls_tree_line {
3201 my $line = shift;
3202 my %opts = @_;
3203 my %res;
3205 if ($opts{'-l'}) {
3206 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3207 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3209 $res{'mode'} = $1;
3210 $res{'type'} = $2;
3211 $res{'hash'} = $3;
3212 $res{'size'} = $4;
3213 if ($opts{'-z'}) {
3214 $res{'name'} = $5;
3215 } else {
3216 $res{'name'} = unquote($5);
3218 } else {
3219 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3220 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3222 $res{'mode'} = $1;
3223 $res{'type'} = $2;
3224 $res{'hash'} = $3;
3225 if ($opts{'-z'}) {
3226 $res{'name'} = $4;
3227 } else {
3228 $res{'name'} = unquote($4);
3232 return wantarray ? %res : \%res;
3235 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3236 sub parse_from_to_diffinfo {
3237 my ($diffinfo, $from, $to, @parents) = @_;
3239 if ($diffinfo->{'nparents'}) {
3240 # combined diff
3241 $from->{'file'} = [];
3242 $from->{'href'} = [];
3243 fill_from_file_info($diffinfo, @parents)
3244 unless exists $diffinfo->{'from_file'};
3245 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3246 $from->{'file'}[$i] =
3247 defined $diffinfo->{'from_file'}[$i] ?
3248 $diffinfo->{'from_file'}[$i] :
3249 $diffinfo->{'to_file'};
3250 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3251 $from->{'href'}[$i] = href(action=>"blob",
3252 hash_base=>$parents[$i],
3253 hash=>$diffinfo->{'from_id'}[$i],
3254 file_name=>$from->{'file'}[$i]);
3255 } else {
3256 $from->{'href'}[$i] = undef;
3259 } else {
3260 # ordinary (not combined) diff
3261 $from->{'file'} = $diffinfo->{'from_file'};
3262 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3263 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3264 hash=>$diffinfo->{'from_id'},
3265 file_name=>$from->{'file'});
3266 } else {
3267 delete $from->{'href'};
3271 $to->{'file'} = $diffinfo->{'to_file'};
3272 if (!is_deleted($diffinfo)) { # file exists in result
3273 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3274 hash=>$diffinfo->{'to_id'},
3275 file_name=>$to->{'file'});
3276 } else {
3277 delete $to->{'href'};
3281 ## ......................................................................
3282 ## parse to array of hashes functions
3284 sub git_get_heads_list {
3285 my $limit = shift;
3286 my @headslist;
3288 open my $fd, '-|', git_cmd(), 'for-each-ref',
3289 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3290 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3291 'refs/heads'
3292 or return;
3293 while (my $line = <$fd>) {
3294 my %ref_item;
3296 chomp $line;
3297 my ($refinfo, $committerinfo) = split(/\0/, $line);
3298 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3299 my ($committer, $epoch, $tz) =
3300 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3301 $ref_item{'fullname'} = $name;
3302 $name =~ s!^refs/heads/!!;
3304 $ref_item{'name'} = $name;
3305 $ref_item{'id'} = $hash;
3306 $ref_item{'title'} = $title || '(no commit message)';
3307 $ref_item{'epoch'} = $epoch;
3308 if ($epoch) {
3309 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3310 } else {
3311 $ref_item{'age'} = "unknown";
3314 push @headslist, \%ref_item;
3316 close $fd;
3318 return wantarray ? @headslist : \@headslist;
3321 sub git_get_tags_list {
3322 my $limit = shift;
3323 my @tagslist;
3325 open my $fd, '-|', git_cmd(), 'for-each-ref',
3326 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3327 '--format=%(objectname) %(objecttype) %(refname) '.
3328 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3329 'refs/tags'
3330 or return;
3331 while (my $line = <$fd>) {
3332 my %ref_item;
3334 chomp $line;
3335 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3336 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3337 my ($creator, $epoch, $tz) =
3338 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3339 $ref_item{'fullname'} = $name;
3340 $name =~ s!^refs/tags/!!;
3342 $ref_item{'type'} = $type;
3343 $ref_item{'id'} = $id;
3344 $ref_item{'name'} = $name;
3345 if ($type eq "tag") {
3346 $ref_item{'subject'} = $title;
3347 $ref_item{'reftype'} = $reftype;
3348 $ref_item{'refid'} = $refid;
3349 } else {
3350 $ref_item{'reftype'} = $type;
3351 $ref_item{'refid'} = $id;
3354 if ($type eq "tag" || $type eq "commit") {
3355 $ref_item{'epoch'} = $epoch;
3356 if ($epoch) {
3357 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3358 } else {
3359 $ref_item{'age'} = "unknown";
3363 push @tagslist, \%ref_item;
3365 close $fd;
3367 return wantarray ? @tagslist : \@tagslist;
3370 ## ----------------------------------------------------------------------
3371 ## filesystem-related functions
3373 sub get_file_owner {
3374 my $path = shift;
3376 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3377 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3378 if (!defined $gcos) {
3379 return undef;
3381 my $owner = $gcos;
3382 $owner =~ s/[,;].*$//;
3383 return to_utf8($owner);
3386 # assume that file exists
3387 sub insert_file {
3388 my $filename = shift;
3390 open my $fd, '<', $filename;
3391 print map { to_utf8($_) } <$fd>;
3392 close $fd;
3395 ## ......................................................................
3396 ## mimetype related functions
3398 sub mimetype_guess_file {
3399 my $filename = shift;
3400 my $mimemap = shift;
3401 -r $mimemap or return undef;
3403 my %mimemap;
3404 open(my $mh, '<', $mimemap) or return undef;
3405 while (<$mh>) {
3406 next if m/^#/; # skip comments
3407 my ($mimetype, $exts) = split(/\t+/);
3408 if (defined $exts) {
3409 my @exts = split(/\s+/, $exts);
3410 foreach my $ext (@exts) {
3411 $mimemap{$ext} = $mimetype;
3415 close($mh);
3417 $filename =~ /\.([^.]*)$/;
3418 return $mimemap{$1};
3421 sub mimetype_guess {
3422 my $filename = shift;
3423 my $mime;
3424 $filename =~ /\./ or return undef;
3426 if ($mimetypes_file) {
3427 my $file = $mimetypes_file;
3428 if ($file !~ m!^/!) { # if it is relative path
3429 # it is relative to project
3430 $file = "$projectroot/$project/$file";
3432 $mime = mimetype_guess_file($filename, $file);
3434 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3435 return $mime;
3438 sub blob_mimetype {
3439 my $fd = shift;
3440 my $filename = shift;
3442 if ($filename) {
3443 my $mime = mimetype_guess($filename);
3444 $mime and return $mime;
3447 # just in case
3448 return $default_blob_plain_mimetype unless $fd;
3450 if (-T $fd) {
3451 return 'text/plain';
3452 } elsif (! $filename) {
3453 return 'application/octet-stream';
3454 } elsif ($filename =~ m/\.png$/i) {
3455 return 'image/png';
3456 } elsif ($filename =~ m/\.gif$/i) {
3457 return 'image/gif';
3458 } elsif ($filename =~ m/\.jpe?g$/i) {
3459 return 'image/jpeg';
3460 } else {
3461 return 'application/octet-stream';
3465 sub blob_contenttype {
3466 my ($fd, $file_name, $type) = @_;
3468 $type ||= blob_mimetype($fd, $file_name);
3469 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3470 $type .= "; charset=$default_text_plain_charset";
3473 return $type;
3476 # guess file syntax for syntax highlighting; return undef if no highlighting
3477 # the name of syntax can (in the future) depend on syntax highlighter used
3478 sub guess_file_syntax {
3479 my ($highlight, $mimetype, $file_name) = @_;
3480 return undef unless ($highlight && defined $file_name);
3481 my $basename = basename($file_name, '.in');
3482 return $highlight_basename{$basename}
3483 if exists $highlight_basename{$basename};
3485 $basename =~ /\.([^.]*)$/;
3486 my $ext = $1 or return undef;
3487 return $highlight_ext{$ext}
3488 if exists $highlight_ext{$ext};
3490 return undef;
3493 # run highlighter and return FD of its output,
3494 # or return original FD if no highlighting
3495 sub run_highlighter {
3496 my ($fd, $highlight, $syntax) = @_;
3497 return $fd unless ($highlight && defined $syntax);
3499 close $fd
3500 or die_error(404, "Reading blob failed");
3501 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3502 quote_command($highlight_bin).
3503 " --xhtml --fragment --syntax $syntax |"
3504 or die_error(500, "Couldn't open file or run syntax highlighter");
3505 return $fd;
3508 ## ======================================================================
3509 ## functions printing HTML: header, footer, error page
3511 sub get_page_title {
3512 my $title = to_utf8($site_name);
3514 return $title unless (defined $project);
3515 $title .= " - " . to_utf8($project);
3517 return $title unless (defined $action);
3518 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3520 return $title unless (defined $file_name);
3521 $title .= " - " . esc_path($file_name);
3522 if ($action eq "tree" && $file_name !~ m|/$|) {
3523 $title .= "/";
3526 return $title;
3529 sub git_header_html {
3530 my $status = shift || "200 OK";
3531 my $expires = shift;
3532 my %opts = @_;
3534 my $title = get_page_title();
3535 my $content_type;
3536 # require explicit support from the UA if we are to send the page as
3537 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3538 # we have to do this because MSIE sometimes globs '*/*', pretending to
3539 # support xhtml+xml but choking when it gets what it asked for.
3540 # Disable content-type negotiation when caching (use mimetype good for all).
3541 if (!$caching_enabled &&
3542 defined $cgi->http('HTTP_ACCEPT') &&
3543 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3544 $cgi->Accept('application/xhtml+xml') != 0) {
3545 $content_type = 'application/xhtml+xml';
3546 } else {
3547 $content_type = 'text/html';
3549 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3550 -status=> $status, -expires => $expires)
3551 unless ($opts{'-no_http_header'});
3552 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3553 print <<EOF;
3554 <?xml version="1.0" encoding="utf-8"?>
3555 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3556 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3557 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3558 <!-- git core binaries version $git_version -->
3559 <head>
3560 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3561 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3562 <meta name="robots" content="index, nofollow"/>
3563 <title>$title</title>
3565 # the stylesheet, favicon etc urls won't work correctly with path_info
3566 # unless we set the appropriate base URL
3567 # if caching is enabled we can get it from cache for path_info when it
3568 # is generated without path_info
3569 if ($ENV{'PATH_INFO'} || $caching_enabled) {
3570 print "<base href=\"".esc_url($base_url)."\" />\n";
3572 # print out each stylesheet that exist, providing backwards capability
3573 # for those people who defined $stylesheet in a config file
3574 if (defined $stylesheet) {
3575 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3576 } else {
3577 foreach my $stylesheet (@stylesheets) {
3578 next unless $stylesheet;
3579 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3582 if (defined $project) {
3583 my %href_params = get_feed_info();
3584 if (!exists $href_params{'-title'}) {
3585 $href_params{'-title'} = 'log';
3588 foreach my $format qw(RSS Atom) {
3589 my $type = lc($format);
3590 my %link_attr = (
3591 '-rel' => 'alternate',
3592 '-title' => "$project - $href_params{'-title'} - $format feed",
3593 '-type' => "application/$type+xml"
3596 $href_params{'action'} = $type;
3597 $link_attr{'-href'} = href(%href_params);
3598 print "<link ".
3599 "rel=\"$link_attr{'-rel'}\" ".
3600 "title=\"$link_attr{'-title'}\" ".
3601 "href=\"$link_attr{'-href'}\" ".
3602 "type=\"$link_attr{'-type'}\" ".
3603 "/>\n";
3605 $href_params{'extra_options'} = '--no-merges';
3606 $link_attr{'-href'} = href(%href_params);
3607 $link_attr{'-title'} .= ' (no merges)';
3608 print "<link ".
3609 "rel=\"$link_attr{'-rel'}\" ".
3610 "title=\"$link_attr{'-title'}\" ".
3611 "href=\"$link_attr{'-href'}\" ".
3612 "type=\"$link_attr{'-type'}\" ".
3613 "/>\n";
3616 } else {
3617 printf('<link rel="alternate" title="%s projects list" '.
3618 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3619 $site_name, href(project=>undef, action=>"project_index"));
3620 printf('<link rel="alternate" title="%s projects feeds" '.
3621 'href="%s" type="text/x-opml" />'."\n",
3622 $site_name, href(project=>undef, action=>"opml"));
3624 if (defined $favicon) {
3625 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3628 print "</head>\n" .
3629 "<body>\n";
3631 if (defined $site_header && -f $site_header) {
3632 insert_file($site_header);
3635 print "<div class=\"page_header\">\n" .
3636 $cgi->a({-href => esc_url($logo_url),
3637 -title => $logo_label},
3638 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3639 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3640 if (defined $project) {
3641 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3642 if (defined $action) {
3643 print " / $action";
3645 print "\n";
3647 print "</div>\n";
3649 my $have_search = gitweb_check_feature('search');
3650 if (defined $project && $have_search) {
3651 if (!defined $searchtext) {
3652 $searchtext = "";
3654 my $search_hash;
3655 if (defined $hash_base) {
3656 $search_hash = $hash_base;
3657 } elsif (defined $hash) {
3658 $search_hash = $hash;
3659 } else {
3660 $search_hash = "HEAD";
3662 my $action = $my_uri;
3663 my $use_pathinfo = gitweb_check_feature('pathinfo');
3664 if ($use_pathinfo) {
3665 $action .= "/".esc_url($project);
3667 print $cgi->startform(-method => "get", -action => $action) .
3668 "<div class=\"search\">\n" .
3669 (!$use_pathinfo &&
3670 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3671 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3672 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3673 $cgi->popup_menu(-name => 'st', -default => 'commit',
3674 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3675 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3676 " search:\n",
3677 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3678 "<span title=\"Extended regular expression\">" .
3679 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3680 -checked => $search_use_regexp) .
3681 "</span>" .
3682 "</div>" .
3683 $cgi->end_form() . "\n";
3687 sub git_footer_html {
3688 my $feed_class = 'rss_logo';
3690 print "<div class=\"page_footer\">\n";
3691 if (defined $project) {
3692 my $descr = git_get_project_description($project);
3693 if (defined $descr) {
3694 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3697 my %href_params = get_feed_info();
3698 if (!%href_params) {
3699 $feed_class .= ' generic';
3701 $href_params{'-title'} ||= 'log';
3703 foreach my $format qw(RSS Atom) {
3704 $href_params{'action'} = lc($format);
3705 print $cgi->a({-href => href(%href_params),
3706 -title => "$href_params{'-title'} $format feed",
3707 -class => $feed_class}, $format)."\n";
3710 } else {
3711 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3712 -class => $feed_class}, "OPML") . " ";
3713 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3714 -class => $feed_class}, "TXT") . "\n";
3716 print "</div>\n"; # class="page_footer"
3718 # timing info doesn't make much sense with output (response) caching,
3719 # so when caching is enabled gitweb prints the time of page generation
3720 if ((defined $t0 || $caching_enabled) &&
3721 gitweb_check_feature('timed')) {
3722 print "<div id=\"generating_info\">\n";
3723 if ($caching_enabled) {
3724 print 'This page was generated at '.
3725 gmtime( time() )." GMT\n";
3726 } else {
3727 print 'This page took '.
3728 '<span id="generating_time" class="time_span">'.
3729 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3730 ' seconds </span>'.
3731 ' and '.
3732 '<span id="generating_cmd">'.
3733 $number_of_git_cmds.
3734 '</span> git commands '.
3735 " to generate.\n";
3737 print "</div>\n"; # class="page_footer"
3740 if (defined $site_footer && -f $site_footer) {
3741 insert_file($site_footer);
3744 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3745 if (!$caching_enabled &&
3746 defined $action && $action eq 'blame_incremental') {
3747 print qq!<script type="text/javascript">\n!.
3748 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3749 qq! "!. href() .qq!");\n!.
3750 qq!</script>\n!;
3751 } elsif (gitweb_check_feature('javascript-actions')) {
3752 print qq!<script type="text/javascript">\n!.
3753 qq!window.onload = fixLinks;\n!.
3754 qq!</script>\n!;
3757 print "</body>\n" .
3758 "</html>";
3761 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3762 # Example: die_error(404, 'Hash not found')
3763 # By convention, use the following status codes (as defined in RFC 2616):
3764 # 400: Invalid or missing CGI parameters, or
3765 # requested object exists but has wrong type.
3766 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3767 # this server or project.
3768 # 404: Requested object/revision/project doesn't exist.
3769 # 500: The server isn't configured properly, or
3770 # an internal error occurred (e.g. failed assertions caused by bugs), or
3771 # an unknown error occurred (e.g. the git binary died unexpectedly).
3772 # 503: The server is currently unavailable (because it is overloaded,
3773 # or down for maintenance). Generally, this is a temporary state.
3774 sub die_error {
3775 my $status = shift || 500;
3776 my $error = esc_html(shift) || "Internal Server Error";
3777 my $extra = shift;
3778 my %opts = @_;
3780 my %http_responses = (
3781 400 => '400 Bad Request',
3782 403 => '403 Forbidden',
3783 404 => '404 Not Found',
3784 500 => '500 Internal Server Error',
3785 503 => '503 Service Unavailable',
3788 # Do not cache error pages
3789 capture_stop($cache, $capture) if ($capture && $caching_enabled);
3791 git_header_html($http_responses{$status}, undef, %opts);
3792 print <<EOF;
3793 <div class="page_body">
3794 <br /><br />
3795 $status - $error
3796 <br />
3798 if (defined $extra) {
3799 print "<hr />\n" .
3800 "$extra\n";
3802 print "</div>\n";
3804 git_footer_html();
3805 goto DONE_GITWEB
3806 unless ($opts{'-error_handler'});
3809 ## ----------------------------------------------------------------------
3810 ## functions printing or outputting HTML: navigation
3812 sub git_print_page_nav {
3813 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3814 $extra = '' if !defined $extra; # pager or formats
3816 my @navs = qw(summary shortlog log commit commitdiff tree);
3817 if ($suppress) {
3818 @navs = grep { $_ ne $suppress } @navs;
3821 my %arg = map { $_ => {action=>$_} } @navs;
3822 if (defined $head) {
3823 for (qw(commit commitdiff)) {
3824 $arg{$_}{'hash'} = $head;
3826 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3827 for (qw(shortlog log)) {
3828 $arg{$_}{'hash'} = $head;
3833 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3834 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3836 my @actions = gitweb_get_feature('actions');
3837 my %repl = (
3838 '%' => '%',
3839 'n' => $project, # project name
3840 'f' => $git_dir, # project path within filesystem
3841 'h' => $treehead || '', # current hash ('h' parameter)
3842 'b' => $treebase || '', # hash base ('hb' parameter)
3844 while (@actions) {
3845 my ($label, $link, $pos) = splice(@actions,0,3);
3846 # insert
3847 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3848 # munch munch
3849 $link =~ s/%([%nfhb])/$repl{$1}/g;
3850 $arg{$label}{'_href'} = $link;
3853 print "<div class=\"page_nav\">\n" .
3854 (join " | ",
3855 map { $_ eq $current ?
3856 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3857 } @navs);
3858 print "<br/>\n$extra<br/>\n" .
3859 "</div>\n";
3862 sub format_paging_nav {
3863 my ($action, $page, $has_next_link) = @_;
3864 my $paging_nav;
3867 if ($page > 0) {
3868 $paging_nav .=
3869 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3870 " &sdot; " .
3871 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3872 -accesskey => "p", -title => "Alt-p"}, "prev");
3873 } else {
3874 $paging_nav .= "first &sdot; prev";
3877 if ($has_next_link) {
3878 $paging_nav .= " &sdot; " .
3879 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3880 -accesskey => "n", -title => "Alt-n"}, "next");
3881 } else {
3882 $paging_nav .= " &sdot; next";
3885 return $paging_nav;
3888 ## ......................................................................
3889 ## functions printing or outputting HTML: div
3891 sub git_print_header_div {
3892 my ($action, $title, $hash, $hash_base) = @_;
3893 my %args = ();
3895 $args{'action'} = $action;
3896 $args{'hash'} = $hash if $hash;
3897 $args{'hash_base'} = $hash_base if $hash_base;
3899 print "<div class=\"header\">\n" .
3900 $cgi->a({-href => href(%args), -class => "title"},
3901 $title ? $title : $action) .
3902 "\n</div>\n";
3905 sub print_local_time {
3906 print format_local_time(@_);
3909 sub format_local_time {
3910 my $localtime = '';
3911 my %date = @_;
3912 if ($date{'hour_local'} < 6) {
3913 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3914 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3915 } else {
3916 $localtime .= sprintf(" (%02d:%02d %s)",
3917 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3920 return $localtime;
3923 # Outputs the author name and date in long form
3924 sub git_print_authorship {
3925 my $co = shift;
3926 my %opts = @_;
3927 my $tag = $opts{-tag} || 'div';
3928 my $author = $co->{'author_name'};
3930 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3931 print "<$tag class=\"author_date\">" .
3932 format_search_author($author, "author", esc_html($author)) .
3933 " [$ad{'rfc2822'}";
3934 print_local_time(%ad) if ($opts{-localtime});
3935 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3936 . "</$tag>\n";
3939 # Outputs table rows containing the full author or committer information,
3940 # in the format expected for 'commit' view (& similar).
3941 # Parameters are a commit hash reference, followed by the list of people
3942 # to output information for. If the list is empty it defaults to both
3943 # author and committer.
3944 sub git_print_authorship_rows {
3945 my $co = shift;
3946 # too bad we can't use @people = @_ || ('author', 'committer')
3947 my @people = @_;
3948 @people = ('author', 'committer') unless @people;
3949 foreach my $who (@people) {
3950 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3951 print "<tr><td>$who</td><td>" .
3952 format_search_author($co->{"${who}_name"}, $who,
3953 esc_html($co->{"${who}_name"})) . " " .
3954 format_search_author($co->{"${who}_email"}, $who,
3955 esc_html("<" . $co->{"${who}_email"} . ">")) .
3956 "</td><td rowspan=\"2\">" .
3957 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3958 "</td></tr>\n" .
3959 "<tr>" .
3960 "<td></td><td> $wd{'rfc2822'}";
3961 print_local_time(%wd);
3962 print "</td>" .
3963 "</tr>\n";
3967 sub git_print_page_path {
3968 my $name = shift;
3969 my $type = shift;
3970 my $hb = shift;
3973 print "<div class=\"page_path\">";
3974 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3975 -title => 'tree root'}, to_utf8("[$project]"));
3976 print " / ";
3977 if (defined $name) {
3978 my @dirname = split '/', $name;
3979 my $basename = pop @dirname;
3980 my $fullname = '';
3982 foreach my $dir (@dirname) {
3983 $fullname .= ($fullname ? '/' : '') . $dir;
3984 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3985 hash_base=>$hb),
3986 -title => $fullname}, esc_path($dir));
3987 print " / ";
3989 if (defined $type && $type eq 'blob') {
3990 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3991 hash_base=>$hb),
3992 -title => $name}, esc_path($basename));
3993 } elsif (defined $type && $type eq 'tree') {
3994 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3995 hash_base=>$hb),
3996 -title => $name}, esc_path($basename));
3997 print " / ";
3998 } else {
3999 print esc_path($basename);
4002 print "<br/></div>\n";
4005 sub git_print_log {
4006 my $log = shift;
4007 my %opts = @_;
4009 if ($opts{'-remove_title'}) {
4010 # remove title, i.e. first line of log
4011 shift @$log;
4013 # remove leading empty lines
4014 while (defined $log->[0] && $log->[0] eq "") {
4015 shift @$log;
4018 # print log
4019 my $signoff = 0;
4020 my $empty = 0;
4021 foreach my $line (@$log) {
4022 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4023 $signoff = 1;
4024 $empty = 0;
4025 if (! $opts{'-remove_signoff'}) {
4026 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4027 next;
4028 } else {
4029 # remove signoff lines
4030 next;
4032 } else {
4033 $signoff = 0;
4036 # print only one empty line
4037 # do not print empty line after signoff
4038 if ($line eq "") {
4039 next if ($empty || $signoff);
4040 $empty = 1;
4041 } else {
4042 $empty = 0;
4045 print format_log_line_html($line) . "<br/>\n";
4048 if ($opts{'-final_empty_line'}) {
4049 # end with single empty line
4050 print "<br/>\n" unless $empty;
4054 # return link target (what link points to)
4055 sub git_get_link_target {
4056 my $hash = shift;
4057 my $link_target;
4059 # read link
4060 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4061 or return;
4063 local $/ = undef;
4064 $link_target = <$fd>;
4066 close $fd
4067 or return;
4069 return $link_target;
4072 # given link target, and the directory (basedir) the link is in,
4073 # return target of link relative to top directory (top tree);
4074 # return undef if it is not possible (including absolute links).
4075 sub normalize_link_target {
4076 my ($link_target, $basedir) = @_;
4078 # absolute symlinks (beginning with '/') cannot be normalized
4079 return if (substr($link_target, 0, 1) eq '/');
4081 # normalize link target to path from top (root) tree (dir)
4082 my $path;
4083 if ($basedir) {
4084 $path = $basedir . '/' . $link_target;
4085 } else {
4086 # we are in top (root) tree (dir)
4087 $path = $link_target;
4090 # remove //, /./, and /../
4091 my @path_parts;
4092 foreach my $part (split('/', $path)) {
4093 # discard '.' and ''
4094 next if (!$part || $part eq '.');
4095 # handle '..'
4096 if ($part eq '..') {
4097 if (@path_parts) {
4098 pop @path_parts;
4099 } else {
4100 # link leads outside repository (outside top dir)
4101 return;
4103 } else {
4104 push @path_parts, $part;
4107 $path = join('/', @path_parts);
4109 return $path;
4112 # print tree entry (row of git_tree), but without encompassing <tr> element
4113 sub git_print_tree_entry {
4114 my ($t, $basedir, $hash_base, $have_blame) = @_;
4116 my %base_key = ();
4117 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4119 # The format of a table row is: mode list link. Where mode is
4120 # the mode of the entry, list is the name of the entry, an href,
4121 # and link is the action links of the entry.
4123 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4124 if (exists $t->{'size'}) {
4125 print "<td class=\"size\">$t->{'size'}</td>\n";
4127 if ($t->{'type'} eq "blob") {
4128 print "<td class=\"list\">" .
4129 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4130 file_name=>"$basedir$t->{'name'}", %base_key),
4131 -class => "list"}, esc_path($t->{'name'}));
4132 if (S_ISLNK(oct $t->{'mode'})) {
4133 my $link_target = git_get_link_target($t->{'hash'});
4134 if ($link_target) {
4135 my $norm_target = normalize_link_target($link_target, $basedir);
4136 if (defined $norm_target) {
4137 print " -> " .
4138 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4139 file_name=>$norm_target),
4140 -title => $norm_target}, esc_path($link_target));
4141 } else {
4142 print " -> " . esc_path($link_target);
4146 print "</td>\n";
4147 print "<td class=\"link\">";
4148 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4149 file_name=>"$basedir$t->{'name'}", %base_key)},
4150 "blob");
4151 if ($have_blame) {
4152 print " | " .
4153 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4154 file_name=>"$basedir$t->{'name'}", %base_key)},
4155 "blame");
4157 if (defined $hash_base) {
4158 print " | " .
4159 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4160 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4161 "history");
4163 print " | " .
4164 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4165 file_name=>"$basedir$t->{'name'}")},
4166 "raw");
4167 print "</td>\n";
4169 } elsif ($t->{'type'} eq "tree") {
4170 print "<td class=\"list\">";
4171 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4172 file_name=>"$basedir$t->{'name'}",
4173 %base_key)},
4174 esc_path($t->{'name'}));
4175 print "</td>\n";
4176 print "<td class=\"link\">";
4177 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4178 file_name=>"$basedir$t->{'name'}",
4179 %base_key)},
4180 "tree");
4181 if (defined $hash_base) {
4182 print " | " .
4183 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4184 file_name=>"$basedir$t->{'name'}")},
4185 "history");
4187 print "</td>\n";
4188 } else {
4189 # unknown object: we can only present history for it
4190 # (this includes 'commit' object, i.e. submodule support)
4191 print "<td class=\"list\">" .
4192 esc_path($t->{'name'}) .
4193 "</td>\n";
4194 print "<td class=\"link\">";
4195 if (defined $hash_base) {
4196 print $cgi->a({-href => href(action=>"history",
4197 hash_base=>$hash_base,
4198 file_name=>"$basedir$t->{'name'}")},
4199 "history");
4201 print "</td>\n";
4205 ## ......................................................................
4206 ## functions printing large fragments of HTML
4208 # get pre-image filenames for merge (combined) diff
4209 sub fill_from_file_info {
4210 my ($diff, @parents) = @_;
4212 $diff->{'from_file'} = [ ];
4213 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4214 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4215 if ($diff->{'status'}[$i] eq 'R' ||
4216 $diff->{'status'}[$i] eq 'C') {
4217 $diff->{'from_file'}[$i] =
4218 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4222 return $diff;
4225 # is current raw difftree line of file deletion
4226 sub is_deleted {
4227 my $diffinfo = shift;
4229 return $diffinfo->{'to_id'} eq ('0' x 40);
4232 # does patch correspond to [previous] difftree raw line
4233 # $diffinfo - hashref of parsed raw diff format
4234 # $patchinfo - hashref of parsed patch diff format
4235 # (the same keys as in $diffinfo)
4236 sub is_patch_split {
4237 my ($diffinfo, $patchinfo) = @_;
4239 return defined $diffinfo && defined $patchinfo
4240 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4244 sub git_difftree_body {
4245 my ($difftree, $hash, @parents) = @_;
4246 my ($parent) = $parents[0];
4247 my $have_blame = gitweb_check_feature('blame');
4248 print "<div class=\"list_head\">\n";
4249 if ($#{$difftree} > 10) {
4250 print(($#{$difftree} + 1) . " files changed:\n");
4252 print "</div>\n";
4254 print "<table class=\"" .
4255 (@parents > 1 ? "combined " : "") .
4256 "diff_tree\">\n";
4258 # header only for combined diff in 'commitdiff' view
4259 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4260 if ($has_header) {
4261 # table header
4262 print "<thead><tr>\n" .
4263 "<th></th><th></th>\n"; # filename, patchN link
4264 for (my $i = 0; $i < @parents; $i++) {
4265 my $par = $parents[$i];
4266 print "<th>" .
4267 $cgi->a({-href => href(action=>"commitdiff",
4268 hash=>$hash, hash_parent=>$par),
4269 -title => 'commitdiff to parent number ' .
4270 ($i+1) . ': ' . substr($par,0,7)},
4271 $i+1) .
4272 "&nbsp;</th>\n";
4274 print "</tr></thead>\n<tbody>\n";
4277 my $alternate = 1;
4278 my $patchno = 0;
4279 foreach my $line (@{$difftree}) {
4280 my $diff = parsed_difftree_line($line);
4282 if ($alternate) {
4283 print "<tr class=\"dark\">\n";
4284 } else {
4285 print "<tr class=\"light\">\n";
4287 $alternate ^= 1;
4289 if (exists $diff->{'nparents'}) { # combined diff
4291 fill_from_file_info($diff, @parents)
4292 unless exists $diff->{'from_file'};
4294 if (!is_deleted($diff)) {
4295 # file exists in the result (child) commit
4296 print "<td>" .
4297 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4298 file_name=>$diff->{'to_file'},
4299 hash_base=>$hash),
4300 -class => "list"}, esc_path($diff->{'to_file'})) .
4301 "</td>\n";
4302 } else {
4303 print "<td>" .
4304 esc_path($diff->{'to_file'}) .
4305 "</td>\n";
4308 if ($action eq 'commitdiff') {
4309 # link to patch
4310 $patchno++;
4311 print "<td class=\"link\">" .
4312 $cgi->a({-href => "#patch$patchno"}, "patch") .
4313 " | " .
4314 "</td>\n";
4317 my $has_history = 0;
4318 my $not_deleted = 0;
4319 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4320 my $hash_parent = $parents[$i];
4321 my $from_hash = $diff->{'from_id'}[$i];
4322 my $from_path = $diff->{'from_file'}[$i];
4323 my $status = $diff->{'status'}[$i];
4325 $has_history ||= ($status ne 'A');
4326 $not_deleted ||= ($status ne 'D');
4328 if ($status eq 'A') {
4329 print "<td class=\"link\" align=\"right\"> | </td>\n";
4330 } elsif ($status eq 'D') {
4331 print "<td class=\"link\">" .
4332 $cgi->a({-href => href(action=>"blob",
4333 hash_base=>$hash,
4334 hash=>$from_hash,
4335 file_name=>$from_path)},
4336 "blob" . ($i+1)) .
4337 " | </td>\n";
4338 } else {
4339 if ($diff->{'to_id'} eq $from_hash) {
4340 print "<td class=\"link nochange\">";
4341 } else {
4342 print "<td class=\"link\">";
4344 print $cgi->a({-href => href(action=>"blobdiff",
4345 hash=>$diff->{'to_id'},
4346 hash_parent=>$from_hash,
4347 hash_base=>$hash,
4348 hash_parent_base=>$hash_parent,
4349 file_name=>$diff->{'to_file'},
4350 file_parent=>$from_path)},
4351 "diff" . ($i+1)) .
4352 " | </td>\n";
4356 print "<td class=\"link\">";
4357 if ($not_deleted) {
4358 print $cgi->a({-href => href(action=>"blob",
4359 hash=>$diff->{'to_id'},
4360 file_name=>$diff->{'to_file'},
4361 hash_base=>$hash)},
4362 "blob");
4363 print " | " if ($has_history);
4365 if ($has_history) {
4366 print $cgi->a({-href => href(action=>"history",
4367 file_name=>$diff->{'to_file'},
4368 hash_base=>$hash)},
4369 "history");
4371 print "</td>\n";
4373 print "</tr>\n";
4374 next; # instead of 'else' clause, to avoid extra indent
4376 # else ordinary diff
4378 my ($to_mode_oct, $to_mode_str, $to_file_type);
4379 my ($from_mode_oct, $from_mode_str, $from_file_type);
4380 if ($diff->{'to_mode'} ne ('0' x 6)) {
4381 $to_mode_oct = oct $diff->{'to_mode'};
4382 if (S_ISREG($to_mode_oct)) { # only for regular file
4383 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4385 $to_file_type = file_type($diff->{'to_mode'});
4387 if ($diff->{'from_mode'} ne ('0' x 6)) {
4388 $from_mode_oct = oct $diff->{'from_mode'};
4389 if (S_ISREG($to_mode_oct)) { # only for regular file
4390 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4392 $from_file_type = file_type($diff->{'from_mode'});
4395 if ($diff->{'status'} eq "A") { # created
4396 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4397 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4398 $mode_chng .= "]</span>";
4399 print "<td>";
4400 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4401 hash_base=>$hash, file_name=>$diff->{'file'}),
4402 -class => "list"}, esc_path($diff->{'file'}));
4403 print "</td>\n";
4404 print "<td>$mode_chng</td>\n";
4405 print "<td class=\"link\">";
4406 if ($action eq 'commitdiff') {
4407 # link to patch
4408 $patchno++;
4409 print $cgi->a({-href => "#patch$patchno"}, "patch");
4410 print " | ";
4412 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4413 hash_base=>$hash, file_name=>$diff->{'file'})},
4414 "blob");
4415 print "</td>\n";
4417 } elsif ($diff->{'status'} eq "D") { # deleted
4418 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4419 print "<td>";
4420 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4421 hash_base=>$parent, file_name=>$diff->{'file'}),
4422 -class => "list"}, esc_path($diff->{'file'}));
4423 print "</td>\n";
4424 print "<td>$mode_chng</td>\n";
4425 print "<td class=\"link\">";
4426 if ($action eq 'commitdiff') {
4427 # link to patch
4428 $patchno++;
4429 print $cgi->a({-href => "#patch$patchno"}, "patch");
4430 print " | ";
4432 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4433 hash_base=>$parent, file_name=>$diff->{'file'})},
4434 "blob") . " | ";
4435 if ($have_blame) {
4436 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4437 file_name=>$diff->{'file'})},
4438 "blame") . " | ";
4440 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4441 file_name=>$diff->{'file'})},
4442 "history");
4443 print "</td>\n";
4445 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4446 my $mode_chnge = "";
4447 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4448 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4449 if ($from_file_type ne $to_file_type) {
4450 $mode_chnge .= " from $from_file_type to $to_file_type";
4452 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4453 if ($from_mode_str && $to_mode_str) {
4454 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4455 } elsif ($to_mode_str) {
4456 $mode_chnge .= " mode: $to_mode_str";
4459 $mode_chnge .= "]</span>\n";
4461 print "<td>";
4462 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4463 hash_base=>$hash, file_name=>$diff->{'file'}),
4464 -class => "list"}, esc_path($diff->{'file'}));
4465 print "</td>\n";
4466 print "<td>$mode_chnge</td>\n";
4467 print "<td class=\"link\">";
4468 if ($action eq 'commitdiff') {
4469 # link to patch
4470 $patchno++;
4471 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4472 " | ";
4473 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4474 # "commit" view and modified file (not onlu mode changed)
4475 print $cgi->a({-href => href(action=>"blobdiff",
4476 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4477 hash_base=>$hash, hash_parent_base=>$parent,
4478 file_name=>$diff->{'file'})},
4479 "diff") .
4480 " | ";
4482 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4483 hash_base=>$hash, file_name=>$diff->{'file'})},
4484 "blob") . " | ";
4485 if ($have_blame) {
4486 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4487 file_name=>$diff->{'file'})},
4488 "blame") . " | ";
4490 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4491 file_name=>$diff->{'file'})},
4492 "history");
4493 print "</td>\n";
4495 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4496 my %status_name = ('R' => 'moved', 'C' => 'copied');
4497 my $nstatus = $status_name{$diff->{'status'}};
4498 my $mode_chng = "";
4499 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4500 # mode also for directories, so we cannot use $to_mode_str
4501 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4503 print "<td>" .
4504 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4505 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4506 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4507 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4508 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4509 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4510 -class => "list"}, esc_path($diff->{'from_file'})) .
4511 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4512 "<td class=\"link\">";
4513 if ($action eq 'commitdiff') {
4514 # link to patch
4515 $patchno++;
4516 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4517 " | ";
4518 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4519 # "commit" view and modified file (not only pure rename or copy)
4520 print $cgi->a({-href => href(action=>"blobdiff",
4521 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4522 hash_base=>$hash, hash_parent_base=>$parent,
4523 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4524 "diff") .
4525 " | ";
4527 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4528 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4529 "blob") . " | ";
4530 if ($have_blame) {
4531 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4532 file_name=>$diff->{'to_file'})},
4533 "blame") . " | ";
4535 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4536 file_name=>$diff->{'to_file'})},
4537 "history");
4538 print "</td>\n";
4540 } # we should not encounter Unmerged (U) or Unknown (X) status
4541 print "</tr>\n";
4543 print "</tbody>" if $has_header;
4544 print "</table>\n";
4547 sub git_patchset_body {
4548 my ($fd, $difftree, $hash, @hash_parents) = @_;
4549 my ($hash_parent) = $hash_parents[0];
4551 my $is_combined = (@hash_parents > 1);
4552 my $patch_idx = 0;
4553 my $patch_number = 0;
4554 my $patch_line;
4555 my $diffinfo;
4556 my $to_name;
4557 my (%from, %to);
4559 print "<div class=\"patchset\">\n";
4561 # skip to first patch
4562 while ($patch_line = <$fd>) {
4563 chomp $patch_line;
4565 last if ($patch_line =~ m/^diff /);
4568 PATCH:
4569 while ($patch_line) {
4571 # parse "git diff" header line
4572 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4573 # $1 is from_name, which we do not use
4574 $to_name = unquote($2);
4575 $to_name =~ s!^b/!!;
4576 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4577 # $1 is 'cc' or 'combined', which we do not use
4578 $to_name = unquote($2);
4579 } else {
4580 $to_name = undef;
4583 # check if current patch belong to current raw line
4584 # and parse raw git-diff line if needed
4585 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4586 # this is continuation of a split patch
4587 print "<div class=\"patch cont\">\n";
4588 } else {
4589 # advance raw git-diff output if needed
4590 $patch_idx++ if defined $diffinfo;
4592 # read and prepare patch information
4593 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4595 # compact combined diff output can have some patches skipped
4596 # find which patch (using pathname of result) we are at now;
4597 if ($is_combined) {
4598 while ($to_name ne $diffinfo->{'to_file'}) {
4599 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4600 format_diff_cc_simplified($diffinfo, @hash_parents) .
4601 "</div>\n"; # class="patch"
4603 $patch_idx++;
4604 $patch_number++;
4606 last if $patch_idx > $#$difftree;
4607 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4611 # modifies %from, %to hashes
4612 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4614 # this is first patch for raw difftree line with $patch_idx index
4615 # we index @$difftree array from 0, but number patches from 1
4616 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4619 # git diff header
4620 #assert($patch_line =~ m/^diff /) if DEBUG;
4621 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4622 $patch_number++;
4623 # print "git diff" header
4624 print format_git_diff_header_line($patch_line, $diffinfo,
4625 \%from, \%to);
4627 # print extended diff header
4628 print "<div class=\"diff extended_header\">\n";
4629 EXTENDED_HEADER:
4630 while ($patch_line = <$fd>) {
4631 chomp $patch_line;
4633 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4635 print format_extended_diff_header_line($patch_line, $diffinfo,
4636 \%from, \%to);
4638 print "</div>\n"; # class="diff extended_header"
4640 # from-file/to-file diff header
4641 if (! $patch_line) {
4642 print "</div>\n"; # class="patch"
4643 last PATCH;
4645 next PATCH if ($patch_line =~ m/^diff /);
4646 #assert($patch_line =~ m/^---/) if DEBUG;
4648 my $last_patch_line = $patch_line;
4649 $patch_line = <$fd>;
4650 chomp $patch_line;
4651 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4653 print format_diff_from_to_header($last_patch_line, $patch_line,
4654 $diffinfo, \%from, \%to,
4655 @hash_parents);
4657 # the patch itself
4658 LINE:
4659 while ($patch_line = <$fd>) {
4660 chomp $patch_line;
4662 next PATCH if ($patch_line =~ m/^diff /);
4664 print format_diff_line($patch_line, \%from, \%to);
4667 } continue {
4668 print "</div>\n"; # class="patch"
4671 # for compact combined (--cc) format, with chunk and patch simplification
4672 # the patchset might be empty, but there might be unprocessed raw lines
4673 for (++$patch_idx if $patch_number > 0;
4674 $patch_idx < @$difftree;
4675 ++$patch_idx) {
4676 # read and prepare patch information
4677 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4679 # generate anchor for "patch" links in difftree / whatchanged part
4680 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4681 format_diff_cc_simplified($diffinfo, @hash_parents) .
4682 "</div>\n"; # class="patch"
4684 $patch_number++;
4687 if ($patch_number == 0) {
4688 if (@hash_parents > 1) {
4689 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4690 } else {
4691 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4695 print "</div>\n"; # class="patchset"
4698 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4700 # fills project list info (age, description, owner, forks) for each
4701 # project in the list, removing invalid projects from returned list
4702 # NOTE: modifies $projlist, but does not remove entries from it
4703 sub fill_project_list_info {
4704 my ($projlist, $check_forks) = @_;
4705 my @projects;
4707 my $show_ctags = gitweb_check_feature('ctags');
4708 PROJECT:
4709 foreach my $pr (@$projlist) {
4710 my (@activity) = git_get_last_activity($pr->{'path'});
4711 unless (@activity) {
4712 next PROJECT;
4714 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4715 if (!defined $pr->{'descr'}) {
4716 my $descr = git_get_project_description($pr->{'path'}) || "";
4717 $descr = to_utf8($descr);
4718 $pr->{'descr_long'} = $descr;
4719 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4721 if (!defined $pr->{'owner'}) {
4722 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4724 if ($check_forks) {
4725 my $pname = $pr->{'path'};
4726 if (($pname =~ s/\.git$//) &&
4727 ($pname !~ /\/$/) &&
4728 (-d "$projectroot/$pname")) {
4729 $pr->{'forks'} = "-d $projectroot/$pname";
4730 } else {
4731 $pr->{'forks'} = 0;
4734 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4735 push @projects, $pr;
4738 return @projects;
4741 # print 'sort by' <th> element, generating 'sort by $name' replay link
4742 # if that order is not selected
4743 sub print_sort_th {
4744 print format_sort_th(@_);
4747 sub format_sort_th {
4748 my ($name, $order, $header) = @_;
4749 my $sort_th = "";
4750 $header ||= ucfirst($name);
4752 if ($order eq $name) {
4753 $sort_th .= "<th>$header</th>\n";
4754 } else {
4755 $sort_th .= "<th>" .
4756 $cgi->a({-href => href(-replay=>1, order=>$name),
4757 -class => "header"}, $header) .
4758 "</th>\n";
4761 return $sort_th;
4764 sub git_project_list_body {
4765 # actually uses global variable $project
4766 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4768 my $check_forks = gitweb_check_feature('forks');
4769 my @projects = fill_project_list_info($projlist, $check_forks);
4771 $order ||= $default_projects_order;
4772 $from = 0 unless defined $from;
4773 $to = $#projects if (!defined $to || $#projects < $to);
4775 my %order_info = (
4776 project => { key => 'path', type => 'str' },
4777 descr => { key => 'descr_long', type => 'str' },
4778 owner => { key => 'owner', type => 'str' },
4779 age => { key => 'age', type => 'num' }
4781 my $oi = $order_info{$order};
4782 if ($oi->{'type'} eq 'str') {
4783 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4784 } else {
4785 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4788 my $show_ctags = gitweb_check_feature('ctags');
4789 if ($show_ctags) {
4790 my %ctags;
4791 foreach my $p (@projects) {
4792 foreach my $ct (keys %{$p->{'ctags'}}) {
4793 $ctags{$ct} += $p->{'ctags'}->{$ct};
4796 my $cloud = git_populate_project_tagcloud(\%ctags);
4797 print git_show_project_tagcloud($cloud, 64);
4800 print "<table class=\"project_list\">\n";
4801 unless ($no_header) {
4802 print "<tr>\n";
4803 if ($check_forks) {
4804 print "<th></th>\n";
4806 print_sort_th('project', $order, 'Project');
4807 print_sort_th('descr', $order, 'Description');
4808 print_sort_th('owner', $order, 'Owner');
4809 print_sort_th('age', $order, 'Last Change');
4810 print "<th></th>\n" . # for links
4811 "</tr>\n";
4813 my $alternate = 1;
4814 my $tagfilter = $cgi->param('by_tag');
4815 for (my $i = $from; $i <= $to; $i++) {
4816 my $pr = $projects[$i];
4818 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4819 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4820 and not $pr->{'descr_long'} =~ /$searchtext/;
4821 # Weed out forks or non-matching entries of search
4822 if ($check_forks) {
4823 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4824 $forkbase="^$forkbase" if $forkbase;
4825 next if not $searchtext and not $tagfilter and $show_ctags
4826 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4829 if ($alternate) {
4830 print "<tr class=\"dark\">\n";
4831 } else {
4832 print "<tr class=\"light\">\n";
4834 $alternate ^= 1;
4835 if ($check_forks) {
4836 print "<td>";
4837 if ($pr->{'forks'}) {
4838 print "<!-- $pr->{'forks'} -->\n";
4839 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4841 print "</td>\n";
4843 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4844 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4845 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4846 -class => "list", -title => $pr->{'descr_long'}},
4847 esc_html($pr->{'descr'})) . "</td>\n" .
4848 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4849 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4850 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4851 "<td class=\"link\">" .
4852 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4853 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4854 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4855 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4856 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4857 "</td>\n" .
4858 "</tr>\n";
4860 if (defined $extra) {
4861 print "<tr>\n";
4862 if ($check_forks) {
4863 print "<td></td>\n";
4865 print "<td colspan=\"5\">$extra</td>\n" .
4866 "</tr>\n";
4868 print "</table>\n";
4871 sub git_log_body {
4872 # uses global variable $project
4873 my ($commitlist, $from, $to, $refs, $extra) = @_;
4875 $from = 0 unless defined $from;
4876 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4878 for (my $i = 0; $i <= $to; $i++) {
4879 my %co = %{$commitlist->[$i]};
4880 next if !%co;
4881 my $commit = $co{'id'};
4882 my $ref = format_ref_marker($refs, $commit);
4883 my %ad = parse_date($co{'author_epoch'});
4884 git_print_header_div('commit',
4885 "<span class=\"age\">$co{'age_string'}</span>" .
4886 esc_html($co{'title'}) . $ref,
4887 $commit);
4888 print "<div class=\"title_text\">\n" .
4889 "<div class=\"log_link\">\n" .
4890 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4891 " | " .
4892 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4893 " | " .
4894 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4895 "<br/>\n" .
4896 "</div>\n";
4897 git_print_authorship(\%co, -tag => 'span');
4898 print "<br/>\n</div>\n";
4900 print "<div class=\"log_body\">\n";
4901 git_print_log($co{'comment'}, -final_empty_line=> 1);
4902 print "</div>\n";
4904 if ($extra) {
4905 print "<div class=\"page_nav\">\n";
4906 print "$extra\n";
4907 print "</div>\n";
4911 sub git_shortlog_body {
4912 # uses global variable $project
4913 my ($commitlist, $from, $to, $refs, $extra) = @_;
4915 $from = 0 unless defined $from;
4916 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4918 print "<table class=\"shortlog\">\n";
4919 my $alternate = 1;
4920 for (my $i = $from; $i <= $to; $i++) {
4921 my %co = %{$commitlist->[$i]};
4922 my $commit = $co{'id'};
4923 my $ref = format_ref_marker($refs, $commit);
4924 if ($alternate) {
4925 print "<tr class=\"dark\">\n";
4926 } else {
4927 print "<tr class=\"light\">\n";
4929 $alternate ^= 1;
4930 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4931 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4932 format_author_html('td', \%co, 10) . "<td>";
4933 print format_subject_html($co{'title'}, $co{'title_short'},
4934 href(action=>"commit", hash=>$commit), $ref);
4935 print "</td>\n" .
4936 "<td class=\"link\">" .
4937 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4938 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4939 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4940 my $snapshot_links = format_snapshot_links($commit);
4941 if (defined $snapshot_links) {
4942 print " | " . $snapshot_links;
4944 print "</td>\n" .
4945 "</tr>\n";
4947 if (defined $extra) {
4948 print "<tr>\n" .
4949 "<td colspan=\"4\">$extra</td>\n" .
4950 "</tr>\n";
4952 print "</table>\n";
4955 sub git_history_body {
4956 # Warning: assumes constant type (blob or tree) during history
4957 my ($commitlist, $from, $to, $refs, $extra,
4958 $file_name, $file_hash, $ftype) = @_;
4960 $from = 0 unless defined $from;
4961 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4963 print "<table class=\"history\">\n";
4964 my $alternate = 1;
4965 for (my $i = $from; $i <= $to; $i++) {
4966 my %co = %{$commitlist->[$i]};
4967 if (!%co) {
4968 next;
4970 my $commit = $co{'id'};
4972 my $ref = format_ref_marker($refs, $commit);
4974 if ($alternate) {
4975 print "<tr class=\"dark\">\n";
4976 } else {
4977 print "<tr class=\"light\">\n";
4979 $alternate ^= 1;
4980 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4981 # shortlog: format_author_html('td', \%co, 10)
4982 format_author_html('td', \%co, 15, 3) . "<td>";
4983 # originally git_history used chop_str($co{'title'}, 50)
4984 print format_subject_html($co{'title'}, $co{'title_short'},
4985 href(action=>"commit", hash=>$commit), $ref);
4986 print "</td>\n" .
4987 "<td class=\"link\">" .
4988 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4989 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4991 if ($ftype eq 'blob') {
4992 my $blob_current = $file_hash;
4993 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4994 if (defined $blob_current && defined $blob_parent &&
4995 $blob_current ne $blob_parent) {
4996 print " | " .
4997 $cgi->a({-href => href(action=>"blobdiff",
4998 hash=>$blob_current, hash_parent=>$blob_parent,
4999 hash_base=>$hash_base, hash_parent_base=>$commit,
5000 file_name=>$file_name)},
5001 "diff to current");
5004 print "</td>\n" .
5005 "</tr>\n";
5007 if (defined $extra) {
5008 print "<tr>\n" .
5009 "<td colspan=\"4\">$extra</td>\n" .
5010 "</tr>\n";
5012 print "</table>\n";
5015 sub git_tags_body {
5016 # uses global variable $project
5017 my ($taglist, $from, $to, $extra) = @_;
5018 $from = 0 unless defined $from;
5019 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5021 print "<table class=\"tags\">\n";
5022 my $alternate = 1;
5023 for (my $i = $from; $i <= $to; $i++) {
5024 my $entry = $taglist->[$i];
5025 my %tag = %$entry;
5026 my $comment = $tag{'subject'};
5027 my $comment_short;
5028 if (defined $comment) {
5029 $comment_short = chop_str($comment, 30, 5);
5031 if ($alternate) {
5032 print "<tr class=\"dark\">\n";
5033 } else {
5034 print "<tr class=\"light\">\n";
5036 $alternate ^= 1;
5037 if (defined $tag{'age'}) {
5038 print "<td><i>$tag{'age'}</i></td>\n";
5039 } else {
5040 print "<td></td>\n";
5042 print "<td>" .
5043 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5044 -class => "list name"}, esc_html($tag{'name'})) .
5045 "</td>\n" .
5046 "<td>";
5047 if (defined $comment) {
5048 print format_subject_html($comment, $comment_short,
5049 href(action=>"tag", hash=>$tag{'id'}));
5051 print "</td>\n" .
5052 "<td class=\"selflink\">";
5053 if ($tag{'type'} eq "tag") {
5054 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5055 } else {
5056 print "&nbsp;";
5058 print "</td>\n" .
5059 "<td class=\"link\">" . " | " .
5060 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5061 if ($tag{'reftype'} eq "commit") {
5062 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5063 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5064 } elsif ($tag{'reftype'} eq "blob") {
5065 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5067 print "</td>\n" .
5068 "</tr>";
5070 if (defined $extra) {
5071 print "<tr>\n" .
5072 "<td colspan=\"5\">$extra</td>\n" .
5073 "</tr>\n";
5075 print "</table>\n";
5078 sub git_heads_body {
5079 # uses global variable $project
5080 my ($headlist, $head, $from, $to, $extra) = @_;
5081 $from = 0 unless defined $from;
5082 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5084 print "<table class=\"heads\">\n";
5085 my $alternate = 1;
5086 for (my $i = $from; $i <= $to; $i++) {
5087 my $entry = $headlist->[$i];
5088 my %ref = %$entry;
5089 my $curr = $ref{'id'} eq $head;
5090 if ($alternate) {
5091 print "<tr class=\"dark\">\n";
5092 } else {
5093 print "<tr class=\"light\">\n";
5095 $alternate ^= 1;
5096 print "<td><i>$ref{'age'}</i></td>\n" .
5097 ($curr ? "<td class=\"current_head\">" : "<td>") .
5098 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5099 -class => "list name"},esc_html($ref{'name'})) .
5100 "</td>\n" .
5101 "<td class=\"link\">" .
5102 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5103 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5104 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
5105 "</td>\n" .
5106 "</tr>";
5108 if (defined $extra) {
5109 print "<tr>\n" .
5110 "<td colspan=\"3\">$extra</td>\n" .
5111 "</tr>\n";
5113 print "</table>\n";
5116 sub git_search_grep_body {
5117 my ($commitlist, $from, $to, $extra) = @_;
5118 $from = 0 unless defined $from;
5119 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5121 print "<table class=\"commit_search\">\n";
5122 my $alternate = 1;
5123 for (my $i = $from; $i <= $to; $i++) {
5124 my %co = %{$commitlist->[$i]};
5125 if (!%co) {
5126 next;
5128 my $commit = $co{'id'};
5129 if ($alternate) {
5130 print "<tr class=\"dark\">\n";
5131 } else {
5132 print "<tr class=\"light\">\n";
5134 $alternate ^= 1;
5135 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5136 format_author_html('td', \%co, 15, 5) .
5137 "<td>" .
5138 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5139 -class => "list subject"},
5140 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5141 my $comment = $co{'comment'};
5142 foreach my $line (@$comment) {
5143 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5144 my ($lead, $match, $trail) = ($1, $2, $3);
5145 $match = chop_str($match, 70, 5, 'center');
5146 my $contextlen = int((80 - length($match))/2);
5147 $contextlen = 30 if ($contextlen > 30);
5148 $lead = chop_str($lead, $contextlen, 10, 'left');
5149 $trail = chop_str($trail, $contextlen, 10, 'right');
5151 $lead = esc_html($lead);
5152 $match = esc_html($match);
5153 $trail = esc_html($trail);
5155 print "$lead<span class=\"match\">$match</span>$trail<br />";
5158 print "</td>\n" .
5159 "<td class=\"link\">" .
5160 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5161 " | " .
5162 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5163 " | " .
5164 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5165 print "</td>\n" .
5166 "</tr>\n";
5168 if (defined $extra) {
5169 print "<tr>\n" .
5170 "<td colspan=\"3\">$extra</td>\n" .
5171 "</tr>\n";
5173 print "</table>\n";
5176 ## ======================================================================
5177 ## ======================================================================
5178 ## actions
5180 sub git_project_list {
5181 my $order = $input_params{'order'};
5182 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5183 die_error(400, "Unknown order parameter");
5186 my @list = git_get_projects_list();
5187 if (!@list) {
5188 die_error(404, "No projects found");
5191 git_header_html();
5192 if (defined $home_text && -f $home_text) {
5193 print "<div class=\"index_include\">\n";
5194 insert_file($home_text);
5195 print "</div>\n";
5197 print $cgi->startform(-method => "get") .
5198 "<p class=\"projsearch\">Search:\n" .
5199 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5200 "</p>" .
5201 $cgi->end_form() . "\n";
5202 git_project_list_body(\@list, $order);
5203 git_footer_html();
5206 sub git_forks {
5207 my $order = $input_params{'order'};
5208 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5209 die_error(400, "Unknown order parameter");
5212 my @list = git_get_projects_list($project);
5213 if (!@list) {
5214 die_error(404, "No forks found");
5217 git_header_html();
5218 git_print_page_nav('','');
5219 git_print_header_div('summary', "$project forks");
5220 git_project_list_body(\@list, $order);
5221 git_footer_html();
5224 sub git_project_index {
5225 my @projects = git_get_projects_list($project);
5227 print $cgi->header(
5228 -type => 'text/plain',
5229 -charset => 'utf-8',
5230 -content_disposition => 'inline; filename="index.aux"');
5232 foreach my $pr (@projects) {
5233 if (!exists $pr->{'owner'}) {
5234 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5237 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5238 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5239 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5240 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5241 $path =~ s/ /\+/g;
5242 $owner =~ s/ /\+/g;
5244 print "$path $owner\n";
5248 sub git_summary {
5249 my $descr = git_get_project_description($project) || "none";
5250 my %co = parse_commit("HEAD");
5251 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5252 my $head = $co{'id'};
5254 my $owner = git_get_project_owner($project);
5256 my $refs = git_get_references();
5257 # These get_*_list functions return one more to allow us to see if
5258 # there are more ...
5259 my @taglist = git_get_tags_list(16);
5260 my @headlist = git_get_heads_list(16);
5261 my @forklist;
5262 my $check_forks = gitweb_check_feature('forks');
5264 if ($check_forks) {
5265 @forklist = git_get_projects_list($project);
5268 git_header_html();
5269 git_print_page_nav('summary','', $head);
5271 print "<div class=\"title\">&nbsp;</div>\n";
5272 print "<table class=\"projects_list\">\n" .
5273 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5274 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5275 if (defined $cd{'rfc2822'}) {
5276 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5279 # use per project git URL list in $projectroot/$project/cloneurl
5280 # or make project git URL from git base URL and project name
5281 my $url_tag = "URL";
5282 my @url_list = git_get_project_url_list($project);
5283 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5284 foreach my $git_url (@url_list) {
5285 next unless $git_url;
5286 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5287 $url_tag = "";
5290 # Tag cloud
5291 my $show_ctags = gitweb_check_feature('ctags');
5292 if ($show_ctags) {
5293 my $ctags = git_get_project_ctags($project);
5294 my $cloud = git_populate_project_tagcloud($ctags);
5295 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5296 print "</td>\n<td>" unless %$ctags;
5297 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5298 print "</td>\n<td>" if %$ctags;
5299 print git_show_project_tagcloud($cloud, 48);
5300 print "</td></tr>";
5303 print "</table>\n";
5305 # If XSS prevention is on, we don't include README.html.
5306 # TODO: Allow a readme in some safe format.
5307 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5308 print "<div class=\"title\">readme</div>\n" .
5309 "<div class=\"readme\">\n";
5310 insert_file("$projectroot/$project/README.html");
5311 print "\n</div>\n"; # class="readme"
5314 # we need to request one more than 16 (0..15) to check if
5315 # those 16 are all
5316 my @commitlist = $head ? parse_commits($head, 17) : ();
5317 if (@commitlist) {
5318 git_print_header_div('shortlog');
5319 git_shortlog_body(\@commitlist, 0, 15, $refs,
5320 $#commitlist <= 15 ? undef :
5321 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5324 if (@taglist) {
5325 git_print_header_div('tags');
5326 git_tags_body(\@taglist, 0, 15,
5327 $#taglist <= 15 ? undef :
5328 $cgi->a({-href => href(action=>"tags")}, "..."));
5331 if (@headlist) {
5332 git_print_header_div('heads');
5333 git_heads_body(\@headlist, $head, 0, 15,
5334 $#headlist <= 15 ? undef :
5335 $cgi->a({-href => href(action=>"heads")}, "..."));
5338 if (@forklist) {
5339 git_print_header_div('forks');
5340 git_project_list_body(\@forklist, 'age', 0, 15,
5341 $#forklist <= 15 ? undef :
5342 $cgi->a({-href => href(action=>"forks")}, "..."),
5343 'no_header');
5346 git_footer_html();
5349 sub git_tag {
5350 my %tag = parse_tag($hash);
5352 if (! %tag) {
5353 die_error(404, "Unknown tag object");
5356 my $head = git_get_head_hash($project);
5357 git_header_html();
5358 git_print_page_nav('','', $head,undef,$head);
5359 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5360 print "<div class=\"title_text\">\n" .
5361 "<table class=\"object_header\">\n" .
5362 "<tr>\n" .
5363 "<td>object</td>\n" .
5364 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5365 $tag{'object'}) . "</td>\n" .
5366 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5367 $tag{'type'}) . "</td>\n" .
5368 "</tr>\n";
5369 if (defined($tag{'author'})) {
5370 git_print_authorship_rows(\%tag, 'author');
5372 print "</table>\n\n" .
5373 "</div>\n";
5374 print "<div class=\"page_body\">";
5375 my $comment = $tag{'comment'};
5376 foreach my $line (@$comment) {
5377 chomp $line;
5378 print esc_html($line, -nbsp=>1) . "<br/>\n";
5380 print "</div>\n";
5381 git_footer_html();
5384 sub git_blame_common {
5385 my $format = shift || 'porcelain';
5386 if ($format eq 'porcelain' && $cgi->param('js') &&
5387 !$caching_enabled) {
5388 $format = 'incremental';
5389 $action = 'blame_incremental'; # for page title etc
5392 # permissions
5393 gitweb_check_feature('blame')
5394 or die_error(403, "Blame view not allowed");
5396 # error checking
5397 die_error(400, "No file name given") unless $file_name;
5398 $hash_base ||= git_get_head_hash($project);
5399 die_error(404, "Couldn't find base commit") unless $hash_base;
5400 my %co = parse_commit($hash_base)
5401 or die_error(404, "Commit not found");
5402 my $ftype = "blob";
5403 if (!defined $hash) {
5404 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5405 or die_error(404, "Error looking up file");
5406 } else {
5407 $ftype = git_get_type($hash);
5408 if ($ftype !~ "blob") {
5409 die_error(400, "Object is not a blob");
5413 my $fd;
5414 if ($format eq 'incremental') {
5415 # get file contents (as base)
5416 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5417 or die_error(500, "Open git-cat-file failed");
5418 } elsif ($format eq 'data') {
5419 # run git-blame --incremental
5420 open $fd, "-|", git_cmd(), "blame", "--incremental",
5421 $hash_base, "--", $file_name
5422 or die_error(500, "Open git-blame --incremental failed");
5423 } else {
5424 # run git-blame --porcelain
5425 open $fd, "-|", git_cmd(), "blame", '-p',
5426 $hash_base, '--', $file_name
5427 or die_error(500, "Open git-blame --porcelain failed");
5430 # incremental blame data returns early
5431 if ($format eq 'data') {
5432 print $cgi->header(
5433 -type=>"text/plain", -charset => "utf-8",
5434 -status=> "200 OK");
5435 local $| = 1; # output autoflush
5436 print while <$fd>;
5437 close $fd
5438 or print "ERROR $!\n";
5440 print 'END';
5441 if (!$caching_enabled &&
5442 defined $t0 && gitweb_check_feature('timed')) {
5443 print ' '.
5444 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5445 ' '.$number_of_git_cmds;
5447 print "\n";
5449 return;
5452 # page header
5453 git_header_html();
5454 my $formats_nav =
5455 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5456 "blob") .
5457 " | ";
5458 if ($format eq 'incremental') {
5459 $formats_nav .=
5460 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5461 "blame") . " (non-incremental)";
5462 } elsif (!$caching_enabled) {
5463 $formats_nav .=
5464 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5465 "blame") . " (incremental)";
5467 $formats_nav .=
5468 " | " .
5469 $cgi->a({-href => href(action=>"history", -replay=>1)},
5470 "history") .
5471 " | " .
5472 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5473 "HEAD");
5474 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5475 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5476 git_print_page_path($file_name, $ftype, $hash_base);
5478 # page body
5479 if ($format eq 'incremental') {
5480 print "<noscript>\n<div class=\"error\"><center><b>\n".
5481 "This page requires JavaScript to run.\n Use ".
5482 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5483 'this page').
5484 " instead.\n".
5485 "</b></center></div>\n</noscript>\n";
5487 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5490 print qq!<div class="page_body">\n!;
5491 print qq!<div id="progress_info">... / ...</div>\n!
5492 if ($format eq 'incremental');
5493 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5494 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5495 qq!<thead>\n!.
5496 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5497 qq!</thead>\n!.
5498 qq!<tbody>\n!;
5500 my @rev_color = qw(light dark);
5501 my $num_colors = scalar(@rev_color);
5502 my $current_color = 0;
5504 if ($format eq 'incremental') {
5505 my $color_class = $rev_color[$current_color];
5507 #contents of a file
5508 my $linenr = 0;
5509 LINE:
5510 while (my $line = <$fd>) {
5511 chomp $line;
5512 $linenr++;
5514 print qq!<tr id="l$linenr" class="$color_class">!.
5515 qq!<td class="sha1"><a href=""> </a></td>!.
5516 qq!<td class="linenr">!.
5517 qq!<a class="linenr" href="">$linenr</a></td>!;
5518 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5519 print qq!</tr>\n!;
5522 } else { # porcelain, i.e. ordinary blame
5523 my %metainfo = (); # saves information about commits
5525 # blame data
5526 LINE:
5527 while (my $line = <$fd>) {
5528 chomp $line;
5529 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5530 # no <lines in group> for subsequent lines in group of lines
5531 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5532 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5533 if (!exists $metainfo{$full_rev}) {
5534 $metainfo{$full_rev} = { 'nprevious' => 0 };
5536 my $meta = $metainfo{$full_rev};
5537 my $data;
5538 while ($data = <$fd>) {
5539 chomp $data;
5540 last if ($data =~ s/^\t//); # contents of line
5541 if ($data =~ /^(\S+)(?: (.*))?$/) {
5542 $meta->{$1} = $2 unless exists $meta->{$1};
5544 if ($data =~ /^previous /) {
5545 $meta->{'nprevious'}++;
5548 my $short_rev = substr($full_rev, 0, 8);
5549 my $author = $meta->{'author'};
5550 my %date =
5551 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5552 my $date = $date{'iso-tz'};
5553 if ($group_size) {
5554 $current_color = ($current_color + 1) % $num_colors;
5556 my $tr_class = $rev_color[$current_color];
5557 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5558 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5559 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5560 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5561 if ($group_size) {
5562 print "<td class=\"sha1\"";
5563 print " title=\"". esc_html($author) . ", $date\"";
5564 print " rowspan=\"$group_size\"" if ($group_size > 1);
5565 print ">";
5566 print $cgi->a({-href => href(action=>"commit",
5567 hash=>$full_rev,
5568 file_name=>$file_name)},
5569 esc_html($short_rev));
5570 if ($group_size >= 2) {
5571 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5572 if (@author_initials) {
5573 print "<br />" .
5574 esc_html(join('', @author_initials));
5575 # or join('.', ...)
5578 print "</td>\n";
5580 # 'previous' <sha1 of parent commit> <filename at commit>
5581 if (exists $meta->{'previous'} &&
5582 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5583 $meta->{'parent'} = $1;
5584 $meta->{'file_parent'} = unquote($2);
5586 my $linenr_commit =
5587 exists($meta->{'parent'}) ?
5588 $meta->{'parent'} : $full_rev;
5589 my $linenr_filename =
5590 exists($meta->{'file_parent'}) ?
5591 $meta->{'file_parent'} : unquote($meta->{'filename'});
5592 my $blamed = href(action => 'blame',
5593 file_name => $linenr_filename,
5594 hash_base => $linenr_commit);
5595 print "<td class=\"linenr\">";
5596 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5597 -class => "linenr" },
5598 esc_html($lineno));
5599 print "</td>";
5600 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5601 print "</tr>\n";
5602 } # end while
5606 # footer
5607 print "</tbody>\n".
5608 "</table>\n"; # class="blame"
5609 print "</div>\n"; # class="blame_body"
5610 close $fd
5611 or print "Reading blob failed\n";
5613 git_footer_html();
5616 sub git_blame {
5617 git_blame_common();
5620 sub git_blame_incremental {
5621 git_blame_common(!$caching_enabled ? 'incremental' : undef);
5624 sub git_blame_data {
5625 git_blame_common('data');
5628 sub git_tags {
5629 my $head = git_get_head_hash($project);
5630 git_header_html();
5631 git_print_page_nav('','', $head,undef,$head);
5632 git_print_header_div('summary', $project);
5634 my @tagslist = git_get_tags_list();
5635 if (@tagslist) {
5636 git_tags_body(\@tagslist);
5638 git_footer_html();
5641 sub git_heads {
5642 my $head = git_get_head_hash($project);
5643 git_header_html();
5644 git_print_page_nav('','', $head,undef,$head);
5645 git_print_header_div('summary', $project);
5647 my @headslist = git_get_heads_list();
5648 if (@headslist) {
5649 git_heads_body(\@headslist, $head);
5651 git_footer_html();
5654 sub git_blob_plain {
5655 my $type = shift;
5656 my $expires;
5658 if (!defined $hash) {
5659 if (defined $file_name) {
5660 my $base = $hash_base || git_get_head_hash($project);
5661 $hash = git_get_hash_by_path($base, $file_name, "blob")
5662 or die_error(404, "Cannot find file");
5663 } else {
5664 die_error(400, "No file name defined");
5666 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5667 # blobs defined by non-textual hash id's can be cached
5668 $expires = "+1d";
5671 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5672 or die_error(500, "Open git-cat-file blob '$hash' failed");
5674 # content-type (can include charset)
5675 $type = blob_contenttype($fd, $file_name, $type);
5677 # "save as" filename, even when no $file_name is given
5678 my $save_as = "$hash";
5679 if (defined $file_name) {
5680 $save_as = $file_name;
5681 } elsif ($type =~ m/^text\//) {
5682 $save_as .= '.txt';
5685 # With XSS prevention on, blobs of all types except a few known safe
5686 # ones are served with "Content-Disposition: attachment" to make sure
5687 # they don't run in our security domain. For certain image types,
5688 # blob view writes an <img> tag referring to blob_plain view, and we
5689 # want to be sure not to break that by serving the image as an
5690 # attachment (though Firefox 3 doesn't seem to care).
5691 my $sandbox = $prevent_xss &&
5692 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5694 print $cgi->header(
5695 -type => $type,
5696 -expires => $expires,
5697 -content_disposition =>
5698 ($sandbox ? 'attachment' : 'inline')
5699 . '; filename="' . $save_as . '"');
5700 local $/ = undef;
5701 binmode STDOUT, ':raw';
5702 print <$fd>;
5703 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5704 close $fd;
5707 sub git_blob {
5708 my $expires;
5710 if (!defined $hash) {
5711 if (defined $file_name) {
5712 my $base = $hash_base || git_get_head_hash($project);
5713 $hash = git_get_hash_by_path($base, $file_name, "blob")
5714 or die_error(404, "Cannot find file");
5715 } else {
5716 die_error(400, "No file name defined");
5718 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5719 # blobs defined by non-textual hash id's can be cached
5720 $expires = "+1d";
5723 my $have_blame = gitweb_check_feature('blame');
5724 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5725 or die_error(500, "Couldn't cat $file_name, $hash");
5726 my $mimetype = blob_mimetype($fd, $file_name);
5727 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5728 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5729 close $fd;
5730 return git_blob_plain($mimetype);
5732 # we can have blame only for text/* mimetype
5733 $have_blame &&= ($mimetype =~ m!^text/!);
5735 my $highlight = gitweb_check_feature('highlight');
5736 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5737 $fd = run_highlighter($fd, $highlight, $syntax)
5738 if $syntax;
5740 git_header_html(undef, $expires);
5741 my $formats_nav = '';
5742 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5743 if (defined $file_name) {
5744 if ($have_blame) {
5745 $formats_nav .=
5746 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5747 "blame") .
5748 " | ";
5750 $formats_nav .=
5751 $cgi->a({-href => href(action=>"history", -replay=>1)},
5752 "history") .
5753 " | " .
5754 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5755 "raw") .
5756 " | " .
5757 $cgi->a({-href => href(action=>"blob",
5758 hash_base=>"HEAD", file_name=>$file_name)},
5759 "HEAD");
5760 } else {
5761 $formats_nav .=
5762 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5763 "raw");
5765 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5766 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5767 } else {
5768 print "<div class=\"page_nav\">\n" .
5769 "<br/><br/></div>\n" .
5770 "<div class=\"title\">$hash</div>\n";
5772 git_print_page_path($file_name, "blob", $hash_base);
5773 print "<div class=\"page_body\">\n";
5774 if ($mimetype =~ m!^image/!) {
5775 print qq!<img type="$mimetype"!;
5776 if ($file_name) {
5777 print qq! alt="$file_name" title="$file_name"!;
5779 print qq! src="! .
5780 href(action=>"blob_plain", hash=>$hash,
5781 hash_base=>$hash_base, file_name=>$file_name) .
5782 qq!" />\n!;
5783 } else {
5784 my $nr;
5785 while (my $line = <$fd>) {
5786 chomp $line;
5787 $nr++;
5788 $line = untabify($line);
5789 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5790 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5793 close $fd
5794 or print "Reading blob failed.\n";
5795 print "</div>";
5796 git_footer_html();
5799 sub git_tree {
5800 if (!defined $hash_base) {
5801 $hash_base = "HEAD";
5803 if (!defined $hash) {
5804 if (defined $file_name) {
5805 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5806 } else {
5807 $hash = $hash_base;
5810 die_error(404, "No such tree") unless defined($hash);
5812 my $show_sizes = gitweb_check_feature('show-sizes');
5813 my $have_blame = gitweb_check_feature('blame');
5815 my @entries = ();
5817 local $/ = "\0";
5818 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5819 ($show_sizes ? '-l' : ()), @extra_options, $hash
5820 or die_error(500, "Open git-ls-tree failed");
5821 @entries = map { chomp; $_ } <$fd>;
5822 close $fd
5823 or die_error(404, "Reading tree failed");
5826 my $refs = git_get_references();
5827 my $ref = format_ref_marker($refs, $hash_base);
5828 git_header_html();
5829 my $basedir = '';
5830 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5831 my @views_nav = ();
5832 if (defined $file_name) {
5833 push @views_nav,
5834 $cgi->a({-href => href(action=>"history", -replay=>1)},
5835 "history"),
5836 $cgi->a({-href => href(action=>"tree",
5837 hash_base=>"HEAD", file_name=>$file_name)},
5838 "HEAD"),
5840 my $snapshot_links = format_snapshot_links($hash);
5841 if (defined $snapshot_links) {
5842 # FIXME: Should be available when we have no hash base as well.
5843 push @views_nav, $snapshot_links;
5845 git_print_page_nav('tree','', $hash_base, undef, undef,
5846 join(' | ', @views_nav));
5847 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5848 } else {
5849 undef $hash_base;
5850 print "<div class=\"page_nav\">\n";
5851 print "<br/><br/></div>\n";
5852 print "<div class=\"title\">$hash</div>\n";
5854 if (defined $file_name) {
5855 $basedir = $file_name;
5856 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5857 $basedir .= '/';
5859 git_print_page_path($file_name, 'tree', $hash_base);
5861 print "<div class=\"page_body\">\n";
5862 print "<table class=\"tree\">\n";
5863 my $alternate = 1;
5864 # '..' (top directory) link if possible
5865 if (defined $hash_base &&
5866 defined $file_name && $file_name =~ m![^/]+$!) {
5867 if ($alternate) {
5868 print "<tr class=\"dark\">\n";
5869 } else {
5870 print "<tr class=\"light\">\n";
5872 $alternate ^= 1;
5874 my $up = $file_name;
5875 $up =~ s!/?[^/]+$!!;
5876 undef $up unless $up;
5877 # based on git_print_tree_entry
5878 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5879 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5880 print '<td class="list">';
5881 print $cgi->a({-href => href(action=>"tree",
5882 hash_base=>$hash_base,
5883 file_name=>$up)},
5884 "..");
5885 print "</td>\n";
5886 print "<td class=\"link\"></td>\n";
5888 print "</tr>\n";
5890 foreach my $line (@entries) {
5891 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5893 if ($alternate) {
5894 print "<tr class=\"dark\">\n";
5895 } else {
5896 print "<tr class=\"light\">\n";
5898 $alternate ^= 1;
5900 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5902 print "</tr>\n";
5904 print "</table>\n" .
5905 "</div>";
5906 git_footer_html();
5909 sub snapshot_name {
5910 my ($project, $hash) = @_;
5912 # path/to/project.git -> project
5913 # path/to/project/.git -> project
5914 my $name = to_utf8($project);
5915 $name =~ s,([^/])/*\.git$,$1,;
5916 $name = basename($name);
5917 # sanitize name
5918 $name =~ s/[[:cntrl:]]/?/g;
5920 my $ver = $hash;
5921 if ($hash =~ /^[0-9a-fA-F]+$/) {
5922 # shorten SHA-1 hash
5923 my $full_hash = git_get_full_hash($project, $hash);
5924 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5925 $ver = git_get_short_hash($project, $hash);
5927 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5928 # tags don't need shortened SHA-1 hash
5929 $ver = $1;
5930 } else {
5931 # branches and other need shortened SHA-1 hash
5932 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5933 $ver = $1;
5935 $ver .= '-' . git_get_short_hash($project, $hash);
5937 # in case of hierarchical branch names
5938 $ver =~ s!/!.!g;
5940 # name = project-version_string
5941 $name = "$name-$ver";
5943 return wantarray ? ($name, $name) : $name;
5946 sub git_snapshot {
5947 my $format = $input_params{'snapshot_format'};
5948 if (!@snapshot_fmts) {
5949 die_error(403, "Snapshots not allowed");
5951 # default to first supported snapshot format
5952 $format ||= $snapshot_fmts[0];
5953 if ($format !~ m/^[a-z0-9]+$/) {
5954 die_error(400, "Invalid snapshot format parameter");
5955 } elsif (!exists($known_snapshot_formats{$format})) {
5956 die_error(400, "Unknown snapshot format");
5957 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5958 die_error(403, "Snapshot format not allowed");
5959 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5960 die_error(403, "Unsupported snapshot format");
5963 my $type = git_get_type("$hash^{}");
5964 if (!$type) {
5965 die_error(404, 'Object does not exist');
5966 } elsif ($type eq 'blob') {
5967 die_error(400, 'Object is not a tree-ish');
5970 my ($name, $prefix) = snapshot_name($project, $hash);
5971 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
5972 my $cmd = quote_command(
5973 git_cmd(), 'archive',
5974 "--format=$known_snapshot_formats{$format}{'format'}",
5975 "--prefix=$prefix/", $hash);
5976 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5977 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5980 $filename =~ s/(["\\])/\\$1/g;
5981 print $cgi->header(
5982 -type => $known_snapshot_formats{$format}{'type'},
5983 -content_disposition => 'inline; filename="' . $filename . '"',
5984 -status => '200 OK');
5986 open my $fd, "-|", $cmd
5987 or die_error(500, "Execute git-archive failed");
5988 binmode STDOUT, ':raw';
5989 print <$fd>;
5990 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5991 close $fd;
5994 sub git_log_generic {
5995 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
5997 my $head = git_get_head_hash($project);
5998 if (!defined $base) {
5999 $base = $head;
6001 if (!defined $page) {
6002 $page = 0;
6004 my $refs = git_get_references();
6006 my $commit_hash = $base;
6007 if (defined $parent) {
6008 $commit_hash = "$parent..$base";
6010 my @commitlist =
6011 parse_commits($commit_hash, 101, (100 * $page),
6012 defined $file_name ? ($file_name, "--full-history") : ());
6014 my $ftype;
6015 if (!defined $file_hash && defined $file_name) {
6016 # some commits could have deleted file in question,
6017 # and not have it in tree, but one of them has to have it
6018 for (my $i = 0; $i < @commitlist; $i++) {
6019 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6020 last if defined $file_hash;
6023 if (defined $file_hash) {
6024 $ftype = git_get_type($file_hash);
6026 if (defined $file_name && !defined $ftype) {
6027 die_error(500, "Unknown type of object");
6029 my %co;
6030 if (defined $file_name) {
6031 %co = parse_commit($base)
6032 or die_error(404, "Unknown commit object");
6036 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6037 my $next_link = '';
6038 if ($#commitlist >= 100) {
6039 $next_link =
6040 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6041 -accesskey => "n", -title => "Alt-n"}, "next");
6043 my $patch_max = gitweb_get_feature('patches');
6044 if ($patch_max && !defined $file_name) {
6045 if ($patch_max < 0 || @commitlist <= $patch_max) {
6046 $paging_nav .= " &sdot; " .
6047 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6048 "patches");
6052 git_header_html();
6053 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6054 if (defined $file_name) {
6055 git_print_header_div('commit', esc_html($co{'title'}), $base);
6056 } else {
6057 git_print_header_div('summary', $project)
6059 git_print_page_path($file_name, $ftype, $hash_base)
6060 if (defined $file_name);
6062 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6063 $file_name, $file_hash, $ftype);
6065 git_footer_html();
6068 sub git_log {
6069 git_log_generic('log', \&git_log_body,
6070 $hash, $hash_parent);
6073 sub git_commit {
6074 $hash ||= $hash_base || "HEAD";
6075 my %co = parse_commit($hash)
6076 or die_error(404, "Unknown commit object");
6078 my $parent = $co{'parent'};
6079 my $parents = $co{'parents'}; # listref
6081 # we need to prepare $formats_nav before any parameter munging
6082 my $formats_nav;
6083 if (!defined $parent) {
6084 # --root commitdiff
6085 $formats_nav .= '(initial)';
6086 } elsif (@$parents == 1) {
6087 # single parent commit
6088 $formats_nav .=
6089 '(parent: ' .
6090 $cgi->a({-href => href(action=>"commit",
6091 hash=>$parent)},
6092 esc_html(substr($parent, 0, 7))) .
6093 ')';
6094 } else {
6095 # merge commit
6096 $formats_nav .=
6097 '(merge: ' .
6098 join(' ', map {
6099 $cgi->a({-href => href(action=>"commit",
6100 hash=>$_)},
6101 esc_html(substr($_, 0, 7)));
6102 } @$parents ) .
6103 ')';
6105 if (gitweb_check_feature('patches') && @$parents <= 1) {
6106 $formats_nav .= " | " .
6107 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6108 "patch");
6111 if (!defined $parent) {
6112 $parent = "--root";
6114 my @difftree;
6115 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6116 @diff_opts,
6117 (@$parents <= 1 ? $parent : '-c'),
6118 $hash, "--"
6119 or die_error(500, "Open git-diff-tree failed");
6120 @difftree = map { chomp; $_ } <$fd>;
6121 close $fd or die_error(404, "Reading git-diff-tree failed");
6123 # non-textual hash id's can be cached
6124 my $expires;
6125 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6126 $expires = "+1d";
6128 my $refs = git_get_references();
6129 my $ref = format_ref_marker($refs, $co{'id'});
6131 git_header_html(undef, $expires);
6132 git_print_page_nav('commit', '',
6133 $hash, $co{'tree'}, $hash,
6134 $formats_nav);
6136 if (defined $co{'parent'}) {
6137 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6138 } else {
6139 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6141 print "<div class=\"title_text\">\n" .
6142 "<table class=\"object_header\">\n";
6143 git_print_authorship_rows(\%co);
6144 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6145 print "<tr>" .
6146 "<td>tree</td>" .
6147 "<td class=\"sha1\">" .
6148 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6149 class => "list"}, $co{'tree'}) .
6150 "</td>" .
6151 "<td class=\"link\">" .
6152 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6153 "tree");
6154 my $snapshot_links = format_snapshot_links($hash);
6155 if (defined $snapshot_links) {
6156 print " | " . $snapshot_links;
6158 print "</td>" .
6159 "</tr>\n";
6161 foreach my $par (@$parents) {
6162 print "<tr>" .
6163 "<td>parent</td>" .
6164 "<td class=\"sha1\">" .
6165 $cgi->a({-href => href(action=>"commit", hash=>$par),
6166 class => "list"}, $par) .
6167 "</td>" .
6168 "<td class=\"link\">" .
6169 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6170 " | " .
6171 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6172 "</td>" .
6173 "</tr>\n";
6175 print "</table>".
6176 "</div>\n";
6178 print "<div class=\"page_body\">\n";
6179 git_print_log($co{'comment'});
6180 print "</div>\n";
6182 git_difftree_body(\@difftree, $hash, @$parents);
6184 git_footer_html();
6187 sub git_object {
6188 # object is defined by:
6189 # - hash or hash_base alone
6190 # - hash_base and file_name
6191 my $type;
6193 # - hash or hash_base alone
6194 if ($hash || ($hash_base && !defined $file_name)) {
6195 my $object_id = $hash || $hash_base;
6197 open my $fd, "-|", quote_command(
6198 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6199 or die_error(404, "Object does not exist");
6200 $type = <$fd>;
6201 chomp $type;
6202 close $fd
6203 or die_error(404, "Object does not exist");
6205 # - hash_base and file_name
6206 } elsif ($hash_base && defined $file_name) {
6207 $file_name =~ s,/+$,,;
6209 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6210 or die_error(404, "Base object does not exist");
6212 # here errors should not hapen
6213 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6214 or die_error(500, "Open git-ls-tree failed");
6215 my $line = <$fd>;
6216 close $fd;
6218 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6219 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6220 die_error(404, "File or directory for given base does not exist");
6222 $type = $2;
6223 $hash = $3;
6224 } else {
6225 die_error(400, "Not enough information to find object");
6228 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6229 hash=>$hash, hash_base=>$hash_base,
6230 file_name=>$file_name),
6231 -status => '302 Found');
6234 sub git_blobdiff {
6235 my $format = shift || 'html';
6237 my $fd;
6238 my @difftree;
6239 my %diffinfo;
6240 my $expires;
6242 # preparing $fd and %diffinfo for git_patchset_body
6243 # new style URI
6244 if (defined $hash_base && defined $hash_parent_base) {
6245 if (defined $file_name) {
6246 # read raw output
6247 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6248 $hash_parent_base, $hash_base,
6249 "--", (defined $file_parent ? $file_parent : ()), $file_name
6250 or die_error(500, "Open git-diff-tree failed");
6251 @difftree = map { chomp; $_ } <$fd>;
6252 close $fd
6253 or die_error(404, "Reading git-diff-tree failed");
6254 @difftree
6255 or die_error(404, "Blob diff not found");
6257 } elsif (defined $hash &&
6258 $hash =~ /[0-9a-fA-F]{40}/) {
6259 # try to find filename from $hash
6261 # read filtered raw output
6262 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6263 $hash_parent_base, $hash_base, "--"
6264 or die_error(500, "Open git-diff-tree failed");
6265 @difftree =
6266 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6267 # $hash == to_id
6268 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6269 map { chomp; $_ } <$fd>;
6270 close $fd
6271 or die_error(404, "Reading git-diff-tree failed");
6272 @difftree
6273 or die_error(404, "Blob diff not found");
6275 } else {
6276 die_error(400, "Missing one of the blob diff parameters");
6279 if (@difftree > 1) {
6280 die_error(400, "Ambiguous blob diff specification");
6283 %diffinfo = parse_difftree_raw_line($difftree[0]);
6284 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6285 $file_name ||= $diffinfo{'to_file'};
6287 $hash_parent ||= $diffinfo{'from_id'};
6288 $hash ||= $diffinfo{'to_id'};
6290 # non-textual hash id's can be cached
6291 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6292 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6293 $expires = '+1d';
6296 # open patch output
6297 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6298 '-p', ($format eq 'html' ? "--full-index" : ()),
6299 $hash_parent_base, $hash_base,
6300 "--", (defined $file_parent ? $file_parent : ()), $file_name
6301 or die_error(500, "Open git-diff-tree failed");
6304 # old/legacy style URI -- not generated anymore since 1.4.3.
6305 if (!%diffinfo) {
6306 die_error('404 Not Found', "Missing one of the blob diff parameters")
6309 # header
6310 if ($format eq 'html') {
6311 my $formats_nav =
6312 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6313 "raw");
6314 git_header_html(undef, $expires);
6315 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6316 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6317 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6318 } else {
6319 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6320 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6322 if (defined $file_name) {
6323 git_print_page_path($file_name, "blob", $hash_base);
6324 } else {
6325 print "<div class=\"page_path\"></div>\n";
6328 } elsif ($format eq 'plain') {
6329 print $cgi->header(
6330 -type => 'text/plain',
6331 -charset => 'utf-8',
6332 -expires => $expires,
6333 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6335 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6337 } else {
6338 die_error(400, "Unknown blobdiff format");
6341 # patch
6342 if ($format eq 'html') {
6343 print "<div class=\"page_body\">\n";
6345 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6346 close $fd;
6348 print "</div>\n"; # class="page_body"
6349 git_footer_html();
6351 } else {
6352 while (my $line = <$fd>) {
6353 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6354 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6356 print $line;
6358 last if $line =~ m!^\+\+\+!;
6360 local $/ = undef;
6361 print <$fd>;
6362 close $fd;
6366 sub git_blobdiff_plain {
6367 git_blobdiff('plain');
6370 sub git_commitdiff {
6371 my %params = @_;
6372 my $format = $params{-format} || 'html';
6374 my ($patch_max) = gitweb_get_feature('patches');
6375 if ($format eq 'patch') {
6376 die_error(403, "Patch view not allowed") unless $patch_max;
6379 $hash ||= $hash_base || "HEAD";
6380 my %co = parse_commit($hash)
6381 or die_error(404, "Unknown commit object");
6383 # choose format for commitdiff for merge
6384 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6385 $hash_parent = '--cc';
6387 # we need to prepare $formats_nav before almost any parameter munging
6388 my $formats_nav;
6389 if ($format eq 'html') {
6390 $formats_nav =
6391 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6392 "raw");
6393 if ($patch_max && @{$co{'parents'}} <= 1) {
6394 $formats_nav .= " | " .
6395 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6396 "patch");
6399 if (defined $hash_parent &&
6400 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6401 # commitdiff with two commits given
6402 my $hash_parent_short = $hash_parent;
6403 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6404 $hash_parent_short = substr($hash_parent, 0, 7);
6406 $formats_nav .=
6407 ' (from';
6408 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6409 if ($co{'parents'}[$i] eq $hash_parent) {
6410 $formats_nav .= ' parent ' . ($i+1);
6411 last;
6414 $formats_nav .= ': ' .
6415 $cgi->a({-href => href(action=>"commitdiff",
6416 hash=>$hash_parent)},
6417 esc_html($hash_parent_short)) .
6418 ')';
6419 } elsif (!$co{'parent'}) {
6420 # --root commitdiff
6421 $formats_nav .= ' (initial)';
6422 } elsif (scalar @{$co{'parents'}} == 1) {
6423 # single parent commit
6424 $formats_nav .=
6425 ' (parent: ' .
6426 $cgi->a({-href => href(action=>"commitdiff",
6427 hash=>$co{'parent'})},
6428 esc_html(substr($co{'parent'}, 0, 7))) .
6429 ')';
6430 } else {
6431 # merge commit
6432 if ($hash_parent eq '--cc') {
6433 $formats_nav .= ' | ' .
6434 $cgi->a({-href => href(action=>"commitdiff",
6435 hash=>$hash, hash_parent=>'-c')},
6436 'combined');
6437 } else { # $hash_parent eq '-c'
6438 $formats_nav .= ' | ' .
6439 $cgi->a({-href => href(action=>"commitdiff",
6440 hash=>$hash, hash_parent=>'--cc')},
6441 'compact');
6443 $formats_nav .=
6444 ' (merge: ' .
6445 join(' ', map {
6446 $cgi->a({-href => href(action=>"commitdiff",
6447 hash=>$_)},
6448 esc_html(substr($_, 0, 7)));
6449 } @{$co{'parents'}} ) .
6450 ')';
6454 my $hash_parent_param = $hash_parent;
6455 if (!defined $hash_parent_param) {
6456 # --cc for multiple parents, --root for parentless
6457 $hash_parent_param =
6458 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6461 # read commitdiff
6462 my $fd;
6463 my @difftree;
6464 if ($format eq 'html') {
6465 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6466 "--no-commit-id", "--patch-with-raw", "--full-index",
6467 $hash_parent_param, $hash, "--"
6468 or die_error(500, "Open git-diff-tree failed");
6470 while (my $line = <$fd>) {
6471 chomp $line;
6472 # empty line ends raw part of diff-tree output
6473 last unless $line;
6474 push @difftree, scalar parse_difftree_raw_line($line);
6477 } elsif ($format eq 'plain') {
6478 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6479 '-p', $hash_parent_param, $hash, "--"
6480 or die_error(500, "Open git-diff-tree failed");
6481 } elsif ($format eq 'patch') {
6482 # For commit ranges, we limit the output to the number of
6483 # patches specified in the 'patches' feature.
6484 # For single commits, we limit the output to a single patch,
6485 # diverging from the git-format-patch default.
6486 my @commit_spec = ();
6487 if ($hash_parent) {
6488 if ($patch_max > 0) {
6489 push @commit_spec, "-$patch_max";
6491 push @commit_spec, '-n', "$hash_parent..$hash";
6492 } else {
6493 if ($params{-single}) {
6494 push @commit_spec, '-1';
6495 } else {
6496 if ($patch_max > 0) {
6497 push @commit_spec, "-$patch_max";
6499 push @commit_spec, "-n";
6501 push @commit_spec, '--root', $hash;
6503 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6504 '--encoding=utf8', '--stdout', @commit_spec
6505 or die_error(500, "Open git-format-patch failed");
6506 } else {
6507 die_error(400, "Unknown commitdiff format");
6510 # non-textual hash id's can be cached
6511 my $expires;
6512 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6513 $expires = "+1d";
6516 # write commit message
6517 if ($format eq 'html') {
6518 my $refs = git_get_references();
6519 my $ref = format_ref_marker($refs, $co{'id'});
6521 git_header_html(undef, $expires);
6522 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6523 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6524 print "<div class=\"title_text\">\n" .
6525 "<table class=\"object_header\">\n";
6526 git_print_authorship_rows(\%co);
6527 print "</table>".
6528 "</div>\n";
6529 print "<div class=\"page_body\">\n";
6530 if (@{$co{'comment'}} > 1) {
6531 print "<div class=\"log\">\n";
6532 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6533 print "</div>\n"; # class="log"
6536 } elsif ($format eq 'plain') {
6537 my $refs = git_get_references("tags");
6538 my $tagname = git_get_rev_name_tags($hash);
6539 my $filename = basename($project) . "-$hash.patch";
6541 print $cgi->header(
6542 -type => 'text/plain',
6543 -charset => 'utf-8',
6544 -expires => $expires,
6545 -content_disposition => 'inline; filename="' . "$filename" . '"');
6546 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6547 print "From: " . to_utf8($co{'author'}) . "\n";
6548 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6549 print "Subject: " . to_utf8($co{'title'}) . "\n";
6551 print "X-Git-Tag: $tagname\n" if $tagname;
6552 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6554 foreach my $line (@{$co{'comment'}}) {
6555 print to_utf8($line) . "\n";
6557 print "---\n\n";
6558 } elsif ($format eq 'patch') {
6559 my $filename = basename($project) . "-$hash.patch";
6561 print $cgi->header(
6562 -type => 'text/plain',
6563 -charset => 'utf-8',
6564 -expires => $expires,
6565 -content_disposition => 'inline; filename="' . "$filename" . '"');
6568 # write patch
6569 if ($format eq 'html') {
6570 my $use_parents = !defined $hash_parent ||
6571 $hash_parent eq '-c' || $hash_parent eq '--cc';
6572 git_difftree_body(\@difftree, $hash,
6573 $use_parents ? @{$co{'parents'}} : $hash_parent);
6574 print "<br/>\n";
6576 git_patchset_body($fd, \@difftree, $hash,
6577 $use_parents ? @{$co{'parents'}} : $hash_parent);
6578 close $fd;
6579 print "</div>\n"; # class="page_body"
6580 git_footer_html();
6582 } elsif ($format eq 'plain') {
6583 local $/ = undef;
6584 print <$fd>;
6585 close $fd
6586 or print "Reading git-diff-tree failed\n";
6587 } elsif ($format eq 'patch') {
6588 local $/ = undef;
6589 print <$fd>;
6590 close $fd
6591 or print "Reading git-format-patch failed\n";
6595 sub git_commitdiff_plain {
6596 git_commitdiff(-format => 'plain');
6599 # format-patch-style patches
6600 sub git_patch {
6601 git_commitdiff(-format => 'patch', -single => 1);
6604 sub git_patches {
6605 git_commitdiff(-format => 'patch');
6608 sub git_history {
6609 git_log_generic('history', \&git_history_body,
6610 $hash_base, $hash_parent_base,
6611 $file_name, $hash);
6614 sub git_search {
6615 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6616 if (!defined $searchtext) {
6617 die_error(400, "Text field is empty");
6619 if (!defined $hash) {
6620 $hash = git_get_head_hash($project);
6622 my %co = parse_commit($hash);
6623 if (!%co) {
6624 die_error(404, "Unknown commit object");
6626 if (!defined $page) {
6627 $page = 0;
6630 $searchtype ||= 'commit';
6631 if ($searchtype eq 'pickaxe') {
6632 # pickaxe may take all resources of your box and run for several minutes
6633 # with every query - so decide by yourself how public you make this feature
6634 gitweb_check_feature('pickaxe')
6635 or die_error(403, "Pickaxe is disabled");
6637 if ($searchtype eq 'grep') {
6638 gitweb_check_feature('grep')
6639 or die_error(403, "Grep is disabled");
6642 git_header_html();
6644 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6645 my $greptype;
6646 if ($searchtype eq 'commit') {
6647 $greptype = "--grep=";
6648 } elsif ($searchtype eq 'author') {
6649 $greptype = "--author=";
6650 } elsif ($searchtype eq 'committer') {
6651 $greptype = "--committer=";
6653 $greptype .= $searchtext;
6654 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6655 $greptype, '--regexp-ignore-case',
6656 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6658 my $paging_nav = '';
6659 if ($page > 0) {
6660 $paging_nav .=
6661 $cgi->a({-href => href(action=>"search", hash=>$hash,
6662 searchtext=>$searchtext,
6663 searchtype=>$searchtype)},
6664 "first");
6665 $paging_nav .= " &sdot; " .
6666 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6667 -accesskey => "p", -title => "Alt-p"}, "prev");
6668 } else {
6669 $paging_nav .= "first";
6670 $paging_nav .= " &sdot; prev";
6672 my $next_link = '';
6673 if ($#commitlist >= 100) {
6674 $next_link =
6675 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6676 -accesskey => "n", -title => "Alt-n"}, "next");
6677 $paging_nav .= " &sdot; $next_link";
6678 } else {
6679 $paging_nav .= " &sdot; next";
6682 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6683 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6684 if ($page == 0 && !@commitlist) {
6685 print "<p>No match.</p>\n";
6686 } else {
6687 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6691 if ($searchtype eq 'pickaxe') {
6692 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6693 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6695 print "<table class=\"pickaxe search\">\n";
6696 my $alternate = 1;
6697 local $/ = "\n";
6698 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6699 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6700 ($search_use_regexp ? '--pickaxe-regex' : ());
6701 undef %co;
6702 my @files;
6703 while (my $line = <$fd>) {
6704 chomp $line;
6705 next unless $line;
6707 my %set = parse_difftree_raw_line($line);
6708 if (defined $set{'commit'}) {
6709 # finish previous commit
6710 if (%co) {
6711 print "</td>\n" .
6712 "<td class=\"link\">" .
6713 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6714 " | " .
6715 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6716 print "</td>\n" .
6717 "</tr>\n";
6720 if ($alternate) {
6721 print "<tr class=\"dark\">\n";
6722 } else {
6723 print "<tr class=\"light\">\n";
6725 $alternate ^= 1;
6726 %co = parse_commit($set{'commit'});
6727 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6728 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6729 "<td><i>$author</i></td>\n" .
6730 "<td>" .
6731 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6732 -class => "list subject"},
6733 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6734 } elsif (defined $set{'to_id'}) {
6735 next if ($set{'to_id'} =~ m/^0{40}$/);
6737 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6738 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6739 -class => "list"},
6740 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6741 "<br/>\n";
6744 close $fd;
6746 # finish last commit (warning: repetition!)
6747 if (%co) {
6748 print "</td>\n" .
6749 "<td class=\"link\">" .
6750 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6751 " | " .
6752 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6753 print "</td>\n" .
6754 "</tr>\n";
6757 print "</table>\n";
6760 if ($searchtype eq 'grep') {
6761 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6762 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6764 print "<table class=\"grep_search\">\n";
6765 my $alternate = 1;
6766 my $matches = 0;
6767 local $/ = "\n";
6768 open my $fd, "-|", git_cmd(), 'grep', '-n',
6769 $search_use_regexp ? ('-E', '-i') : '-F',
6770 $searchtext, $co{'tree'};
6771 my $lastfile = '';
6772 while (my $line = <$fd>) {
6773 chomp $line;
6774 my ($file, $lno, $ltext, $binary);
6775 last if ($matches++ > 1000);
6776 if ($line =~ /^Binary file (.+) matches$/) {
6777 $file = $1;
6778 $binary = 1;
6779 } else {
6780 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6782 if ($file ne $lastfile) {
6783 $lastfile and print "</td></tr>\n";
6784 if ($alternate++) {
6785 print "<tr class=\"dark\">\n";
6786 } else {
6787 print "<tr class=\"light\">\n";
6789 print "<td class=\"list\">".
6790 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6791 file_name=>"$file"),
6792 -class => "list"}, esc_path($file));
6793 print "</td><td>\n";
6794 $lastfile = $file;
6796 if ($binary) {
6797 print "<div class=\"binary\">Binary file</div>\n";
6798 } else {
6799 $ltext = untabify($ltext);
6800 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6801 $ltext = esc_html($1, -nbsp=>1);
6802 $ltext .= '<span class="match">';
6803 $ltext .= esc_html($2, -nbsp=>1);
6804 $ltext .= '</span>';
6805 $ltext .= esc_html($3, -nbsp=>1);
6806 } else {
6807 $ltext = esc_html($ltext, -nbsp=>1);
6809 print "<div class=\"pre\">" .
6810 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6811 file_name=>"$file").'#l'.$lno,
6812 -class => "linenr"}, sprintf('%4i', $lno))
6813 . ' ' . $ltext . "</div>\n";
6816 if ($lastfile) {
6817 print "</td></tr>\n";
6818 if ($matches > 1000) {
6819 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6821 } else {
6822 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6824 close $fd;
6826 print "</table>\n";
6828 git_footer_html();
6831 sub git_search_help {
6832 git_header_html();
6833 git_print_page_nav('','', $hash,$hash,$hash);
6834 print <<EOT;
6835 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6836 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6837 the pattern entered is recognized as the POSIX extended
6838 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6839 insensitive).</p>
6840 <dl>
6841 <dt><b>commit</b></dt>
6842 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6844 my $have_grep = gitweb_check_feature('grep');
6845 if ($have_grep) {
6846 print <<EOT;
6847 <dt><b>grep</b></dt>
6848 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6849 a different one) are searched for the given pattern. On large trees, this search can take
6850 a while and put some strain on the server, so please use it with some consideration. Note that
6851 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6852 case-sensitive.</dd>
6855 print <<EOT;
6856 <dt><b>author</b></dt>
6857 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6858 <dt><b>committer</b></dt>
6859 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6861 my $have_pickaxe = gitweb_check_feature('pickaxe');
6862 if ($have_pickaxe) {
6863 print <<EOT;
6864 <dt><b>pickaxe</b></dt>
6865 <dd>All commits that caused the string to appear or disappear from any file (changes that
6866 added, removed or "modified" the string) will be listed. This search can take a while and
6867 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6868 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6871 print "</dl>\n";
6872 git_footer_html();
6875 sub git_shortlog {
6876 git_log_generic('shortlog', \&git_shortlog_body,
6877 $hash, $hash_parent);
6880 ## ......................................................................
6881 ## feeds (RSS, Atom; OPML)
6883 sub git_feed {
6884 my $format = shift || 'atom';
6885 my $have_blame = gitweb_check_feature('blame');
6887 # Atom: http://www.atomenabled.org/developers/syndication/
6888 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6889 if ($format ne 'rss' && $format ne 'atom') {
6890 die_error(400, "Unknown web feed format");
6893 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6894 my $head = $hash || 'HEAD';
6895 my @commitlist = parse_commits($head, 150, 0, $file_name);
6897 my %latest_commit;
6898 my %latest_date;
6899 my $content_type = "application/$format+xml";
6900 if (defined $cgi->http('HTTP_ACCEPT') &&
6901 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6902 # browser (feed reader) prefers text/xml
6903 $content_type = 'text/xml';
6905 if (defined($commitlist[0])) {
6906 %latest_commit = %{$commitlist[0]};
6907 my $latest_epoch = $latest_commit{'committer_epoch'};
6908 %latest_date = parse_date($latest_epoch);
6909 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6910 if (defined $if_modified) {
6911 my $since;
6912 if (eval { require HTTP::Date; 1; }) {
6913 $since = HTTP::Date::str2time($if_modified);
6914 } elsif (eval { require Time::ParseDate; 1; }) {
6915 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6917 if (defined $since && $latest_epoch <= $since) {
6918 print $cgi->header(
6919 -type => $content_type,
6920 -charset => 'utf-8',
6921 -last_modified => $latest_date{'rfc2822'},
6922 -status => '304 Not Modified');
6923 return;
6926 print $cgi->header(
6927 -type => $content_type,
6928 -charset => 'utf-8',
6929 -last_modified => $latest_date{'rfc2822'});
6930 } else {
6931 print $cgi->header(
6932 -type => $content_type,
6933 -charset => 'utf-8');
6936 # Optimization: skip generating the body if client asks only
6937 # for Last-Modified date.
6938 return if ($cgi->request_method() eq 'HEAD');
6940 # header variables
6941 my $title = "$site_name - $project/$action";
6942 my $feed_type = 'log';
6943 if (defined $hash) {
6944 $title .= " - '$hash'";
6945 $feed_type = 'branch log';
6946 if (defined $file_name) {
6947 $title .= " :: $file_name";
6948 $feed_type = 'history';
6950 } elsif (defined $file_name) {
6951 $title .= " - $file_name";
6952 $feed_type = 'history';
6954 $title .= " $feed_type";
6955 my $descr = git_get_project_description($project);
6956 if (defined $descr) {
6957 $descr = esc_html($descr);
6958 } else {
6959 $descr = "$project " .
6960 ($format eq 'rss' ? 'RSS' : 'Atom') .
6961 " feed";
6963 my $owner = git_get_project_owner($project);
6964 $owner = esc_html($owner);
6966 #header
6967 my $alt_url;
6968 if (defined $file_name) {
6969 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6970 } elsif (defined $hash) {
6971 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6972 } else {
6973 $alt_url = href(-full=>1, action=>"summary");
6975 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6976 if ($format eq 'rss') {
6977 print <<XML;
6978 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6979 <channel>
6981 print "<title>$title</title>\n" .
6982 "<link>$alt_url</link>\n" .
6983 "<description>$descr</description>\n" .
6984 "<language>en</language>\n" .
6985 # project owner is responsible for 'editorial' content
6986 "<managingEditor>$owner</managingEditor>\n";
6987 if (defined $logo || defined $favicon) {
6988 # prefer the logo to the favicon, since RSS
6989 # doesn't allow both
6990 my $img = esc_url($logo || $favicon);
6991 print "<image>\n" .
6992 "<url>$img</url>\n" .
6993 "<title>$title</title>\n" .
6994 "<link>$alt_url</link>\n" .
6995 "</image>\n";
6997 if (%latest_date) {
6998 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6999 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7001 print "<generator>gitweb v.$version/$git_version</generator>\n";
7002 } elsif ($format eq 'atom') {
7003 print <<XML;
7004 <feed xmlns="http://www.w3.org/2005/Atom">
7006 print "<title>$title</title>\n" .
7007 "<subtitle>$descr</subtitle>\n" .
7008 '<link rel="alternate" type="text/html" href="' .
7009 $alt_url . '" />' . "\n" .
7010 '<link rel="self" type="' . $content_type . '" href="' .
7011 $cgi->self_url() . '" />' . "\n" .
7012 "<id>" . href(-full=>1) . "</id>\n" .
7013 # use project owner for feed author
7014 "<author><name>$owner</name></author>\n";
7015 if (defined $favicon) {
7016 print "<icon>" . esc_url($favicon) . "</icon>\n";
7018 if (defined $logo_url) {
7019 # not twice as wide as tall: 72 x 27 pixels
7020 print "<logo>" . esc_url($logo) . "</logo>\n";
7022 if (! %latest_date) {
7023 # dummy date to keep the feed valid until commits trickle in:
7024 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7025 } else {
7026 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7028 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7031 # contents
7032 for (my $i = 0; $i <= $#commitlist; $i++) {
7033 my %co = %{$commitlist[$i]};
7034 my $commit = $co{'id'};
7035 # we read 150, we always show 30 and the ones more recent than 48 hours
7036 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7037 last;
7039 my %cd = parse_date($co{'author_epoch'});
7041 # get list of changed files
7042 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7043 $co{'parent'} || "--root",
7044 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7045 or next;
7046 my @difftree = map { chomp; $_ } <$fd>;
7047 close $fd
7048 or next;
7050 # print element (entry, item)
7051 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7052 if ($format eq 'rss') {
7053 print "<item>\n" .
7054 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7055 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7056 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7057 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7058 "<link>$co_url</link>\n" .
7059 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7060 "<content:encoded>" .
7061 "<![CDATA[\n";
7062 } elsif ($format eq 'atom') {
7063 print "<entry>\n" .
7064 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7065 "<updated>$cd{'iso-8601'}</updated>\n" .
7066 "<author>\n" .
7067 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7068 if ($co{'author_email'}) {
7069 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7071 print "</author>\n" .
7072 # use committer for contributor
7073 "<contributor>\n" .
7074 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7075 if ($co{'committer_email'}) {
7076 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7078 print "</contributor>\n" .
7079 "<published>$cd{'iso-8601'}</published>\n" .
7080 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7081 "<id>$co_url</id>\n" .
7082 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7083 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7085 my $comment = $co{'comment'};
7086 print "<pre>\n";
7087 foreach my $line (@$comment) {
7088 $line = esc_html($line);
7089 print "$line\n";
7091 print "</pre><ul>\n";
7092 foreach my $difftree_line (@difftree) {
7093 my %difftree = parse_difftree_raw_line($difftree_line);
7094 next if !$difftree{'from_id'};
7096 my $file = $difftree{'file'} || $difftree{'to_file'};
7098 print "<li>" .
7099 "[" .
7100 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7101 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7102 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7103 file_name=>$file, file_parent=>$difftree{'from_file'}),
7104 -title => "diff"}, 'D');
7105 if ($have_blame) {
7106 print $cgi->a({-href => href(-full=>1, action=>"blame",
7107 file_name=>$file, hash_base=>$commit),
7108 -title => "blame"}, 'B');
7110 # if this is not a feed of a file history
7111 if (!defined $file_name || $file_name ne $file) {
7112 print $cgi->a({-href => href(-full=>1, action=>"history",
7113 file_name=>$file, hash=>$commit),
7114 -title => "history"}, 'H');
7116 $file = esc_path($file);
7117 print "] ".
7118 "$file</li>\n";
7120 if ($format eq 'rss') {
7121 print "</ul>]]>\n" .
7122 "</content:encoded>\n" .
7123 "</item>\n";
7124 } elsif ($format eq 'atom') {
7125 print "</ul>\n</div>\n" .
7126 "</content>\n" .
7127 "</entry>\n";
7131 # end of feed
7132 if ($format eq 'rss') {
7133 print "</channel>\n</rss>\n";
7134 } elsif ($format eq 'atom') {
7135 print "</feed>\n";
7139 sub git_rss {
7140 git_feed('rss');
7143 sub git_atom {
7144 git_feed('atom');
7147 sub git_opml {
7148 my @list = git_get_projects_list();
7150 print $cgi->header(
7151 -type => 'text/xml',
7152 -charset => 'utf-8',
7153 -content_disposition => 'inline; filename="opml.xml"');
7155 print <<XML;
7156 <?xml version="1.0" encoding="utf-8"?>
7157 <opml version="1.0">
7158 <head>
7159 <title>$site_name OPML Export</title>
7160 </head>
7161 <body>
7162 <outline text="git RSS feeds">
7165 foreach my $pr (@list) {
7166 my %proj = %$pr;
7167 my $head = git_get_head_hash($proj{'path'});
7168 if (!defined $head) {
7169 next;
7171 $git_dir = "$projectroot/$proj{'path'}";
7172 my %co = parse_commit($head);
7173 if (!%co) {
7174 next;
7177 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7178 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7179 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7180 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7182 print <<XML;
7183 </outline>
7184 </body>
7185 </opml>