32376346ca6590278485f72164f41b8b08d5ba53
[git/jnareb-git.git] / gitweb / gitweb.perl
blob32376346ca6590278485f72164f41b8b08d5ba53
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use 5.008;
11 use strict;
12 use warnings;
14 use File::Spec;
15 # __DIR__ is taken from Dir::Self __DIR__ fragment
16 sub __DIR__ () {
17 File::Spec->rel2abs(join '', (File::Spec->splitpath(__FILE__))[0, 1]);
19 use lib __DIR__ . '/lib';
21 use CGI qw(:standard :escapeHTML -nosticky);
22 use CGI::Util qw(unescape);
23 use CGI::Carp qw(fatalsToBrowser set_message);
24 use Encode;
25 use Fcntl ':mode';
26 use File::Find qw();
27 use File::Basename qw(basename);
28 binmode STDOUT, ':utf8';
30 our $t0;
31 if (eval { require Time::HiRes; 1; }) {
32 $t0 = [Time::HiRes::gettimeofday()];
34 our $number_of_git_cmds = 0;
36 BEGIN {
37 CGI->compile() if $ENV{'MOD_PERL'};
40 our $version = "++GIT_VERSION++";
42 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
43 sub evaluate_uri {
44 our $cgi;
46 our $my_url = $cgi->url();
47 our $my_uri = $cgi->url(-absolute => 1);
49 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
50 # needed and used only for URLs with nonempty PATH_INFO
51 our $base_url = $my_url;
53 # When the script is used as DirectoryIndex, the URL does not contain the name
54 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
55 # have to do it ourselves. We make $path_info global because it's also used
56 # later on.
58 # Another issue with the script being the DirectoryIndex is that the resulting
59 # $my_url data is not the full script URL: this is good, because we want
60 # generated links to keep implying the script name if it wasn't explicitly
61 # indicated in the URL we're handling, but it means that $my_url cannot be used
62 # as base URL.
63 # Therefore, if we needed to strip PATH_INFO, then we know that we have
64 # to build the base URL ourselves:
65 our $path_info = $ENV{"PATH_INFO"};
66 if ($path_info) {
67 if ($my_url =~ s,\Q$path_info\E$,, &&
68 $my_uri =~ s,\Q$path_info\E$,, &&
69 defined $ENV{'SCRIPT_NAME'}) {
70 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
74 # target of the home link on top of all pages
75 our $home_link = $my_uri || "/";
78 # core git executable to use
79 # this can just be "git" if your webserver has a sensible PATH
80 our $GIT = "++GIT_BINDIR++/git";
82 # absolute fs-path which will be prepended to the project path
83 #our $projectroot = "/pub/scm";
84 our $projectroot = "++GITWEB_PROJECTROOT++";
86 # fs traversing limit for getting project list
87 # the number is relative to the projectroot
88 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
90 # string of the home link on top of all pages
91 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
93 # name of your site or organization to appear in page titles
94 # replace this with something more descriptive for clearer bookmarks
95 our $site_name = "++GITWEB_SITENAME++"
96 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
98 # filename of html text to include at top of each page
99 our $site_header = "++GITWEB_SITE_HEADER++";
100 # html text to include at home page
101 our $home_text = "++GITWEB_HOMETEXT++";
102 # filename of html text to include at bottom of each page
103 our $site_footer = "++GITWEB_SITE_FOOTER++";
105 # URI of stylesheets
106 our @stylesheets = ("++GITWEB_CSS++");
107 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
108 our $stylesheet = undef;
109 # URI of GIT logo (72x27 size)
110 our $logo = "++GITWEB_LOGO++";
111 # URI of GIT favicon, assumed to be image/png type
112 our $favicon = "++GITWEB_FAVICON++";
113 # URI of gitweb.js (JavaScript code for gitweb)
114 our $javascript = "++GITWEB_JS++";
116 # URI and label (title) of GIT logo link
117 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
118 #our $logo_label = "git documentation";
119 our $logo_url = "http://git-scm.com/";
120 our $logo_label = "git homepage";
122 # source of projects list
123 our $projects_list = "++GITWEB_LIST++";
125 # the width (in characters) of the projects list "Description" column
126 our $projects_list_description_width = 25;
128 # default order of projects list
129 # valid values are none, project, descr, owner, and age
130 our $default_projects_order = "project";
132 # show repository only if this file exists
133 # (only effective if this variable evaluates to true)
134 our $export_ok = "++GITWEB_EXPORT_OK++";
136 # show repository only if this subroutine returns true
137 # when given the path to the project, for example:
138 # sub { return -e "$_[0]/git-daemon-export-ok"; }
139 our $export_auth_hook = undef;
141 # only allow viewing of repositories also shown on the overview page
142 our $strict_export = "++GITWEB_STRICT_EXPORT++";
144 # list of git base URLs used for URL to where fetch project from,
145 # i.e. full URL is "$git_base_url/$project"
146 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
148 # default blob_plain mimetype and default charset for text/plain blob
149 our $default_blob_plain_mimetype = 'text/plain';
150 our $default_text_plain_charset = undef;
152 # file to use for guessing MIME types before trying /etc/mime.types
153 # (relative to the current git repository)
154 our $mimetypes_file = undef;
156 # assume this charset if line contains non-UTF-8 characters;
157 # it should be valid encoding (see Encoding::Supported(3pm) for list),
158 # for which encoding all byte sequences are valid, for example
159 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
160 # could be even 'utf-8' for the old behavior)
161 our $fallback_encoding = 'latin1';
163 # rename detection options for git-diff and git-diff-tree
164 # - default is '-M', with the cost proportional to
165 # (number of removed files) * (number of new files).
166 # - more costly is '-C' (which implies '-M'), with the cost proportional to
167 # (number of changed files + number of removed files) * (number of new files)
168 # - even more costly is '-C', '--find-copies-harder' with cost
169 # (number of files in the original tree) * (number of new files)
170 # - one might want to include '-B' option, e.g. '-B', '-M'
171 our @diff_opts = ('-M'); # taken from git_commit
173 # Disables features that would allow repository owners to inject script into
174 # the gitweb domain.
175 our $prevent_xss = 0;
177 # Path to the highlight executable to use (must be the one from
178 # http://www.andre-simon.de due to assumptions about parameters and output).
179 # Useful if highlight is not installed on your webserver's PATH.
180 # [Default: highlight]
181 our $highlight_bin = "++HIGHLIGHT_BIN++";
183 # information about snapshot formats that gitweb is capable of serving
184 our %known_snapshot_formats = (
185 # name => {
186 # 'display' => display name,
187 # 'type' => mime type,
188 # 'suffix' => filename suffix,
189 # 'format' => --format for git-archive,
190 # 'compressor' => [compressor command and arguments]
191 # (array reference, optional)
192 # 'disabled' => boolean (optional)}
194 'tgz' => {
195 'display' => 'tar.gz',
196 'type' => 'application/x-gzip',
197 'suffix' => '.tar.gz',
198 'format' => 'tar',
199 'compressor' => ['gzip']},
201 'tbz2' => {
202 'display' => 'tar.bz2',
203 'type' => 'application/x-bzip2',
204 'suffix' => '.tar.bz2',
205 'format' => 'tar',
206 'compressor' => ['bzip2']},
208 'txz' => {
209 'display' => 'tar.xz',
210 'type' => 'application/x-xz',
211 'suffix' => '.tar.xz',
212 'format' => 'tar',
213 'compressor' => ['xz'],
214 'disabled' => 1},
216 'zip' => {
217 'display' => 'zip',
218 'type' => 'application/x-zip',
219 'suffix' => '.zip',
220 'format' => 'zip'},
223 # Aliases so we understand old gitweb.snapshot values in repository
224 # configuration.
225 our %known_snapshot_format_aliases = (
226 'gzip' => 'tgz',
227 'bzip2' => 'tbz2',
228 'xz' => 'txz',
230 # backward compatibility: legacy gitweb config support
231 'x-gzip' => undef, 'gz' => undef,
232 'x-bzip2' => undef, 'bz2' => undef,
233 'x-zip' => undef, '' => undef,
236 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
237 # are changed, it may be appropriate to change these values too via
238 # $GITWEB_CONFIG.
239 our %avatar_size = (
240 'default' => 16,
241 'double' => 32
244 # Used to set the maximum load that we will still respond to gitweb queries.
245 # If server load exceed this value then return "503 server busy" error.
246 # If gitweb cannot determined server load, it is taken to be 0.
247 # Leave it undefined (or set to 'undef') to turn off load checking.
248 our $maxload = 300;
250 # configuration for 'highlight' (http://www.andre-simon.de/)
251 # match by basename
252 our %highlight_basename = (
253 #'Program' => 'py',
254 #'Library' => 'py',
255 'SConstruct' => 'py', # SCons equivalent of Makefile
256 'Makefile' => 'make',
258 # match by extension
259 our %highlight_ext = (
260 # main extensions, defining name of syntax;
261 # see files in /usr/share/highlight/langDefs/ directory
262 map { $_ => $_ }
263 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl),
264 # alternate extensions, see /etc/highlight/filetypes.conf
265 'h' => 'c',
266 map { $_ => 'cpp' } qw(cxx c++ cc),
267 map { $_ => 'php' } qw(php3 php4),
268 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
269 'mak' => 'make',
270 map { $_ => 'xml' } qw(xhtml html htm),
274 # This enables/disables the caching layer in gitweb. Currently supported
275 # is only output (response) caching, similar to the one used on git.kernel.org.
276 our $caching_enabled = 0;
277 # Set to _initialized_ instance of cache interface implementing (at least)
278 # get($key) and set($key, $data) methods (Cache::Cache and CHI interfaces),
279 # or to name of class of cache interface implementing said methods.
280 # If unset, GitwebCache::FileCacheWithLocking would be used, which is 'dumb'
281 # (but fast) file based caching layer, currently without any support for
282 # cache size limiting. It is therefore recommended that the cache directory
283 # be periodically completely deleted; this operation is safe to perform.
284 # Suggested mechanism:
285 # mv $cachedir $cachedir.flush && mkdir $cachedir && rm -rf $cachedir.flush
286 our $cache;
287 # You define site-wide cache options defaults here; override them with
288 # $GITWEB_CONFIG as necessary.
289 our %cache_options = (
290 # The location in the filesystem that will hold the root of the cache.
291 # This directory will be created as needed (if possible) on the first
292 # cache set. Note that either this directory must exists and web server
293 # has to have write permissions to it, or web server must be able to
294 # create this directory.
295 # Possible values:
296 # * 'cache' (relative to gitweb),
297 # * File::Spec->catdir(File::Spec->tmpdir(), 'gitweb-cache'),
298 # * '/var/cache/gitweb' (FHS compliant, requires being set up),
299 'cache_root' => 'cache',
301 # The number of subdirectories deep to cache object item. This should be
302 # large enough that no cache directory has more than a few hundred
303 # objects. Each non-leaf directory contains up to 256 subdirectories
304 # (00-ff). Must be larger than 0.
305 'cache_depth' => 1,
307 # The (global) minimum expiration time for objects placed in the cache,
308 # in seconds. If the dynamic adaptive cache exporation time is lower
309 # than this number, we set cache timeout to this minimum.
310 'expires_min' => 20, # 20 seconds
312 # The (global) maximum expiration time for dynamic (adaptive) caching
313 # algorithm, in seconds. If the adaptive cache lifetime exceeds this
314 # number, we set cache timeout to this maximum.
315 # (If 'expires_min' >= 'expires_max', there is no adaptive cache timeout,
316 # and 'expires_min' is used as expiration time for objects in cache.)
317 'expires_max' => 1200, # 20 minutes
319 # Cache lifetime will be increased by applying this factor to the result
320 # from 'check_load' callback (see below).
321 'expires_factor' => 60, # expire time in seconds for 1.0 (100% CPU) load
323 # User supplied callback for deciding the cache policy, usually system
324 # load. Multiplied by 'expires_factor' gives adaptive expiration time,
325 # in seconds, subject to the limits imposed by 'expires_min' and
326 # 'expires_max' bounds. Set to undef (or delete) to turn off dynamic
327 # lifetime control.
328 # (Compatibile with Cache::Adaptive.)
329 'check_load' => \&get_loadavg,
331 # Maximum cache file life, in seconds. If cache entry lifetime exceeds
332 # this value, it wouldn't be served as being too stale when waiting for
333 # cache to be regenerated/refreshed, instead of trying to display
334 # existing cache date.
335 # Set it to -1 to always serve existing data if it exists,
336 # set it to 0 to turn off serving stale data - always wait.
337 'max_lifetime' => 5*60*60, # 5 hours
339 # This enables/disables background caching. If it is set to true value,
340 # caching engine would return stale data (if it is not older than
341 # 'max_lifetime' seconds) if it exists, and launch process if regenerating
342 # (refreshing) cache into the background. If it is set to false value,
343 # the process that fills cache must always wait for data to be generated.
344 # In theory this will make gitweb seem more responsive at the price of
345 # serving possibly stale data.
346 'background_cache' => 1,
348 # Set to _initialized_ instance of GitwebCache::Capture compatibile capturing
349 # engine, i.e. one implementing ->new() constructor, and ->capture($code)
350 # method. If unset (default), the GitwebCache::Capture::Simple would be used.
351 our $capture;
353 # You define site-wide feature defaults here; override them with
354 # $GITWEB_CONFIG as necessary.
355 our %feature = (
356 # feature => {
357 # 'sub' => feature-sub (subroutine),
358 # 'override' => allow-override (boolean),
359 # 'default' => [ default options...] (array reference)}
361 # if feature is overridable (it means that allow-override has true value),
362 # then feature-sub will be called with default options as parameters;
363 # return value of feature-sub indicates if to enable specified feature
365 # if there is no 'sub' key (no feature-sub), then feature cannot be
366 # overridden
368 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
369 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
370 # is enabled
372 # Enable the 'blame' blob view, showing the last commit that modified
373 # each line in the file. This can be very CPU-intensive.
375 # To enable system wide have in $GITWEB_CONFIG
376 # $feature{'blame'}{'default'} = [1];
377 # To have project specific config enable override in $GITWEB_CONFIG
378 # $feature{'blame'}{'override'} = 1;
379 # and in project config gitweb.blame = 0|1;
380 'blame' => {
381 'sub' => sub { feature_bool('blame', @_) },
382 'override' => 0,
383 'default' => [0]},
385 # Enable the 'snapshot' link, providing a compressed archive of any
386 # tree. This can potentially generate high traffic if you have large
387 # project.
389 # Value is a list of formats defined in %known_snapshot_formats that
390 # you wish to offer.
391 # To disable system wide have in $GITWEB_CONFIG
392 # $feature{'snapshot'}{'default'} = [];
393 # To have project specific config enable override in $GITWEB_CONFIG
394 # $feature{'snapshot'}{'override'} = 1;
395 # and in project config, a comma-separated list of formats or "none"
396 # to disable. Example: gitweb.snapshot = tbz2,zip;
397 'snapshot' => {
398 'sub' => \&feature_snapshot,
399 'override' => 0,
400 'default' => ['tgz']},
402 # Enable text search, which will list the commits which match author,
403 # committer or commit text to a given string. Enabled by default.
404 # Project specific override is not supported.
405 'search' => {
406 'override' => 0,
407 'default' => [1]},
409 # Enable grep search, which will list the files in currently selected
410 # tree containing the given string. Enabled by default. This can be
411 # potentially CPU-intensive, of course.
413 # To enable system wide have in $GITWEB_CONFIG
414 # $feature{'grep'}{'default'} = [1];
415 # To have project specific config enable override in $GITWEB_CONFIG
416 # $feature{'grep'}{'override'} = 1;
417 # and in project config gitweb.grep = 0|1;
418 'grep' => {
419 'sub' => sub { feature_bool('grep', @_) },
420 'override' => 0,
421 'default' => [1]},
423 # Enable the pickaxe search, which will list the commits that modified
424 # a given string in a file. This can be practical and quite faster
425 # alternative to 'blame', but still potentially CPU-intensive.
427 # To enable system wide have in $GITWEB_CONFIG
428 # $feature{'pickaxe'}{'default'} = [1];
429 # To have project specific config enable override in $GITWEB_CONFIG
430 # $feature{'pickaxe'}{'override'} = 1;
431 # and in project config gitweb.pickaxe = 0|1;
432 'pickaxe' => {
433 'sub' => sub { feature_bool('pickaxe', @_) },
434 'override' => 0,
435 'default' => [1]},
437 # Enable showing size of blobs in a 'tree' view, in a separate
438 # column, similar to what 'ls -l' does. This cost a bit of IO.
440 # To disable system wide have in $GITWEB_CONFIG
441 # $feature{'show-sizes'}{'default'} = [0];
442 # To have project specific config enable override in $GITWEB_CONFIG
443 # $feature{'show-sizes'}{'override'} = 1;
444 # and in project config gitweb.showsizes = 0|1;
445 'show-sizes' => {
446 'sub' => sub { feature_bool('showsizes', @_) },
447 'override' => 0,
448 'default' => [1]},
450 # Make gitweb use an alternative format of the URLs which can be
451 # more readable and natural-looking: project name is embedded
452 # directly in the path and the query string contains other
453 # auxiliary information. All gitweb installations recognize
454 # URL in either format; this configures in which formats gitweb
455 # generates links.
457 # To enable system wide have in $GITWEB_CONFIG
458 # $feature{'pathinfo'}{'default'} = [1];
459 # Project specific override is not supported.
461 # Note that you will need to change the default location of CSS,
462 # favicon, logo and possibly other files to an absolute URL. Also,
463 # if gitweb.cgi serves as your indexfile, you will need to force
464 # $my_uri to contain the script name in your $GITWEB_CONFIG.
465 'pathinfo' => {
466 'override' => 0,
467 'default' => [0]},
469 # Make gitweb consider projects in project root subdirectories
470 # to be forks of existing projects. Given project $projname.git,
471 # projects matching $projname/*.git will not be shown in the main
472 # projects list, instead a '+' mark will be added to $projname
473 # there and a 'forks' view will be enabled for the project, listing
474 # all the forks. If project list is taken from a file, forks have
475 # to be listed after the main project.
477 # To enable system wide have in $GITWEB_CONFIG
478 # $feature{'forks'}{'default'} = [1];
479 # Project specific override is not supported.
480 'forks' => {
481 'override' => 0,
482 'default' => [0]},
484 # Insert custom links to the action bar of all project pages.
485 # This enables you mainly to link to third-party scripts integrating
486 # into gitweb; e.g. git-browser for graphical history representation
487 # or custom web-based repository administration interface.
489 # The 'default' value consists of a list of triplets in the form
490 # (label, link, position) where position is the label after which
491 # to insert the link and link is a format string where %n expands
492 # to the project name, %f to the project path within the filesystem,
493 # %h to the current hash (h gitweb parameter) and %b to the current
494 # hash base (hb gitweb parameter); %% expands to %.
496 # To enable system wide have in $GITWEB_CONFIG e.g.
497 # $feature{'actions'}{'default'} = [('graphiclog',
498 # '/git-browser/by-commit.html?r=%n', 'summary')];
499 # Project specific override is not supported.
500 'actions' => {
501 'override' => 0,
502 'default' => []},
504 # Allow gitweb scan project content tags described in ctags/
505 # of project repository, and display the popular Web 2.0-ish
506 # "tag cloud" near the project list. Note that this is something
507 # COMPLETELY different from the normal Git tags.
509 # gitweb by itself can show existing tags, but it does not handle
510 # tagging itself; you need an external application for that.
511 # For an example script, check Girocco's cgi/tagproj.cgi.
512 # You may want to install the HTML::TagCloud Perl module to get
513 # a pretty tag cloud instead of just a list of tags.
515 # To enable system wide have in $GITWEB_CONFIG
516 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
517 # Project specific override is not supported.
518 'ctags' => {
519 'override' => 0,
520 'default' => [0]},
522 # The maximum number of patches in a patchset generated in patch
523 # view. Set this to 0 or undef to disable patch view, or to a
524 # negative number to remove any limit.
526 # To disable system wide have in $GITWEB_CONFIG
527 # $feature{'patches'}{'default'} = [0];
528 # To have project specific config enable override in $GITWEB_CONFIG
529 # $feature{'patches'}{'override'} = 1;
530 # and in project config gitweb.patches = 0|n;
531 # where n is the maximum number of patches allowed in a patchset.
532 'patches' => {
533 'sub' => \&feature_patches,
534 'override' => 0,
535 'default' => [16]},
537 # Avatar support. When this feature is enabled, views such as
538 # shortlog or commit will display an avatar associated with
539 # the email of the committer(s) and/or author(s).
541 # Currently available providers are gravatar and picon.
542 # If an unknown provider is specified, the feature is disabled.
544 # Gravatar depends on Digest::MD5.
545 # Picon currently relies on the indiana.edu database.
547 # To enable system wide have in $GITWEB_CONFIG
548 # $feature{'avatar'}{'default'} = ['<provider>'];
549 # where <provider> is either gravatar or picon.
550 # To have project specific config enable override in $GITWEB_CONFIG
551 # $feature{'avatar'}{'override'} = 1;
552 # and in project config gitweb.avatar = <provider>;
553 'avatar' => {
554 'sub' => \&feature_avatar,
555 'override' => 0,
556 'default' => ['']},
558 # Enable displaying how much time and how many git commands
559 # it took to generate and display page. Disabled by default.
560 # Project specific override is not supported.
561 'timed' => {
562 'override' => 0,
563 'default' => [0]},
565 # Enable turning some links into links to actions which require
566 # JavaScript to run (like 'blame_incremental'). Not enabled by
567 # default. Project specific override is currently not supported.
568 'javascript-actions' => {
569 'override' => 0,
570 'default' => [0]},
572 # Syntax highlighting support. This is based on Daniel Svensson's
573 # and Sham Chukoury's work in gitweb-xmms2.git.
574 # It requires the 'highlight' program present in $PATH,
575 # and therefore is disabled by default.
577 # To enable system wide have in $GITWEB_CONFIG
578 # $feature{'highlight'}{'default'} = [1];
580 'highlight' => {
581 'sub' => sub { feature_bool('highlight', @_) },
582 'override' => 0,
583 'default' => [0]},
586 sub gitweb_get_feature {
587 my ($name) = @_;
588 return unless exists $feature{$name};
589 my ($sub, $override, @defaults) = (
590 $feature{$name}{'sub'},
591 $feature{$name}{'override'},
592 @{$feature{$name}{'default'}});
593 # project specific override is possible only if we have project
594 our $git_dir; # global variable, declared later
595 if (!$override || !defined $git_dir) {
596 return @defaults;
598 if (!defined $sub) {
599 warn "feature $name is not overridable";
600 return @defaults;
602 return $sub->(@defaults);
605 # A wrapper to check if a given feature is enabled.
606 # With this, you can say
608 # my $bool_feat = gitweb_check_feature('bool_feat');
609 # gitweb_check_feature('bool_feat') or somecode;
611 # instead of
613 # my ($bool_feat) = gitweb_get_feature('bool_feat');
614 # (gitweb_get_feature('bool_feat'))[0] or somecode;
616 sub gitweb_check_feature {
617 return (gitweb_get_feature(@_))[0];
621 sub feature_bool {
622 my $key = shift;
623 my ($val) = git_get_project_config($key, '--bool');
625 if (!defined $val) {
626 return ($_[0]);
627 } elsif ($val eq 'true') {
628 return (1);
629 } elsif ($val eq 'false') {
630 return (0);
634 sub feature_snapshot {
635 my (@fmts) = @_;
637 my ($val) = git_get_project_config('snapshot');
639 if ($val) {
640 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
643 return @fmts;
646 sub feature_patches {
647 my @val = (git_get_project_config('patches', '--int'));
649 if (@val) {
650 return @val;
653 return ($_[0]);
656 sub feature_avatar {
657 my @val = (git_get_project_config('avatar'));
659 return @val ? @val : @_;
662 # checking HEAD file with -e is fragile if the repository was
663 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
664 # and then pruned.
665 sub check_head_link {
666 my ($dir) = @_;
667 my $headfile = "$dir/HEAD";
668 return ((-e $headfile) ||
669 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
672 sub check_export_ok {
673 my ($dir) = @_;
674 return (check_head_link($dir) &&
675 (!$export_ok || -e "$dir/$export_ok") &&
676 (!$export_auth_hook || $export_auth_hook->($dir)));
679 # process alternate names for backward compatibility
680 # filter out unsupported (unknown) snapshot formats
681 sub filter_snapshot_fmts {
682 my @fmts = @_;
684 @fmts = map {
685 exists $known_snapshot_format_aliases{$_} ?
686 $known_snapshot_format_aliases{$_} : $_} @fmts;
687 @fmts = grep {
688 exists $known_snapshot_formats{$_} &&
689 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
692 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
693 sub evaluate_gitweb_config {
694 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
695 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
696 # die if there are errors parsing config file
697 if (-e $GITWEB_CONFIG) {
698 do $GITWEB_CONFIG;
699 die $@ if $@;
700 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
701 do $GITWEB_CONFIG_SYSTEM;
702 die $@ if $@;
706 # Get loadavg of system, to compare against $maxload.
707 # Currently it requires '/proc/loadavg' present to get loadavg;
708 # if it is not present it returns 0, which means no load checking.
709 sub get_loadavg {
710 if( -e '/proc/loadavg' ){
711 open my $fd, '<', '/proc/loadavg'
712 or return 0;
713 my @load = split(/\s+/, scalar <$fd>);
714 close $fd;
716 # The first three columns measure CPU and IO utilization of the last one,
717 # five, and 10 minute periods. The fourth column shows the number of
718 # currently running processes and the total number of processes in the m/n
719 # format. The last column displays the last process ID used.
720 return $load[0] || 0;
722 # additional checks for load average should go here for things that don't export
723 # /proc/loadavg
725 return 0;
728 # version of the core git binary
729 our $git_version;
730 sub evaluate_git_version {
731 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
732 $number_of_git_cmds++;
735 sub check_loadavg {
736 if (defined $maxload && get_loadavg() > $maxload) {
737 die_error(503, "The load average on the server is too high");
741 # ======================================================================
742 # input validation and dispatch
744 # input parameters can be collected from a variety of sources (presently, CGI
745 # and PATH_INFO), so we define an %input_params hash that collects them all
746 # together during validation: this allows subsequent uses (e.g. href()) to be
747 # agnostic of the parameter origin
749 our %input_params = ();
751 # input parameters are stored with the long parameter name as key. This will
752 # also be used in the href subroutine to convert parameters to their CGI
753 # equivalent, and since the href() usage is the most frequent one, we store
754 # the name -> CGI key mapping here, instead of the reverse.
756 # XXX: Warning: If you touch this, check the search form for updating,
757 # too.
759 our @cgi_param_mapping = (
760 project => "p",
761 action => "a",
762 file_name => "f",
763 file_parent => "fp",
764 hash => "h",
765 hash_parent => "hp",
766 hash_base => "hb",
767 hash_parent_base => "hpb",
768 page => "pg",
769 order => "o",
770 searchtext => "s",
771 searchtype => "st",
772 snapshot_format => "sf",
773 extra_options => "opt",
774 search_use_regexp => "sr",
775 # this must be last entry (for manipulation from JavaScript)
776 javascript => "js"
778 our %cgi_param_mapping = @cgi_param_mapping;
780 # we will also need to know the possible actions, for validation
781 our %actions = (
782 "blame" => \&git_blame,
783 "blame_incremental" => \&git_blame_incremental,
784 "blame_data" => \&git_blame_data,
785 "blobdiff" => \&git_blobdiff,
786 "blobdiff_plain" => \&git_blobdiff_plain,
787 "blob" => \&git_blob,
788 "blob_plain" => \&git_blob_plain,
789 "commitdiff" => \&git_commitdiff,
790 "commitdiff_plain" => \&git_commitdiff_plain,
791 "commit" => \&git_commit,
792 "forks" => \&git_forks,
793 "heads" => \&git_heads,
794 "history" => \&git_history,
795 "log" => \&git_log,
796 "patch" => \&git_patch,
797 "patches" => \&git_patches,
798 "rss" => \&git_rss,
799 "atom" => \&git_atom,
800 "search" => \&git_search,
801 "search_help" => \&git_search_help,
802 "shortlog" => \&git_shortlog,
803 "summary" => \&git_summary,
804 "tag" => \&git_tag,
805 "tags" => \&git_tags,
806 "tree" => \&git_tree,
807 "snapshot" => \&git_snapshot,
808 "object" => \&git_object,
809 # those below don't need $project
810 "opml" => \&git_opml,
811 "project_list" => \&git_project_list,
812 "project_index" => \&git_project_index,
815 # finally, we have the hash of allowed extra_options for the commands that
816 # allow them
817 our %allowed_options = (
818 "--no-merges" => [ qw(rss atom log shortlog history) ],
821 our %actions_info = ();
822 sub evaluate_actions_info {
823 our %actions_info;
824 our (%actions);
826 # unless explicitely stated otherwise, default output format is html
827 foreach my $action (keys %actions) {
828 $actions_info{$action}{'output_format'} = 'html';
830 # list all exceptions; undef means variable (no definite format)
831 map { $actions_info{$_}{'output_format'} = 'text' }
832 qw(commitdiff_plain patch patches project_index blame_data);
833 map { $actions_info{$_}{'output_format'} = 'xml' }
834 qw(rss atom opml); # there are different types (document formats) of XML
835 map { $actions_info{$_}{'output_format'} = undef }
836 qw(blob_plain object);
837 $actions_info{'snapshot'}{'output_format'} = 'binary';
840 # fill %input_params with the CGI parameters. All values except for 'opt'
841 # should be single values, but opt can be an array. We should probably
842 # build an array of parameters that can be multi-valued, but since for the time
843 # being it's only this one, we just single it out
844 sub evaluate_query_params {
845 our $cgi;
847 while (my ($name, $symbol) = each %cgi_param_mapping) {
848 if ($symbol eq 'opt') {
849 $input_params{$name} = [ $cgi->param($symbol) ];
850 } else {
851 $input_params{$name} = $cgi->param($symbol);
856 # now read PATH_INFO and update the parameter list for missing parameters
857 sub evaluate_path_info {
858 return if defined $input_params{'project'};
859 return if !$path_info;
860 $path_info =~ s,^/+,,;
861 return if !$path_info;
863 # find which part of PATH_INFO is project
864 my $project = $path_info;
865 $project =~ s,/+$,,;
866 while ($project && !check_head_link("$projectroot/$project")) {
867 $project =~ s,/*[^/]*$,,;
869 return unless $project;
870 $input_params{'project'} = $project;
872 # do not change any parameters if an action is given using the query string
873 return if $input_params{'action'};
874 $path_info =~ s,^\Q$project\E/*,,;
876 # next, check if we have an action
877 my $action = $path_info;
878 $action =~ s,/.*$,,;
879 if (exists $actions{$action}) {
880 $path_info =~ s,^$action/*,,;
881 $input_params{'action'} = $action;
884 # list of actions that want hash_base instead of hash, but can have no
885 # pathname (f) parameter
886 my @wants_base = (
887 'tree',
888 'history',
891 # we want to catch, among others
892 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
893 my ($parentrefname, $parentpathname, $refname, $pathname) =
894 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
896 # first, analyze the 'current' part
897 if (defined $pathname) {
898 # we got "branch:filename" or "branch:dir/"
899 # we could use git_get_type(branch:pathname), but:
900 # - it needs $git_dir
901 # - it does a git() call
902 # - the convention of terminating directories with a slash
903 # makes it superfluous
904 # - embedding the action in the PATH_INFO would make it even
905 # more superfluous
906 $pathname =~ s,^/+,,;
907 if (!$pathname || substr($pathname, -1) eq "/") {
908 $input_params{'action'} ||= "tree";
909 $pathname =~ s,/$,,;
910 } else {
911 # the default action depends on whether we had parent info
912 # or not
913 if ($parentrefname) {
914 $input_params{'action'} ||= "blobdiff_plain";
915 } else {
916 $input_params{'action'} ||= "blob_plain";
919 $input_params{'hash_base'} ||= $refname;
920 $input_params{'file_name'} ||= $pathname;
921 } elsif (defined $refname) {
922 # we got "branch". In this case we have to choose if we have to
923 # set hash or hash_base.
925 # Most of the actions without a pathname only want hash to be
926 # set, except for the ones specified in @wants_base that want
927 # hash_base instead. It should also be noted that hand-crafted
928 # links having 'history' as an action and no pathname or hash
929 # set will fail, but that happens regardless of PATH_INFO.
930 if (defined $parentrefname) {
931 # if there is parent let the default be 'shortlog' action
932 # (for http://git.example.com/repo.git/A..B links); if there
933 # is no parent, dispatch will detect type of object and set
934 # action appropriately if required (if action is not set)
935 $input_params{'action'} ||= "shortlog";
937 if ($input_params{'action'} &&
938 grep { $_ eq $input_params{'action'} } @wants_base) {
939 $input_params{'hash_base'} ||= $refname;
940 } else {
941 $input_params{'hash'} ||= $refname;
945 # next, handle the 'parent' part, if present
946 if (defined $parentrefname) {
947 # a missing pathspec defaults to the 'current' filename, allowing e.g.
948 # someproject/blobdiff/oldrev..newrev:/filename
949 if ($parentpathname) {
950 $parentpathname =~ s,^/+,,;
951 $parentpathname =~ s,/$,,;
952 $input_params{'file_parent'} ||= $parentpathname;
953 } else {
954 $input_params{'file_parent'} ||= $input_params{'file_name'};
956 # we assume that hash_parent_base is wanted if a path was specified,
957 # or if the action wants hash_base instead of hash
958 if (defined $input_params{'file_parent'} ||
959 grep { $_ eq $input_params{'action'} } @wants_base) {
960 $input_params{'hash_parent_base'} ||= $parentrefname;
961 } else {
962 $input_params{'hash_parent'} ||= $parentrefname;
966 # for the snapshot action, we allow URLs in the form
967 # $project/snapshot/$hash.ext
968 # where .ext determines the snapshot and gets removed from the
969 # passed $refname to provide the $hash.
971 # To be able to tell that $refname includes the format extension, we
972 # require the following two conditions to be satisfied:
973 # - the hash input parameter MUST have been set from the $refname part
974 # of the URL (i.e. they must be equal)
975 # - the snapshot format MUST NOT have been defined already (e.g. from
976 # CGI parameter sf)
977 # It's also useless to try any matching unless $refname has a dot,
978 # so we check for that too
979 if (defined $input_params{'action'} &&
980 $input_params{'action'} eq 'snapshot' &&
981 defined $refname && index($refname, '.') != -1 &&
982 $refname eq $input_params{'hash'} &&
983 !defined $input_params{'snapshot_format'}) {
984 # We loop over the known snapshot formats, checking for
985 # extensions. Allowed extensions are both the defined suffix
986 # (which includes the initial dot already) and the snapshot
987 # format key itself, with a prepended dot
988 while (my ($fmt, $opt) = each %known_snapshot_formats) {
989 my $hash = $refname;
990 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
991 next;
993 my $sfx = $1;
994 # a valid suffix was found, so set the snapshot format
995 # and reset the hash parameter
996 $input_params{'snapshot_format'} = $fmt;
997 $input_params{'hash'} = $hash;
998 # we also set the format suffix to the one requested
999 # in the URL: this way a request for e.g. .tgz returns
1000 # a .tgz instead of a .tar.gz
1001 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1002 last;
1007 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1008 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1009 $searchtext, $search_regexp);
1010 sub evaluate_and_validate_params {
1011 our $action = $input_params{'action'};
1012 if (defined $action) {
1013 if (!validate_action($action)) {
1014 die_error(400, "Invalid action parameter");
1018 # parameters which are pathnames
1019 our $project = $input_params{'project'};
1020 if (defined $project) {
1021 if (!validate_project($project)) {
1022 undef $project;
1023 die_error(404, "No such project");
1027 our $file_name = $input_params{'file_name'};
1028 if (defined $file_name) {
1029 if (!validate_pathname($file_name)) {
1030 die_error(400, "Invalid file parameter");
1034 our $file_parent = $input_params{'file_parent'};
1035 if (defined $file_parent) {
1036 if (!validate_pathname($file_parent)) {
1037 die_error(400, "Invalid file parent parameter");
1041 # parameters which are refnames
1042 our $hash = $input_params{'hash'};
1043 if (defined $hash) {
1044 if (!validate_refname($hash)) {
1045 die_error(400, "Invalid hash parameter");
1049 our $hash_parent = $input_params{'hash_parent'};
1050 if (defined $hash_parent) {
1051 if (!validate_refname($hash_parent)) {
1052 die_error(400, "Invalid hash parent parameter");
1056 our $hash_base = $input_params{'hash_base'};
1057 if (defined $hash_base) {
1058 if (!validate_refname($hash_base)) {
1059 die_error(400, "Invalid hash base parameter");
1063 our @extra_options = @{$input_params{'extra_options'}};
1064 # @extra_options is always defined, since it can only be (currently) set from
1065 # CGI, and $cgi->param() returns the empty array in array context if the param
1066 # is not set
1067 foreach my $opt (@extra_options) {
1068 if (not exists $allowed_options{$opt}) {
1069 die_error(400, "Invalid option parameter");
1071 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1072 die_error(400, "Invalid option parameter for this action");
1076 our $hash_parent_base = $input_params{'hash_parent_base'};
1077 if (defined $hash_parent_base) {
1078 if (!validate_refname($hash_parent_base)) {
1079 die_error(400, "Invalid hash parent base parameter");
1083 # other parameters
1084 our $page = $input_params{'page'};
1085 if (defined $page) {
1086 if ($page =~ m/[^0-9]/) {
1087 die_error(400, "Invalid page parameter");
1091 our $searchtype = $input_params{'searchtype'};
1092 if (defined $searchtype) {
1093 if ($searchtype =~ m/[^a-z]/) {
1094 die_error(400, "Invalid searchtype parameter");
1098 our $search_use_regexp = $input_params{'search_use_regexp'};
1100 our $searchtext = $input_params{'searchtext'};
1101 our $search_regexp;
1102 if (defined $searchtext) {
1103 if (length($searchtext) < 2) {
1104 die_error(403, "At least two characters are required for search parameter");
1106 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1110 # path to the current git repository
1111 our $git_dir;
1112 sub evaluate_git_dir {
1113 our $git_dir = "$projectroot/$project" if $project;
1116 our (@snapshot_fmts, $git_avatar);
1117 sub configure_gitweb_features {
1118 # list of supported snapshot formats
1119 our @snapshot_fmts = gitweb_get_feature('snapshot');
1120 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1122 # check that the avatar feature is set to a known provider name,
1123 # and for each provider check if the dependencies are satisfied.
1124 # if the provider name is invalid or the dependencies are not met,
1125 # reset $git_avatar to the empty string.
1126 our ($git_avatar) = gitweb_get_feature('avatar');
1127 if ($git_avatar eq 'gravatar') {
1128 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1129 } elsif ($git_avatar eq 'picon') {
1130 # no dependencies
1131 } else {
1132 $git_avatar = '';
1136 # custom error handler: 'die <message>' is Internal Server Error
1137 sub handle_errors_html {
1138 my $msg = shift; # it is already HTML escaped
1140 # to avoid infinite loop where error occurs in die_error,
1141 # change handler to default handler, disabling handle_errors_html
1142 set_message("Error occured when inside die_error:\n$msg");
1144 # you cannot jump out of die_error when called as error handler;
1145 # the subroutine set via CGI::Carp::set_message is called _after_
1146 # HTTP headers are already written, so it cannot write them itself
1147 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1149 set_message(\&handle_errors_html);
1151 # dispatch
1152 sub dispatch {
1153 if (!defined $action) {
1154 if (defined $hash) {
1155 $action = git_get_type($hash);
1156 } elsif (defined $hash_base && defined $file_name) {
1157 $action = git_get_type("$hash_base:$file_name");
1158 } elsif (defined $project) {
1159 $action = 'summary';
1160 } else {
1161 $action = 'project_list';
1164 if (!defined($actions{$action})) {
1165 die_error(400, "Unknown action");
1167 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1168 !$project) {
1169 die_error(400, "Project needed");
1172 if ($caching_enabled) {
1173 # human readable key identifying gitweb output
1174 my $output_key = href(-replay => 1, -full => 1, -path_info => 0);
1176 cache_output($cache, $capture, $output_key, $actions{$action});
1177 } else {
1178 $actions{$action}->();
1182 sub reset_timer {
1183 our $t0 = [Time::HiRes::gettimeofday()]
1184 if defined $t0;
1185 our $number_of_git_cmds = 0;
1188 sub run_request {
1189 reset_timer();
1191 evaluate_uri();
1192 evaluate_gitweb_config();
1193 evaluate_git_version();
1194 check_loadavg();
1195 configure_caching()
1196 if ($caching_enabled);
1198 # $projectroot and $projects_list might be set in gitweb config file
1199 $projects_list ||= $projectroot;
1201 evaluate_query_params();
1202 evaluate_path_info();
1203 evaluate_and_validate_params();
1204 evaluate_git_dir();
1206 configure_gitweb_features();
1208 dispatch();
1211 our $is_last_request = sub { 1 };
1212 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1213 our $CGI = 'CGI';
1214 our $cgi;
1215 sub configure_as_fcgi {
1216 require CGI::Fast;
1217 our $CGI = 'CGI::Fast';
1219 my $request_number = 0;
1220 # let each child service 100 requests
1221 our $is_last_request = sub { ++$request_number > 100 };
1223 sub evaluate_argv {
1224 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1225 configure_as_fcgi()
1226 if $script_name =~ /\.fcgi$/;
1228 return unless (@ARGV);
1230 require Getopt::Long;
1231 Getopt::Long::GetOptions(
1232 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1233 'nproc|n=i' => sub {
1234 my ($arg, $val) = @_;
1235 return unless eval { require FCGI::ProcManager; 1; };
1236 my $proc_manager = FCGI::ProcManager->new({
1237 n_processes => $val,
1239 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1240 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1241 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1246 sub run {
1247 evaluate_argv();
1248 evaluate_actions_info();
1250 $pre_listen_hook->()
1251 if $pre_listen_hook;
1253 REQUEST:
1254 while ($cgi = $CGI->new()) {
1255 $pre_dispatch_hook->()
1256 if $pre_dispatch_hook;
1258 run_request();
1260 $post_dispatch_hook->()
1261 if $post_dispatch_hook;
1263 last REQUEST if ($is_last_request->());
1266 DONE_GITWEB:
1270 sub configure_caching {
1271 if (!eval { require GitwebCache::CacheOutput; 1; }) {
1272 # cache is configured _before_ handling request, so $cgi is not defined,
1273 # so we can't just "die" with sending error message to web browser
1274 #die_error(500, "Caching enabled and GitwebCache::CacheOutput not found");
1276 # turn off caching and warn instead
1277 $caching_enabled = 0;
1278 warn "Caching enabled and GitwebCache::CacheOutput not found";
1280 GitwebCache::CacheOutput->import();
1282 # $cache might be initialized (instantiated) cache, i.e. cache object,
1283 # or it might be name of class, or it might be undefined
1284 unless (defined $cache && ref($cache)) {
1285 $cache ||= 'GitwebCache::FileCacheWithLocking';
1286 eval "require $cache";
1287 die $@ if $@;
1288 $cache = $cache->new({
1289 %cache_options,
1290 #'cache_root' => '/tmp/cache',
1291 #'cache_depth' => 2,
1292 #'expires_in' => 20, # in seconds (CHI compatibile)
1293 # (Cache::Cache compatibile initialization)
1294 'default_expires_in' => $cache_options{'expires_in'},
1295 # (CHI compatibile initialization)
1296 'root_dir' => $cache_options{'cache_root'},
1297 'depth' => $cache_options{'cache_depth'},
1300 unless (defined $capture && ref($capture)) {
1301 require GitwebCache::Capture::Simple;
1302 $capture = GitwebCache::Capture::Simple->new();
1306 run();
1308 if (defined caller) {
1309 # wrapped in a subroutine processing requests,
1310 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1311 return;
1312 } else {
1313 # pure CGI script, serving single request
1314 exit;
1317 ## ======================================================================
1318 ## action links
1320 # possible values of extra options
1321 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1322 # -replay => 1 - start from a current view (replay with modifications)
1323 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1324 sub href {
1325 my %params = @_;
1326 # default is to use -absolute url() i.e. $my_uri
1327 my $href = $params{-full} ? $my_url : $my_uri;
1329 $params{'project'} = $project unless exists $params{'project'};
1331 if ($params{-replay}) {
1332 while (my ($name, $symbol) = each %cgi_param_mapping) {
1333 if (!exists $params{$name}) {
1334 $params{$name} = $input_params{$name};
1339 my $use_pathinfo = gitweb_check_feature('pathinfo');
1340 if (defined $params{'project'} &&
1341 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1342 # try to put as many parameters as possible in PATH_INFO:
1343 # - project name
1344 # - action
1345 # - hash_parent or hash_parent_base:/file_parent
1346 # - hash or hash_base:/filename
1347 # - the snapshot_format as an appropriate suffix
1349 # When the script is the root DirectoryIndex for the domain,
1350 # $href here would be something like http://gitweb.example.com/
1351 # Thus, we strip any trailing / from $href, to spare us double
1352 # slashes in the final URL
1353 $href =~ s,/$,,;
1355 # Then add the project name, if present
1356 $href .= "/".esc_url($params{'project'});
1357 delete $params{'project'};
1359 # since we destructively absorb parameters, we keep this
1360 # boolean that remembers if we're handling a snapshot
1361 my $is_snapshot = $params{'action'} eq 'snapshot';
1363 # Summary just uses the project path URL, any other action is
1364 # added to the URL
1365 if (defined $params{'action'}) {
1366 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1367 delete $params{'action'};
1370 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1371 # stripping nonexistent or useless pieces
1372 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1373 || $params{'hash_parent'} || $params{'hash'});
1374 if (defined $params{'hash_base'}) {
1375 if (defined $params{'hash_parent_base'}) {
1376 $href .= esc_url($params{'hash_parent_base'});
1377 # skip the file_parent if it's the same as the file_name
1378 if (defined $params{'file_parent'}) {
1379 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1380 delete $params{'file_parent'};
1381 } elsif ($params{'file_parent'} !~ /\.\./) {
1382 $href .= ":/".esc_url($params{'file_parent'});
1383 delete $params{'file_parent'};
1386 $href .= "..";
1387 delete $params{'hash_parent'};
1388 delete $params{'hash_parent_base'};
1389 } elsif (defined $params{'hash_parent'}) {
1390 $href .= esc_url($params{'hash_parent'}). "..";
1391 delete $params{'hash_parent'};
1394 $href .= esc_url($params{'hash_base'});
1395 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1396 $href .= ":/".esc_url($params{'file_name'});
1397 delete $params{'file_name'};
1399 delete $params{'hash'};
1400 delete $params{'hash_base'};
1401 } elsif (defined $params{'hash'}) {
1402 $href .= esc_url($params{'hash'});
1403 delete $params{'hash'};
1406 # If the action was a snapshot, we can absorb the
1407 # snapshot_format parameter too
1408 if ($is_snapshot) {
1409 my $fmt = $params{'snapshot_format'};
1410 # snapshot_format should always be defined when href()
1411 # is called, but just in case some code forgets, we
1412 # fall back to the default
1413 $fmt ||= $snapshot_fmts[0];
1414 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1415 delete $params{'snapshot_format'};
1419 # now encode the parameters explicitly
1420 my @result = ();
1421 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1422 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1423 if (defined $params{$name}) {
1424 if (ref($params{$name}) eq "ARRAY") {
1425 foreach my $par (@{$params{$name}}) {
1426 push @result, $symbol . "=" . esc_param($par);
1428 } else {
1429 push @result, $symbol . "=" . esc_param($params{$name});
1433 $href .= "?" . join(';', @result) if scalar @result;
1435 return $href;
1439 ## ======================================================================
1440 ## validation, quoting/unquoting and escaping
1442 sub validate_action {
1443 my $input = shift || return undef;
1444 return undef unless exists $actions{$input};
1445 return $input;
1448 sub validate_project {
1449 my $input = shift || return undef;
1450 if (!validate_pathname($input) ||
1451 !(-d "$projectroot/$input") ||
1452 !check_export_ok("$projectroot/$input") ||
1453 ($strict_export && !project_in_list($input))) {
1454 return undef;
1455 } else {
1456 return $input;
1460 sub validate_pathname {
1461 my $input = shift || return undef;
1463 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1464 # at the beginning, at the end, and between slashes.
1465 # also this catches doubled slashes
1466 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1467 return undef;
1469 # no null characters
1470 if ($input =~ m!\0!) {
1471 return undef;
1473 return $input;
1476 sub validate_refname {
1477 my $input = shift || return undef;
1479 # textual hashes are O.K.
1480 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1481 return $input;
1483 # it must be correct pathname
1484 $input = validate_pathname($input)
1485 or return undef;
1486 # restrictions on ref name according to git-check-ref-format
1487 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1488 return undef;
1490 return $input;
1493 # decode sequences of octets in utf8 into Perl's internal form,
1494 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1495 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1496 sub to_utf8 {
1497 my $str = shift;
1498 return undef unless defined $str;
1499 if (utf8::valid($str)) {
1500 utf8::decode($str);
1501 return $str;
1502 } else {
1503 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1507 # quote unsafe chars, but keep the slash, even when it's not
1508 # correct, but quoted slashes look too horrible in bookmarks
1509 sub esc_param {
1510 my $str = shift;
1511 return undef unless defined $str;
1512 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1513 $str =~ s/ /\+/g;
1514 return $str;
1517 # quote unsafe chars in whole URL, so some characters cannot be quoted
1518 sub esc_url {
1519 my $str = shift;
1520 return undef unless defined $str;
1521 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1522 $str =~ s/ /\+/g;
1523 return $str;
1526 # replace invalid utf8 character with SUBSTITUTION sequence
1527 sub esc_html {
1528 my $str = shift;
1529 my %opts = @_;
1531 return undef unless defined $str;
1533 $str = to_utf8($str);
1534 $str = $cgi->escapeHTML($str);
1535 if ($opts{'-nbsp'}) {
1536 $str =~ s/ /&nbsp;/g;
1538 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1539 return $str;
1542 # quote control characters and escape filename to HTML
1543 sub esc_path {
1544 my $str = shift;
1545 my %opts = @_;
1547 return undef unless defined $str;
1549 $str = to_utf8($str);
1550 $str = $cgi->escapeHTML($str);
1551 if ($opts{'-nbsp'}) {
1552 $str =~ s/ /&nbsp;/g;
1554 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1555 return $str;
1558 # Make control characters "printable", using character escape codes (CEC)
1559 sub quot_cec {
1560 my $cntrl = shift;
1561 my %opts = @_;
1562 my %es = ( # character escape codes, aka escape sequences
1563 "\t" => '\t', # tab (HT)
1564 "\n" => '\n', # line feed (LF)
1565 "\r" => '\r', # carrige return (CR)
1566 "\f" => '\f', # form feed (FF)
1567 "\b" => '\b', # backspace (BS)
1568 "\a" => '\a', # alarm (bell) (BEL)
1569 "\e" => '\e', # escape (ESC)
1570 "\013" => '\v', # vertical tab (VT)
1571 "\000" => '\0', # nul character (NUL)
1573 my $chr = ( (exists $es{$cntrl})
1574 ? $es{$cntrl}
1575 : sprintf('\%2x', ord($cntrl)) );
1576 if ($opts{-nohtml}) {
1577 return $chr;
1578 } else {
1579 return "<span class=\"cntrl\">$chr</span>";
1583 # Alternatively use unicode control pictures codepoints,
1584 # Unicode "printable representation" (PR)
1585 sub quot_upr {
1586 my $cntrl = shift;
1587 my %opts = @_;
1589 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1590 if ($opts{-nohtml}) {
1591 return $chr;
1592 } else {
1593 return "<span class=\"cntrl\">$chr</span>";
1597 # git may return quoted and escaped filenames
1598 sub unquote {
1599 my $str = shift;
1601 sub unq {
1602 my $seq = shift;
1603 my %es = ( # character escape codes, aka escape sequences
1604 't' => "\t", # tab (HT, TAB)
1605 'n' => "\n", # newline (NL)
1606 'r' => "\r", # return (CR)
1607 'f' => "\f", # form feed (FF)
1608 'b' => "\b", # backspace (BS)
1609 'a' => "\a", # alarm (bell) (BEL)
1610 'e' => "\e", # escape (ESC)
1611 'v' => "\013", # vertical tab (VT)
1614 if ($seq =~ m/^[0-7]{1,3}$/) {
1615 # octal char sequence
1616 return chr(oct($seq));
1617 } elsif (exists $es{$seq}) {
1618 # C escape sequence, aka character escape code
1619 return $es{$seq};
1621 # quoted ordinary character
1622 return $seq;
1625 if ($str =~ m/^"(.*)"$/) {
1626 # needs unquoting
1627 $str = $1;
1628 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1630 return $str;
1633 # escape tabs (convert tabs to spaces)
1634 sub untabify {
1635 my $line = shift;
1637 while ((my $pos = index($line, "\t")) != -1) {
1638 if (my $count = (8 - ($pos % 8))) {
1639 my $spaces = ' ' x $count;
1640 $line =~ s/\t/$spaces/;
1644 return $line;
1647 sub project_in_list {
1648 my $project = shift;
1649 my @list = git_get_projects_list();
1650 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1653 ## ----------------------------------------------------------------------
1654 ## HTML aware string manipulation
1656 # Try to chop given string on a word boundary between position
1657 # $len and $len+$add_len. If there is no word boundary there,
1658 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1659 # (marking chopped part) would be longer than given string.
1660 sub chop_str {
1661 my $str = shift;
1662 my $len = shift;
1663 my $add_len = shift || 10;
1664 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1666 # Make sure perl knows it is utf8 encoded so we don't
1667 # cut in the middle of a utf8 multibyte char.
1668 $str = to_utf8($str);
1670 # allow only $len chars, but don't cut a word if it would fit in $add_len
1671 # if it doesn't fit, cut it if it's still longer than the dots we would add
1672 # remove chopped character entities entirely
1674 # when chopping in the middle, distribute $len into left and right part
1675 # return early if chopping wouldn't make string shorter
1676 if ($where eq 'center') {
1677 return $str if ($len + 5 >= length($str)); # filler is length 5
1678 $len = int($len/2);
1679 } else {
1680 return $str if ($len + 4 >= length($str)); # filler is length 4
1683 # regexps: ending and beginning with word part up to $add_len
1684 my $endre = qr/.{$len}\w{0,$add_len}/;
1685 my $begre = qr/\w{0,$add_len}.{$len}/;
1687 if ($where eq 'left') {
1688 $str =~ m/^(.*?)($begre)$/;
1689 my ($lead, $body) = ($1, $2);
1690 if (length($lead) > 4) {
1691 $lead = " ...";
1693 return "$lead$body";
1695 } elsif ($where eq 'center') {
1696 $str =~ m/^($endre)(.*)$/;
1697 my ($left, $str) = ($1, $2);
1698 $str =~ m/^(.*?)($begre)$/;
1699 my ($mid, $right) = ($1, $2);
1700 if (length($mid) > 5) {
1701 $mid = " ... ";
1703 return "$left$mid$right";
1705 } else {
1706 $str =~ m/^($endre)(.*)$/;
1707 my $body = $1;
1708 my $tail = $2;
1709 if (length($tail) > 4) {
1710 $tail = "... ";
1712 return "$body$tail";
1716 # takes the same arguments as chop_str, but also wraps a <span> around the
1717 # result with a title attribute if it does get chopped. Additionally, the
1718 # string is HTML-escaped.
1719 sub chop_and_escape_str {
1720 my ($str) = @_;
1722 my $chopped = chop_str(@_);
1723 if ($chopped eq $str) {
1724 return esc_html($chopped);
1725 } else {
1726 $str =~ s/[[:cntrl:]]/?/g;
1727 return $cgi->span({-title=>$str}, esc_html($chopped));
1731 ## ----------------------------------------------------------------------
1732 ## functions returning short strings
1734 # CSS class for given age value (in seconds)
1735 sub age_class {
1736 my $age = shift;
1738 if (!defined $age) {
1739 return "noage";
1740 } elsif ($age < 60*60*2) {
1741 return "age0";
1742 } elsif ($age < 60*60*24*2) {
1743 return "age1";
1744 } else {
1745 return "age2";
1749 # convert age in seconds to "nn units ago" string
1750 sub age_string {
1751 my $age = shift;
1752 my $age_str;
1754 if ($age > 60*60*24*365*2) {
1755 $age_str = (int $age/60/60/24/365);
1756 $age_str .= " years ago";
1757 } elsif ($age > 60*60*24*(365/12)*2) {
1758 $age_str = int $age/60/60/24/(365/12);
1759 $age_str .= " months ago";
1760 } elsif ($age > 60*60*24*7*2) {
1761 $age_str = int $age/60/60/24/7;
1762 $age_str .= " weeks ago";
1763 } elsif ($age > 60*60*24*2) {
1764 $age_str = int $age/60/60/24;
1765 $age_str .= " days ago";
1766 } elsif ($age > 60*60*2) {
1767 $age_str = int $age/60/60;
1768 $age_str .= " hours ago";
1769 } elsif ($age > 60*2) {
1770 $age_str = int $age/60;
1771 $age_str .= " min ago";
1772 } elsif ($age > 2) {
1773 $age_str = int $age;
1774 $age_str .= " sec ago";
1775 } else {
1776 $age_str .= " right now";
1778 return $age_str;
1781 use constant {
1782 S_IFINVALID => 0030000,
1783 S_IFGITLINK => 0160000,
1786 # submodule/subproject, a commit object reference
1787 sub S_ISGITLINK {
1788 my $mode = shift;
1790 return (($mode & S_IFMT) == S_IFGITLINK)
1793 # convert file mode in octal to symbolic file mode string
1794 sub mode_str {
1795 my $mode = oct shift;
1797 if (S_ISGITLINK($mode)) {
1798 return 'm---------';
1799 } elsif (S_ISDIR($mode & S_IFMT)) {
1800 return 'drwxr-xr-x';
1801 } elsif (S_ISLNK($mode)) {
1802 return 'lrwxrwxrwx';
1803 } elsif (S_ISREG($mode)) {
1804 # git cares only about the executable bit
1805 if ($mode & S_IXUSR) {
1806 return '-rwxr-xr-x';
1807 } else {
1808 return '-rw-r--r--';
1810 } else {
1811 return '----------';
1815 # convert file mode in octal to file type string
1816 sub file_type {
1817 my $mode = shift;
1819 if ($mode !~ m/^[0-7]+$/) {
1820 return $mode;
1821 } else {
1822 $mode = oct $mode;
1825 if (S_ISGITLINK($mode)) {
1826 return "submodule";
1827 } elsif (S_ISDIR($mode & S_IFMT)) {
1828 return "directory";
1829 } elsif (S_ISLNK($mode)) {
1830 return "symlink";
1831 } elsif (S_ISREG($mode)) {
1832 return "file";
1833 } else {
1834 return "unknown";
1838 # convert file mode in octal to file type description string
1839 sub file_type_long {
1840 my $mode = shift;
1842 if ($mode !~ m/^[0-7]+$/) {
1843 return $mode;
1844 } else {
1845 $mode = oct $mode;
1848 if (S_ISGITLINK($mode)) {
1849 return "submodule";
1850 } elsif (S_ISDIR($mode & S_IFMT)) {
1851 return "directory";
1852 } elsif (S_ISLNK($mode)) {
1853 return "symlink";
1854 } elsif (S_ISREG($mode)) {
1855 if ($mode & S_IXUSR) {
1856 return "executable";
1857 } else {
1858 return "file";
1860 } else {
1861 return "unknown";
1866 ## ----------------------------------------------------------------------
1867 ## functions returning short HTML fragments, or transforming HTML fragments
1868 ## which don't belong to other sections
1870 # format line of commit message.
1871 sub format_log_line_html {
1872 my $line = shift;
1874 $line = esc_html($line, -nbsp=>1);
1875 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1876 $cgi->a({-href => href(action=>"object", hash=>$1),
1877 -class => "text"}, $1);
1878 }eg;
1880 return $line;
1883 # format marker of refs pointing to given object
1885 # the destination action is chosen based on object type and current context:
1886 # - for annotated tags, we choose the tag view unless it's the current view
1887 # already, in which case we go to shortlog view
1888 # - for other refs, we keep the current view if we're in history, shortlog or
1889 # log view, and select shortlog otherwise
1890 sub format_ref_marker {
1891 my ($refs, $id) = @_;
1892 my $markers = '';
1894 if (defined $refs->{$id}) {
1895 foreach my $ref (@{$refs->{$id}}) {
1896 # this code exploits the fact that non-lightweight tags are the
1897 # only indirect objects, and that they are the only objects for which
1898 # we want to use tag instead of shortlog as action
1899 my ($type, $name) = qw();
1900 my $indirect = ($ref =~ s/\^\{\}$//);
1901 # e.g. tags/v2.6.11 or heads/next
1902 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1903 $type = $1;
1904 $name = $2;
1905 } else {
1906 $type = "ref";
1907 $name = $ref;
1910 my $class = $type;
1911 $class .= " indirect" if $indirect;
1913 my $dest_action = "shortlog";
1915 if ($indirect) {
1916 $dest_action = "tag" unless $action eq "tag";
1917 } elsif ($action =~ /^(history|(short)?log)$/) {
1918 $dest_action = $action;
1921 my $dest = "";
1922 $dest .= "refs/" unless $ref =~ m!^refs/!;
1923 $dest .= $ref;
1925 my $link = $cgi->a({
1926 -href => href(
1927 action=>$dest_action,
1928 hash=>$dest
1929 )}, $name);
1931 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1932 $link . "</span>";
1936 if ($markers) {
1937 return ' <span class="refs">'. $markers . '</span>';
1938 } else {
1939 return "";
1943 # format, perhaps shortened and with markers, title line
1944 sub format_subject_html {
1945 my ($long, $short, $href, $extra) = @_;
1946 $extra = '' unless defined($extra);
1948 if (length($short) < length($long)) {
1949 $long =~ s/[[:cntrl:]]/?/g;
1950 return $cgi->a({-href => $href, -class => "list subject",
1951 -title => to_utf8($long)},
1952 esc_html($short)) . $extra;
1953 } else {
1954 return $cgi->a({-href => $href, -class => "list subject"},
1955 esc_html($long)) . $extra;
1959 # Rather than recomputing the url for an email multiple times, we cache it
1960 # after the first hit. This gives a visible benefit in views where the avatar
1961 # for the same email is used repeatedly (e.g. shortlog).
1962 # The cache is shared by all avatar engines (currently gravatar only), which
1963 # are free to use it as preferred. Since only one avatar engine is used for any
1964 # given page, there's no risk for cache conflicts.
1965 our %avatar_cache = ();
1967 # Compute the picon url for a given email, by using the picon search service over at
1968 # http://www.cs.indiana.edu/picons/search.html
1969 sub picon_url {
1970 my $email = lc shift;
1971 if (!$avatar_cache{$email}) {
1972 my ($user, $domain) = split('@', $email);
1973 $avatar_cache{$email} =
1974 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1975 "$domain/$user/" .
1976 "users+domains+unknown/up/single";
1978 return $avatar_cache{$email};
1981 # Compute the gravatar url for a given email, if it's not in the cache already.
1982 # Gravatar stores only the part of the URL before the size, since that's the
1983 # one computationally more expensive. This also allows reuse of the cache for
1984 # different sizes (for this particular engine).
1985 sub gravatar_url {
1986 my $email = lc shift;
1987 my $size = shift;
1988 $avatar_cache{$email} ||=
1989 "http://www.gravatar.com/avatar/" .
1990 Digest::MD5::md5_hex($email) . "?s=";
1991 return $avatar_cache{$email} . $size;
1994 # Insert an avatar for the given $email at the given $size if the feature
1995 # is enabled.
1996 sub git_get_avatar {
1997 my ($email, %opts) = @_;
1998 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1999 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2000 $opts{-size} ||= 'default';
2001 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2002 my $url = "";
2003 if ($git_avatar eq 'gravatar') {
2004 $url = gravatar_url($email, $size);
2005 } elsif ($git_avatar eq 'picon') {
2006 $url = picon_url($email);
2008 # Other providers can be added by extending the if chain, defining $url
2009 # as needed. If no variant puts something in $url, we assume avatars
2010 # are completely disabled/unavailable.
2011 if ($url) {
2012 return $pre_white .
2013 "<img width=\"$size\" " .
2014 "class=\"avatar\" " .
2015 "src=\"$url\" " .
2016 "alt=\"\" " .
2017 "/>" . $post_white;
2018 } else {
2019 return "";
2023 sub format_search_author {
2024 my ($author, $searchtype, $displaytext) = @_;
2025 my $have_search = gitweb_check_feature('search');
2027 if ($have_search) {
2028 my $performed = "";
2029 if ($searchtype eq 'author') {
2030 $performed = "authored";
2031 } elsif ($searchtype eq 'committer') {
2032 $performed = "committed";
2035 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2036 searchtext=>$author,
2037 searchtype=>$searchtype), class=>"list",
2038 title=>"Search for commits $performed by $author"},
2039 $displaytext);
2041 } else {
2042 return $displaytext;
2046 # format the author name of the given commit with the given tag
2047 # the author name is chopped and escaped according to the other
2048 # optional parameters (see chop_str).
2049 sub format_author_html {
2050 my $tag = shift;
2051 my $co = shift;
2052 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2053 return "<$tag class=\"author\">" .
2054 format_search_author($co->{'author_name'}, "author",
2055 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2056 $author) .
2057 "</$tag>";
2060 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2061 sub format_git_diff_header_line {
2062 my $line = shift;
2063 my $diffinfo = shift;
2064 my ($from, $to) = @_;
2066 if ($diffinfo->{'nparents'}) {
2067 # combined diff
2068 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2069 if ($to->{'href'}) {
2070 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2071 esc_path($to->{'file'}));
2072 } else { # file was deleted (no href)
2073 $line .= esc_path($to->{'file'});
2075 } else {
2076 # "ordinary" diff
2077 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2078 if ($from->{'href'}) {
2079 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2080 'a/' . esc_path($from->{'file'}));
2081 } else { # file was added (no href)
2082 $line .= 'a/' . esc_path($from->{'file'});
2084 $line .= ' ';
2085 if ($to->{'href'}) {
2086 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2087 'b/' . esc_path($to->{'file'}));
2088 } else { # file was deleted
2089 $line .= 'b/' . esc_path($to->{'file'});
2093 return "<div class=\"diff header\">$line</div>\n";
2096 # format extended diff header line, before patch itself
2097 sub format_extended_diff_header_line {
2098 my $line = shift;
2099 my $diffinfo = shift;
2100 my ($from, $to) = @_;
2102 # match <path>
2103 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2104 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2105 esc_path($from->{'file'}));
2107 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2108 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2109 esc_path($to->{'file'}));
2111 # match single <mode>
2112 if ($line =~ m/\s(\d{6})$/) {
2113 $line .= '<span class="info"> (' .
2114 file_type_long($1) .
2115 ')</span>';
2117 # match <hash>
2118 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2119 # can match only for combined diff
2120 $line = 'index ';
2121 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2122 if ($from->{'href'}[$i]) {
2123 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2124 -class=>"hash"},
2125 substr($diffinfo->{'from_id'}[$i],0,7));
2126 } else {
2127 $line .= '0' x 7;
2129 # separator
2130 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2132 $line .= '..';
2133 if ($to->{'href'}) {
2134 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2135 substr($diffinfo->{'to_id'},0,7));
2136 } else {
2137 $line .= '0' x 7;
2140 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2141 # can match only for ordinary diff
2142 my ($from_link, $to_link);
2143 if ($from->{'href'}) {
2144 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2145 substr($diffinfo->{'from_id'},0,7));
2146 } else {
2147 $from_link = '0' x 7;
2149 if ($to->{'href'}) {
2150 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2151 substr($diffinfo->{'to_id'},0,7));
2152 } else {
2153 $to_link = '0' x 7;
2155 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2156 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2159 return $line . "<br/>\n";
2162 # format from-file/to-file diff header
2163 sub format_diff_from_to_header {
2164 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2165 my $line;
2166 my $result = '';
2168 $line = $from_line;
2169 #assert($line =~ m/^---/) if DEBUG;
2170 # no extra formatting for "^--- /dev/null"
2171 if (! $diffinfo->{'nparents'}) {
2172 # ordinary (single parent) diff
2173 if ($line =~ m!^--- "?a/!) {
2174 if ($from->{'href'}) {
2175 $line = '--- a/' .
2176 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2177 esc_path($from->{'file'}));
2178 } else {
2179 $line = '--- a/' .
2180 esc_path($from->{'file'});
2183 $result .= qq!<div class="diff from_file">$line</div>\n!;
2185 } else {
2186 # combined diff (merge commit)
2187 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2188 if ($from->{'href'}[$i]) {
2189 $line = '--- ' .
2190 $cgi->a({-href=>href(action=>"blobdiff",
2191 hash_parent=>$diffinfo->{'from_id'}[$i],
2192 hash_parent_base=>$parents[$i],
2193 file_parent=>$from->{'file'}[$i],
2194 hash=>$diffinfo->{'to_id'},
2195 hash_base=>$hash,
2196 file_name=>$to->{'file'}),
2197 -class=>"path",
2198 -title=>"diff" . ($i+1)},
2199 $i+1) .
2200 '/' .
2201 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2202 esc_path($from->{'file'}[$i]));
2203 } else {
2204 $line = '--- /dev/null';
2206 $result .= qq!<div class="diff from_file">$line</div>\n!;
2210 $line = $to_line;
2211 #assert($line =~ m/^\+\+\+/) if DEBUG;
2212 # no extra formatting for "^+++ /dev/null"
2213 if ($line =~ m!^\+\+\+ "?b/!) {
2214 if ($to->{'href'}) {
2215 $line = '+++ b/' .
2216 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2217 esc_path($to->{'file'}));
2218 } else {
2219 $line = '+++ b/' .
2220 esc_path($to->{'file'});
2223 $result .= qq!<div class="diff to_file">$line</div>\n!;
2225 return $result;
2228 # create note for patch simplified by combined diff
2229 sub format_diff_cc_simplified {
2230 my ($diffinfo, @parents) = @_;
2231 my $result = '';
2233 $result .= "<div class=\"diff header\">" .
2234 "diff --cc ";
2235 if (!is_deleted($diffinfo)) {
2236 $result .= $cgi->a({-href => href(action=>"blob",
2237 hash_base=>$hash,
2238 hash=>$diffinfo->{'to_id'},
2239 file_name=>$diffinfo->{'to_file'}),
2240 -class => "path"},
2241 esc_path($diffinfo->{'to_file'}));
2242 } else {
2243 $result .= esc_path($diffinfo->{'to_file'});
2245 $result .= "</div>\n" . # class="diff header"
2246 "<div class=\"diff nodifferences\">" .
2247 "Simple merge" .
2248 "</div>\n"; # class="diff nodifferences"
2250 return $result;
2253 # format patch (diff) line (not to be used for diff headers)
2254 sub format_diff_line {
2255 my $line = shift;
2256 my ($from, $to) = @_;
2257 my $diff_class = "";
2259 chomp $line;
2261 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2262 # combined diff
2263 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2264 if ($line =~ m/^\@{3}/) {
2265 $diff_class = " chunk_header";
2266 } elsif ($line =~ m/^\\/) {
2267 $diff_class = " incomplete";
2268 } elsif ($prefix =~ tr/+/+/) {
2269 $diff_class = " add";
2270 } elsif ($prefix =~ tr/-/-/) {
2271 $diff_class = " rem";
2273 } else {
2274 # assume ordinary diff
2275 my $char = substr($line, 0, 1);
2276 if ($char eq '+') {
2277 $diff_class = " add";
2278 } elsif ($char eq '-') {
2279 $diff_class = " rem";
2280 } elsif ($char eq '@') {
2281 $diff_class = " chunk_header";
2282 } elsif ($char eq "\\") {
2283 $diff_class = " incomplete";
2286 $line = untabify($line);
2287 if ($from && $to && $line =~ m/^\@{2} /) {
2288 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2289 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2291 $from_lines = 0 unless defined $from_lines;
2292 $to_lines = 0 unless defined $to_lines;
2294 if ($from->{'href'}) {
2295 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2296 -class=>"list"}, $from_text);
2298 if ($to->{'href'}) {
2299 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2300 -class=>"list"}, $to_text);
2302 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2303 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2304 return "<div class=\"diff$diff_class\">$line</div>\n";
2305 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2306 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2307 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2309 @from_text = split(' ', $ranges);
2310 for (my $i = 0; $i < @from_text; ++$i) {
2311 ($from_start[$i], $from_nlines[$i]) =
2312 (split(',', substr($from_text[$i], 1)), 0);
2315 $to_text = pop @from_text;
2316 $to_start = pop @from_start;
2317 $to_nlines = pop @from_nlines;
2319 $line = "<span class=\"chunk_info\">$prefix ";
2320 for (my $i = 0; $i < @from_text; ++$i) {
2321 if ($from->{'href'}[$i]) {
2322 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2323 -class=>"list"}, $from_text[$i]);
2324 } else {
2325 $line .= $from_text[$i];
2327 $line .= " ";
2329 if ($to->{'href'}) {
2330 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2331 -class=>"list"}, $to_text);
2332 } else {
2333 $line .= $to_text;
2335 $line .= " $prefix</span>" .
2336 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2337 return "<div class=\"diff$diff_class\">$line</div>\n";
2339 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2342 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2343 # linked. Pass the hash of the tree/commit to snapshot.
2344 sub format_snapshot_links {
2345 my ($hash) = @_;
2346 my $num_fmts = @snapshot_fmts;
2347 if ($num_fmts > 1) {
2348 # A parenthesized list of links bearing format names.
2349 # e.g. "snapshot (_tar.gz_ _zip_)"
2350 return "snapshot (" . join(' ', map
2351 $cgi->a({
2352 -href => href(
2353 action=>"snapshot",
2354 hash=>$hash,
2355 snapshot_format=>$_
2357 }, $known_snapshot_formats{$_}{'display'})
2358 , @snapshot_fmts) . ")";
2359 } elsif ($num_fmts == 1) {
2360 # A single "snapshot" link whose tooltip bears the format name.
2361 # i.e. "_snapshot_"
2362 my ($fmt) = @snapshot_fmts;
2363 return
2364 $cgi->a({
2365 -href => href(
2366 action=>"snapshot",
2367 hash=>$hash,
2368 snapshot_format=>$fmt
2370 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2371 }, "snapshot");
2372 } else { # $num_fmts == 0
2373 return undef;
2377 ## ......................................................................
2378 ## functions returning values to be passed, perhaps after some
2379 ## transformation, to other functions; e.g. returning arguments to href()
2381 # returns hash to be passed to href to generate gitweb URL
2382 # in -title key it returns description of link
2383 sub get_feed_info {
2384 my $format = shift || 'Atom';
2385 my %res = (action => lc($format));
2387 # feed links are possible only for project views
2388 return unless (defined $project);
2389 # some views should link to OPML, or to generic project feed,
2390 # or don't have specific feed yet (so they should use generic)
2391 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2393 my $branch;
2394 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2395 # from tag links; this also makes possible to detect branch links
2396 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2397 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2398 $branch = $1;
2400 # find log type for feed description (title)
2401 my $type = 'log';
2402 if (defined $file_name) {
2403 $type = "history of $file_name";
2404 $type .= "/" if ($action eq 'tree');
2405 $type .= " on '$branch'" if (defined $branch);
2406 } else {
2407 $type = "log of $branch" if (defined $branch);
2410 $res{-title} = $type;
2411 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2412 $res{'file_name'} = $file_name;
2414 return %res;
2417 ## ----------------------------------------------------------------------
2418 ## git utility subroutines, invoking git commands
2420 # returns path to the core git executable and the --git-dir parameter as list
2421 sub git_cmd {
2422 $number_of_git_cmds++;
2423 return $GIT, '--git-dir='.$git_dir;
2426 # quote the given arguments for passing them to the shell
2427 # quote_command("command", "arg 1", "arg with ' and ! characters")
2428 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2429 # Try to avoid using this function wherever possible.
2430 sub quote_command {
2431 return join(' ',
2432 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2435 # get HEAD ref of given project as hash
2436 sub git_get_head_hash {
2437 return git_get_full_hash(shift, 'HEAD');
2440 sub git_get_full_hash {
2441 return git_get_hash(@_);
2444 sub git_get_short_hash {
2445 return git_get_hash(@_, '--short=7');
2448 sub git_get_hash {
2449 my ($project, $hash, @options) = @_;
2450 my $o_git_dir = $git_dir;
2451 my $retval = undef;
2452 $git_dir = "$projectroot/$project";
2453 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2454 '--verify', '-q', @options, $hash) {
2455 $retval = <$fd>;
2456 chomp $retval if defined $retval;
2457 close $fd;
2459 if (defined $o_git_dir) {
2460 $git_dir = $o_git_dir;
2462 return $retval;
2465 # get type of given object
2466 sub git_get_type {
2467 my $hash = shift;
2469 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2470 my $type = <$fd>;
2471 close $fd or return;
2472 chomp $type;
2473 return $type;
2476 # repository configuration
2477 our $config_file = '';
2478 our %config;
2480 # store multiple values for single key as anonymous array reference
2481 # single values stored directly in the hash, not as [ <value> ]
2482 sub hash_set_multi {
2483 my ($hash, $key, $value) = @_;
2485 if (!exists $hash->{$key}) {
2486 $hash->{$key} = $value;
2487 } elsif (!ref $hash->{$key}) {
2488 $hash->{$key} = [ $hash->{$key}, $value ];
2489 } else {
2490 push @{$hash->{$key}}, $value;
2494 # return hash of git project configuration
2495 # optionally limited to some section, e.g. 'gitweb'
2496 sub git_parse_project_config {
2497 my $section_regexp = shift;
2498 my %config;
2500 local $/ = "\0";
2502 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2503 or return;
2505 while (my $keyval = <$fh>) {
2506 chomp $keyval;
2507 my ($key, $value) = split(/\n/, $keyval, 2);
2509 hash_set_multi(\%config, $key, $value)
2510 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2512 close $fh;
2514 return %config;
2517 # convert config value to boolean: 'true' or 'false'
2518 # no value, number > 0, 'true' and 'yes' values are true
2519 # rest of values are treated as false (never as error)
2520 sub config_to_bool {
2521 my $val = shift;
2523 return 1 if !defined $val; # section.key
2525 # strip leading and trailing whitespace
2526 $val =~ s/^\s+//;
2527 $val =~ s/\s+$//;
2529 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2530 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2533 # convert config value to simple decimal number
2534 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2535 # to be multiplied by 1024, 1048576, or 1073741824
2536 sub config_to_int {
2537 my $val = shift;
2539 # strip leading and trailing whitespace
2540 $val =~ s/^\s+//;
2541 $val =~ s/\s+$//;
2543 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2544 $unit = lc($unit);
2545 # unknown unit is treated as 1
2546 return $num * ($unit eq 'g' ? 1073741824 :
2547 $unit eq 'm' ? 1048576 :
2548 $unit eq 'k' ? 1024 : 1);
2550 return $val;
2553 # convert config value to array reference, if needed
2554 sub config_to_multi {
2555 my $val = shift;
2557 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2560 sub git_get_project_config {
2561 my ($key, $type) = @_;
2563 return unless defined $git_dir;
2565 # key sanity check
2566 return unless ($key);
2567 $key =~ s/^gitweb\.//;
2568 return if ($key =~ m/\W/);
2570 # type sanity check
2571 if (defined $type) {
2572 $type =~ s/^--//;
2573 $type = undef
2574 unless ($type eq 'bool' || $type eq 'int');
2577 # get config
2578 if (!defined $config_file ||
2579 $config_file ne "$git_dir/config") {
2580 %config = git_parse_project_config('gitweb');
2581 $config_file = "$git_dir/config";
2584 # check if config variable (key) exists
2585 return unless exists $config{"gitweb.$key"};
2587 # ensure given type
2588 if (!defined $type) {
2589 return $config{"gitweb.$key"};
2590 } elsif ($type eq 'bool') {
2591 # backward compatibility: 'git config --bool' returns true/false
2592 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2593 } elsif ($type eq 'int') {
2594 return config_to_int($config{"gitweb.$key"});
2596 return $config{"gitweb.$key"};
2599 # get hash of given path at given ref
2600 sub git_get_hash_by_path {
2601 my $base = shift;
2602 my $path = shift || return undef;
2603 my $type = shift;
2605 $path =~ s,/+$,,;
2607 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2608 or die_error(500, "Open git-ls-tree failed");
2609 my $line = <$fd>;
2610 close $fd or return undef;
2612 if (!defined $line) {
2613 # there is no tree or hash given by $path at $base
2614 return undef;
2617 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2618 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2619 if (defined $type && $type ne $2) {
2620 # type doesn't match
2621 return undef;
2623 return $3;
2626 # get path of entry with given hash at given tree-ish (ref)
2627 # used to get 'from' filename for combined diff (merge commit) for renames
2628 sub git_get_path_by_hash {
2629 my $base = shift || return;
2630 my $hash = shift || return;
2632 local $/ = "\0";
2634 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2635 or return undef;
2636 while (my $line = <$fd>) {
2637 chomp $line;
2639 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2640 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2641 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2642 close $fd;
2643 return $1;
2646 close $fd;
2647 return undef;
2650 ## ......................................................................
2651 ## git utility functions, directly accessing git repository
2653 sub git_get_project_description {
2654 my $path = shift;
2656 $git_dir = "$projectroot/$path";
2657 open my $fd, '<', "$git_dir/description"
2658 or return git_get_project_config('description');
2659 my $descr = <$fd>;
2660 close $fd;
2661 if (defined $descr) {
2662 chomp $descr;
2664 return $descr;
2667 sub git_get_project_ctags {
2668 my $path = shift;
2669 my $ctags = {};
2671 $git_dir = "$projectroot/$path";
2672 opendir my $dh, "$git_dir/ctags"
2673 or return $ctags;
2674 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2675 open my $ct, '<', $_ or next;
2676 my $val = <$ct>;
2677 chomp $val;
2678 close $ct;
2679 my $ctag = $_; $ctag =~ s#.*/##;
2680 $ctags->{$ctag} = $val;
2682 closedir $dh;
2683 $ctags;
2686 sub git_populate_project_tagcloud {
2687 my $ctags = shift;
2689 # First, merge different-cased tags; tags vote on casing
2690 my %ctags_lc;
2691 foreach (keys %$ctags) {
2692 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2693 if (not $ctags_lc{lc $_}->{topcount}
2694 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2695 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2696 $ctags_lc{lc $_}->{topname} = $_;
2700 my $cloud;
2701 if (eval { require HTML::TagCloud; 1; }) {
2702 $cloud = HTML::TagCloud->new;
2703 foreach (sort keys %ctags_lc) {
2704 # Pad the title with spaces so that the cloud looks
2705 # less crammed.
2706 my $title = $ctags_lc{$_}->{topname};
2707 $title =~ s/ /&nbsp;/g;
2708 $title =~ s/^/&nbsp;/g;
2709 $title =~ s/$/&nbsp;/g;
2710 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2712 } else {
2713 $cloud = \%ctags_lc;
2715 $cloud;
2718 sub git_show_project_tagcloud {
2719 my ($cloud, $count) = @_;
2720 print STDERR ref($cloud)."..\n";
2721 if (ref $cloud eq 'HTML::TagCloud') {
2722 return $cloud->html_and_css($count);
2723 } else {
2724 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2725 return '<p align="center">' . join (', ', map {
2726 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2727 } splice(@tags, 0, $count)) . '</p>';
2731 sub git_get_project_url_list {
2732 my $path = shift;
2734 $git_dir = "$projectroot/$path";
2735 open my $fd, '<', "$git_dir/cloneurl"
2736 or return wantarray ?
2737 @{ config_to_multi(git_get_project_config('url')) } :
2738 config_to_multi(git_get_project_config('url'));
2739 my @git_project_url_list = map { chomp; $_ } <$fd>;
2740 close $fd;
2742 return wantarray ? @git_project_url_list : \@git_project_url_list;
2745 sub git_get_projects_list {
2746 my ($filter) = @_;
2747 my @list;
2749 $filter ||= '';
2750 $filter =~ s/\.git$//;
2752 my $check_forks = gitweb_check_feature('forks');
2754 if (-d $projects_list) {
2755 # search in directory
2756 my $dir = $projects_list . ($filter ? "/$filter" : '');
2757 # remove the trailing "/"
2758 $dir =~ s!/+$!!;
2759 my $pfxlen = length("$dir");
2760 my $pfxdepth = ($dir =~ tr!/!!);
2762 File::Find::find({
2763 follow_fast => 1, # follow symbolic links
2764 follow_skip => 2, # ignore duplicates
2765 dangling_symlinks => 0, # ignore dangling symlinks, silently
2766 wanted => sub {
2767 # global variables
2768 our $project_maxdepth;
2769 our $projectroot;
2770 # skip project-list toplevel, if we get it.
2771 return if (m!^[/.]$!);
2772 # only directories can be git repositories
2773 return unless (-d $_);
2774 # don't traverse too deep (Find is super slow on os x)
2775 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2776 $File::Find::prune = 1;
2777 return;
2780 my $subdir = substr($File::Find::name, $pfxlen + 1);
2781 # we check related file in $projectroot
2782 my $path = ($filter ? "$filter/" : '') . $subdir;
2783 if (check_export_ok("$projectroot/$path")) {
2784 push @list, { path => $path };
2785 $File::Find::prune = 1;
2788 }, "$dir");
2790 } elsif (-f $projects_list) {
2791 # read from file(url-encoded):
2792 # 'git%2Fgit.git Linus+Torvalds'
2793 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2794 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2795 my %paths;
2796 open my $fd, '<', $projects_list or return;
2797 PROJECT:
2798 while (my $line = <$fd>) {
2799 chomp $line;
2800 my ($path, $owner) = split ' ', $line;
2801 $path = unescape($path);
2802 $owner = unescape($owner);
2803 if (!defined $path) {
2804 next;
2806 if ($filter ne '') {
2807 # looking for forks;
2808 my $pfx = substr($path, 0, length($filter));
2809 if ($pfx ne $filter) {
2810 next PROJECT;
2812 my $sfx = substr($path, length($filter));
2813 if ($sfx !~ /^\/.*\.git$/) {
2814 next PROJECT;
2816 } elsif ($check_forks) {
2817 PATH:
2818 foreach my $filter (keys %paths) {
2819 # looking for forks;
2820 my $pfx = substr($path, 0, length($filter));
2821 if ($pfx ne $filter) {
2822 next PATH;
2824 my $sfx = substr($path, length($filter));
2825 if ($sfx !~ /^\/.*\.git$/) {
2826 next PATH;
2828 # is a fork, don't include it in
2829 # the list
2830 next PROJECT;
2833 if (check_export_ok("$projectroot/$path")) {
2834 my $pr = {
2835 path => $path,
2836 owner => to_utf8($owner),
2838 push @list, $pr;
2839 (my $forks_path = $path) =~ s/\.git$//;
2840 $paths{$forks_path}++;
2843 close $fd;
2845 return @list;
2848 our $gitweb_project_owner = undef;
2849 sub git_get_project_list_from_file {
2851 return if (defined $gitweb_project_owner);
2853 $gitweb_project_owner = {};
2854 # read from file (url-encoded):
2855 # 'git%2Fgit.git Linus+Torvalds'
2856 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2857 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2858 if (-f $projects_list) {
2859 open(my $fd, '<', $projects_list);
2860 while (my $line = <$fd>) {
2861 chomp $line;
2862 my ($pr, $ow) = split ' ', $line;
2863 $pr = unescape($pr);
2864 $ow = unescape($ow);
2865 $gitweb_project_owner->{$pr} = to_utf8($ow);
2867 close $fd;
2871 sub git_get_project_owner {
2872 my $project = shift;
2873 my $owner;
2875 return undef unless $project;
2876 $git_dir = "$projectroot/$project";
2878 if (!defined $gitweb_project_owner) {
2879 git_get_project_list_from_file();
2882 if (exists $gitweb_project_owner->{$project}) {
2883 $owner = $gitweb_project_owner->{$project};
2885 if (!defined $owner){
2886 $owner = git_get_project_config('owner');
2888 if (!defined $owner) {
2889 $owner = get_file_owner("$git_dir");
2892 return $owner;
2895 sub git_get_last_activity {
2896 my ($path) = @_;
2897 my $fd;
2899 $git_dir = "$projectroot/$path";
2900 open($fd, "-|", git_cmd(), 'for-each-ref',
2901 '--format=%(committer)',
2902 '--sort=-committerdate',
2903 '--count=1',
2904 'refs/heads') or return;
2905 my $most_recent = <$fd>;
2906 close $fd or return;
2907 if (defined $most_recent &&
2908 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2909 my $timestamp = $1;
2910 my $age = time - $timestamp;
2911 return ($age, age_string($age));
2913 return (undef, undef);
2916 sub git_get_references {
2917 my $type = shift || "";
2918 my %refs;
2919 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2920 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2921 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2922 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2923 or return;
2925 while (my $line = <$fd>) {
2926 chomp $line;
2927 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2928 if (defined $refs{$1}) {
2929 push @{$refs{$1}}, $2;
2930 } else {
2931 $refs{$1} = [ $2 ];
2935 close $fd or return;
2936 return \%refs;
2939 sub git_get_rev_name_tags {
2940 my $hash = shift || return undef;
2942 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2943 or return;
2944 my $name_rev = <$fd>;
2945 close $fd;
2947 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2948 return $1;
2949 } else {
2950 # catches also '$hash undefined' output
2951 return undef;
2955 ## ----------------------------------------------------------------------
2956 ## parse to hash functions
2958 sub parse_date {
2959 my $epoch = shift;
2960 my $tz = shift || "-0000";
2962 my %date;
2963 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2964 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2965 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2966 $date{'hour'} = $hour;
2967 $date{'minute'} = $min;
2968 $date{'mday'} = $mday;
2969 $date{'day'} = $days[$wday];
2970 $date{'month'} = $months[$mon];
2971 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2972 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2973 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2974 $mday, $months[$mon], $hour ,$min;
2975 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2976 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2978 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2979 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2980 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2981 $date{'hour_local'} = $hour;
2982 $date{'minute_local'} = $min;
2983 $date{'tz_local'} = $tz;
2984 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2985 1900+$year, $mon+1, $mday,
2986 $hour, $min, $sec, $tz);
2987 return %date;
2990 sub parse_tag {
2991 my $tag_id = shift;
2992 my %tag;
2993 my @comment;
2995 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2996 $tag{'id'} = $tag_id;
2997 while (my $line = <$fd>) {
2998 chomp $line;
2999 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3000 $tag{'object'} = $1;
3001 } elsif ($line =~ m/^type (.+)$/) {
3002 $tag{'type'} = $1;
3003 } elsif ($line =~ m/^tag (.+)$/) {
3004 $tag{'name'} = $1;
3005 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3006 $tag{'author'} = $1;
3007 $tag{'author_epoch'} = $2;
3008 $tag{'author_tz'} = $3;
3009 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3010 $tag{'author_name'} = $1;
3011 $tag{'author_email'} = $2;
3012 } else {
3013 $tag{'author_name'} = $tag{'author'};
3015 } elsif ($line =~ m/--BEGIN/) {
3016 push @comment, $line;
3017 last;
3018 } elsif ($line eq "") {
3019 last;
3022 push @comment, <$fd>;
3023 $tag{'comment'} = \@comment;
3024 close $fd or return;
3025 if (!defined $tag{'name'}) {
3026 return
3028 return %tag
3031 sub parse_commit_text {
3032 my ($commit_text, $withparents) = @_;
3033 my @commit_lines = split '\n', $commit_text;
3034 my %co;
3036 pop @commit_lines; # Remove '\0'
3038 if (! @commit_lines) {
3039 return;
3042 my $header = shift @commit_lines;
3043 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3044 return;
3046 ($co{'id'}, my @parents) = split ' ', $header;
3047 while (my $line = shift @commit_lines) {
3048 last if $line eq "\n";
3049 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3050 $co{'tree'} = $1;
3051 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3052 push @parents, $1;
3053 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3054 $co{'author'} = to_utf8($1);
3055 $co{'author_epoch'} = $2;
3056 $co{'author_tz'} = $3;
3057 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3058 $co{'author_name'} = $1;
3059 $co{'author_email'} = $2;
3060 } else {
3061 $co{'author_name'} = $co{'author'};
3063 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3064 $co{'committer'} = to_utf8($1);
3065 $co{'committer_epoch'} = $2;
3066 $co{'committer_tz'} = $3;
3067 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3068 $co{'committer_name'} = $1;
3069 $co{'committer_email'} = $2;
3070 } else {
3071 $co{'committer_name'} = $co{'committer'};
3075 if (!defined $co{'tree'}) {
3076 return;
3078 $co{'parents'} = \@parents;
3079 $co{'parent'} = $parents[0];
3081 foreach my $title (@commit_lines) {
3082 $title =~ s/^ //;
3083 if ($title ne "") {
3084 $co{'title'} = chop_str($title, 80, 5);
3085 # remove leading stuff of merges to make the interesting part visible
3086 if (length($title) > 50) {
3087 $title =~ s/^Automatic //;
3088 $title =~ s/^merge (of|with) /Merge ... /i;
3089 if (length($title) > 50) {
3090 $title =~ s/(http|rsync):\/\///;
3092 if (length($title) > 50) {
3093 $title =~ s/(master|www|rsync)\.//;
3095 if (length($title) > 50) {
3096 $title =~ s/kernel.org:?//;
3098 if (length($title) > 50) {
3099 $title =~ s/\/pub\/scm//;
3102 $co{'title_short'} = chop_str($title, 50, 5);
3103 last;
3106 if (! defined $co{'title'} || $co{'title'} eq "") {
3107 $co{'title'} = $co{'title_short'} = '(no commit message)';
3109 # remove added spaces
3110 foreach my $line (@commit_lines) {
3111 $line =~ s/^ //;
3113 $co{'comment'} = \@commit_lines;
3115 my $age = time - $co{'committer_epoch'};
3116 $co{'age'} = $age;
3117 $co{'age_string'} = age_string($age);
3118 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3119 if ($age > 60*60*24*7*2) {
3120 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3121 $co{'age_string_age'} = $co{'age_string'};
3122 } else {
3123 $co{'age_string_date'} = $co{'age_string'};
3124 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3126 return %co;
3129 sub parse_commit {
3130 my ($commit_id) = @_;
3131 my %co;
3133 local $/ = "\0";
3135 open my $fd, "-|", git_cmd(), "rev-list",
3136 "--parents",
3137 "--header",
3138 "--max-count=1",
3139 $commit_id,
3140 "--",
3141 or die_error(500, "Open git-rev-list failed");
3142 %co = parse_commit_text(<$fd>, 1);
3143 close $fd;
3145 return %co;
3148 sub parse_commits {
3149 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3150 my @cos;
3152 $maxcount ||= 1;
3153 $skip ||= 0;
3155 local $/ = "\0";
3157 open my $fd, "-|", git_cmd(), "rev-list",
3158 "--header",
3159 @args,
3160 ("--max-count=" . $maxcount),
3161 ("--skip=" . $skip),
3162 @extra_options,
3163 $commit_id,
3164 "--",
3165 ($filename ? ($filename) : ())
3166 or die_error(500, "Open git-rev-list failed");
3167 while (my $line = <$fd>) {
3168 my %co = parse_commit_text($line);
3169 push @cos, \%co;
3171 close $fd;
3173 return wantarray ? @cos : \@cos;
3176 # parse line of git-diff-tree "raw" output
3177 sub parse_difftree_raw_line {
3178 my $line = shift;
3179 my %res;
3181 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3182 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3183 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3184 $res{'from_mode'} = $1;
3185 $res{'to_mode'} = $2;
3186 $res{'from_id'} = $3;
3187 $res{'to_id'} = $4;
3188 $res{'status'} = $5;
3189 $res{'similarity'} = $6;
3190 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3191 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3192 } else {
3193 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3196 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3197 # combined diff (for merge commit)
3198 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3199 $res{'nparents'} = length($1);
3200 $res{'from_mode'} = [ split(' ', $2) ];
3201 $res{'to_mode'} = pop @{$res{'from_mode'}};
3202 $res{'from_id'} = [ split(' ', $3) ];
3203 $res{'to_id'} = pop @{$res{'from_id'}};
3204 $res{'status'} = [ split('', $4) ];
3205 $res{'to_file'} = unquote($5);
3207 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3208 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3209 $res{'commit'} = $1;
3212 return wantarray ? %res : \%res;
3215 # wrapper: return parsed line of git-diff-tree "raw" output
3216 # (the argument might be raw line, or parsed info)
3217 sub parsed_difftree_line {
3218 my $line_or_ref = shift;
3220 if (ref($line_or_ref) eq "HASH") {
3221 # pre-parsed (or generated by hand)
3222 return $line_or_ref;
3223 } else {
3224 return parse_difftree_raw_line($line_or_ref);
3228 # parse line of git-ls-tree output
3229 sub parse_ls_tree_line {
3230 my $line = shift;
3231 my %opts = @_;
3232 my %res;
3234 if ($opts{'-l'}) {
3235 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3236 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3238 $res{'mode'} = $1;
3239 $res{'type'} = $2;
3240 $res{'hash'} = $3;
3241 $res{'size'} = $4;
3242 if ($opts{'-z'}) {
3243 $res{'name'} = $5;
3244 } else {
3245 $res{'name'} = unquote($5);
3247 } else {
3248 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3249 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3251 $res{'mode'} = $1;
3252 $res{'type'} = $2;
3253 $res{'hash'} = $3;
3254 if ($opts{'-z'}) {
3255 $res{'name'} = $4;
3256 } else {
3257 $res{'name'} = unquote($4);
3261 return wantarray ? %res : \%res;
3264 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3265 sub parse_from_to_diffinfo {
3266 my ($diffinfo, $from, $to, @parents) = @_;
3268 if ($diffinfo->{'nparents'}) {
3269 # combined diff
3270 $from->{'file'} = [];
3271 $from->{'href'} = [];
3272 fill_from_file_info($diffinfo, @parents)
3273 unless exists $diffinfo->{'from_file'};
3274 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3275 $from->{'file'}[$i] =
3276 defined $diffinfo->{'from_file'}[$i] ?
3277 $diffinfo->{'from_file'}[$i] :
3278 $diffinfo->{'to_file'};
3279 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3280 $from->{'href'}[$i] = href(action=>"blob",
3281 hash_base=>$parents[$i],
3282 hash=>$diffinfo->{'from_id'}[$i],
3283 file_name=>$from->{'file'}[$i]);
3284 } else {
3285 $from->{'href'}[$i] = undef;
3288 } else {
3289 # ordinary (not combined) diff
3290 $from->{'file'} = $diffinfo->{'from_file'};
3291 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3292 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3293 hash=>$diffinfo->{'from_id'},
3294 file_name=>$from->{'file'});
3295 } else {
3296 delete $from->{'href'};
3300 $to->{'file'} = $diffinfo->{'to_file'};
3301 if (!is_deleted($diffinfo)) { # file exists in result
3302 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3303 hash=>$diffinfo->{'to_id'},
3304 file_name=>$to->{'file'});
3305 } else {
3306 delete $to->{'href'};
3310 ## ......................................................................
3311 ## parse to array of hashes functions
3313 sub git_get_heads_list {
3314 my $limit = shift;
3315 my @headslist;
3317 open my $fd, '-|', git_cmd(), 'for-each-ref',
3318 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3319 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3320 'refs/heads'
3321 or return;
3322 while (my $line = <$fd>) {
3323 my %ref_item;
3325 chomp $line;
3326 my ($refinfo, $committerinfo) = split(/\0/, $line);
3327 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3328 my ($committer, $epoch, $tz) =
3329 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3330 $ref_item{'fullname'} = $name;
3331 $name =~ s!^refs/heads/!!;
3333 $ref_item{'name'} = $name;
3334 $ref_item{'id'} = $hash;
3335 $ref_item{'title'} = $title || '(no commit message)';
3336 $ref_item{'epoch'} = $epoch;
3337 if ($epoch) {
3338 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3339 } else {
3340 $ref_item{'age'} = "unknown";
3343 push @headslist, \%ref_item;
3345 close $fd;
3347 return wantarray ? @headslist : \@headslist;
3350 sub git_get_tags_list {
3351 my $limit = shift;
3352 my @tagslist;
3354 open my $fd, '-|', git_cmd(), 'for-each-ref',
3355 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3356 '--format=%(objectname) %(objecttype) %(refname) '.
3357 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3358 'refs/tags'
3359 or return;
3360 while (my $line = <$fd>) {
3361 my %ref_item;
3363 chomp $line;
3364 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3365 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3366 my ($creator, $epoch, $tz) =
3367 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3368 $ref_item{'fullname'} = $name;
3369 $name =~ s!^refs/tags/!!;
3371 $ref_item{'type'} = $type;
3372 $ref_item{'id'} = $id;
3373 $ref_item{'name'} = $name;
3374 if ($type eq "tag") {
3375 $ref_item{'subject'} = $title;
3376 $ref_item{'reftype'} = $reftype;
3377 $ref_item{'refid'} = $refid;
3378 } else {
3379 $ref_item{'reftype'} = $type;
3380 $ref_item{'refid'} = $id;
3383 if ($type eq "tag" || $type eq "commit") {
3384 $ref_item{'epoch'} = $epoch;
3385 if ($epoch) {
3386 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3387 } else {
3388 $ref_item{'age'} = "unknown";
3392 push @tagslist, \%ref_item;
3394 close $fd;
3396 return wantarray ? @tagslist : \@tagslist;
3399 ## ----------------------------------------------------------------------
3400 ## filesystem-related functions
3402 sub get_file_owner {
3403 my $path = shift;
3405 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3406 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3407 if (!defined $gcos) {
3408 return undef;
3410 my $owner = $gcos;
3411 $owner =~ s/[,;].*$//;
3412 return to_utf8($owner);
3415 # assume that file exists
3416 sub insert_file {
3417 my $filename = shift;
3419 open my $fd, '<', $filename;
3420 print map { to_utf8($_) } <$fd>;
3421 close $fd;
3424 ## ......................................................................
3425 ## mimetype related functions
3427 sub mimetype_guess_file {
3428 my $filename = shift;
3429 my $mimemap = shift;
3430 -r $mimemap or return undef;
3432 my %mimemap;
3433 open(my $mh, '<', $mimemap) or return undef;
3434 while (<$mh>) {
3435 next if m/^#/; # skip comments
3436 my ($mimetype, $exts) = split(/\t+/);
3437 if (defined $exts) {
3438 my @exts = split(/\s+/, $exts);
3439 foreach my $ext (@exts) {
3440 $mimemap{$ext} = $mimetype;
3444 close($mh);
3446 $filename =~ /\.([^.]*)$/;
3447 return $mimemap{$1};
3450 sub mimetype_guess {
3451 my $filename = shift;
3452 my $mime;
3453 $filename =~ /\./ or return undef;
3455 if ($mimetypes_file) {
3456 my $file = $mimetypes_file;
3457 if ($file !~ m!^/!) { # if it is relative path
3458 # it is relative to project
3459 $file = "$projectroot/$project/$file";
3461 $mime = mimetype_guess_file($filename, $file);
3463 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3464 return $mime;
3467 sub blob_mimetype {
3468 my $fd = shift;
3469 my $filename = shift;
3471 if ($filename) {
3472 my $mime = mimetype_guess($filename);
3473 $mime and return $mime;
3476 # just in case
3477 return $default_blob_plain_mimetype unless $fd;
3479 if (-T $fd) {
3480 return 'text/plain';
3481 } elsif (! $filename) {
3482 return 'application/octet-stream';
3483 } elsif ($filename =~ m/\.png$/i) {
3484 return 'image/png';
3485 } elsif ($filename =~ m/\.gif$/i) {
3486 return 'image/gif';
3487 } elsif ($filename =~ m/\.jpe?g$/i) {
3488 return 'image/jpeg';
3489 } else {
3490 return 'application/octet-stream';
3494 sub blob_contenttype {
3495 my ($fd, $file_name, $type) = @_;
3497 $type ||= blob_mimetype($fd, $file_name);
3498 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3499 $type .= "; charset=$default_text_plain_charset";
3502 return $type;
3505 # guess file syntax for syntax highlighting; return undef if no highlighting
3506 # the name of syntax can (in the future) depend on syntax highlighter used
3507 sub guess_file_syntax {
3508 my ($highlight, $mimetype, $file_name) = @_;
3509 return undef unless ($highlight && defined $file_name);
3510 my $basename = basename($file_name, '.in');
3511 return $highlight_basename{$basename}
3512 if exists $highlight_basename{$basename};
3514 $basename =~ /\.([^.]*)$/;
3515 my $ext = $1 or return undef;
3516 return $highlight_ext{$ext}
3517 if exists $highlight_ext{$ext};
3519 return undef;
3522 # run highlighter and return FD of its output,
3523 # or return original FD if no highlighting
3524 sub run_highlighter {
3525 my ($fd, $highlight, $syntax) = @_;
3526 return $fd unless ($highlight && defined $syntax);
3528 close $fd
3529 or die_error(404, "Reading blob failed");
3530 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3531 quote_command($highlight_bin).
3532 " --xhtml --fragment --syntax $syntax |"
3533 or die_error(500, "Couldn't open file or run syntax highlighter");
3534 return $fd;
3537 ## ======================================================================
3538 ## functions printing HTML: header, footer, error page
3540 sub get_page_title {
3541 my $title = to_utf8($site_name);
3543 return $title unless (defined $project);
3544 $title .= " - " . to_utf8($project);
3546 return $title unless (defined $action);
3547 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3549 return $title unless (defined $file_name);
3550 $title .= " - " . esc_path($file_name);
3551 if ($action eq "tree" && $file_name !~ m|/$|) {
3552 $title .= "/";
3555 return $title;
3558 sub git_header_html {
3559 my $status = shift || "200 OK";
3560 my $expires = shift;
3561 my %opts = @_;
3563 my $title = get_page_title();
3564 my $content_type;
3565 # require explicit support from the UA if we are to send the page as
3566 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3567 # we have to do this because MSIE sometimes globs '*/*', pretending to
3568 # support xhtml+xml but choking when it gets what it asked for.
3569 # Disable content-type negotiation when caching (use mimetype good for all).
3570 if (!$caching_enabled &&
3571 defined $cgi->http('HTTP_ACCEPT') &&
3572 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3573 $cgi->Accept('application/xhtml+xml') != 0) {
3574 $content_type = 'application/xhtml+xml';
3575 } else {
3576 $content_type = 'text/html';
3578 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3579 -status=> $status, -expires => $expires)
3580 unless ($opts{'-no_http_header'});
3581 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3582 print <<EOF;
3583 <?xml version="1.0" encoding="utf-8"?>
3584 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3585 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3586 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3587 <!-- git core binaries version $git_version -->
3588 <head>
3589 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3590 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3591 <meta name="robots" content="index, nofollow"/>
3592 <title>$title</title>
3594 # the stylesheet, favicon etc urls won't work correctly with path_info
3595 # unless we set the appropriate base URL
3596 # if caching is enabled we can get it from cache for path_info when it
3597 # is generated without path_info
3598 if ($ENV{'PATH_INFO'} || $caching_enabled) {
3599 print "<base href=\"".esc_url($base_url)."\" />\n";
3601 # print out each stylesheet that exist, providing backwards capability
3602 # for those people who defined $stylesheet in a config file
3603 if (defined $stylesheet) {
3604 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3605 } else {
3606 foreach my $stylesheet (@stylesheets) {
3607 next unless $stylesheet;
3608 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3611 if (defined $project) {
3612 my %href_params = get_feed_info();
3613 if (!exists $href_params{'-title'}) {
3614 $href_params{'-title'} = 'log';
3617 foreach my $format qw(RSS Atom) {
3618 my $type = lc($format);
3619 my %link_attr = (
3620 '-rel' => 'alternate',
3621 '-title' => "$project - $href_params{'-title'} - $format feed",
3622 '-type' => "application/$type+xml"
3625 $href_params{'action'} = $type;
3626 $link_attr{'-href'} = href(%href_params);
3627 print "<link ".
3628 "rel=\"$link_attr{'-rel'}\" ".
3629 "title=\"$link_attr{'-title'}\" ".
3630 "href=\"$link_attr{'-href'}\" ".
3631 "type=\"$link_attr{'-type'}\" ".
3632 "/>\n";
3634 $href_params{'extra_options'} = '--no-merges';
3635 $link_attr{'-href'} = href(%href_params);
3636 $link_attr{'-title'} .= ' (no merges)';
3637 print "<link ".
3638 "rel=\"$link_attr{'-rel'}\" ".
3639 "title=\"$link_attr{'-title'}\" ".
3640 "href=\"$link_attr{'-href'}\" ".
3641 "type=\"$link_attr{'-type'}\" ".
3642 "/>\n";
3645 } else {
3646 printf('<link rel="alternate" title="%s projects list" '.
3647 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3648 $site_name, href(project=>undef, action=>"project_index"));
3649 printf('<link rel="alternate" title="%s projects feeds" '.
3650 'href="%s" type="text/x-opml" />'."\n",
3651 $site_name, href(project=>undef, action=>"opml"));
3653 if (defined $favicon) {
3654 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3657 print "</head>\n" .
3658 "<body>\n";
3660 if (defined $site_header && -f $site_header) {
3661 insert_file($site_header);
3664 print "<div class=\"page_header\">\n" .
3665 $cgi->a({-href => esc_url($logo_url),
3666 -title => $logo_label},
3667 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3668 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3669 if (defined $project) {
3670 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3671 if (defined $action) {
3672 print " / $action";
3674 print "\n";
3676 print "</div>\n";
3678 my $have_search = gitweb_check_feature('search');
3679 if (defined $project && $have_search) {
3680 if (!defined $searchtext) {
3681 $searchtext = "";
3683 my $search_hash;
3684 if (defined $hash_base) {
3685 $search_hash = $hash_base;
3686 } elsif (defined $hash) {
3687 $search_hash = $hash;
3688 } else {
3689 $search_hash = "HEAD";
3691 my $action = $my_uri;
3692 my $use_pathinfo = gitweb_check_feature('pathinfo');
3693 if ($use_pathinfo) {
3694 $action .= "/".esc_url($project);
3696 print $cgi->startform(-method => "get", -action => $action) .
3697 "<div class=\"search\">\n" .
3698 (!$use_pathinfo &&
3699 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3700 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3701 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3702 $cgi->popup_menu(-name => 'st', -default => 'commit',
3703 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3704 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3705 " search:\n",
3706 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3707 "<span title=\"Extended regular expression\">" .
3708 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3709 -checked => $search_use_regexp) .
3710 "</span>" .
3711 "</div>" .
3712 $cgi->end_form() . "\n";
3716 sub git_footer_html {
3717 my $feed_class = 'rss_logo';
3719 print "<div class=\"page_footer\">\n";
3720 if (defined $project) {
3721 my $descr = git_get_project_description($project);
3722 if (defined $descr) {
3723 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3726 my %href_params = get_feed_info();
3727 if (!%href_params) {
3728 $feed_class .= ' generic';
3730 $href_params{'-title'} ||= 'log';
3732 foreach my $format qw(RSS Atom) {
3733 $href_params{'action'} = lc($format);
3734 print $cgi->a({-href => href(%href_params),
3735 -title => "$href_params{'-title'} $format feed",
3736 -class => $feed_class}, $format)."\n";
3739 } else {
3740 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3741 -class => $feed_class}, "OPML") . " ";
3742 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3743 -class => $feed_class}, "TXT") . "\n";
3745 print "</div>\n"; # class="page_footer"
3747 # timing info doesn't make much sense with output (response) caching,
3748 # so when caching is enabled gitweb prints the time of page generation
3749 if ((defined $t0 || $caching_enabled) &&
3750 gitweb_check_feature('timed')) {
3751 print "<div id=\"generating_info\">\n";
3752 if ($caching_enabled) {
3753 print 'This page was generated at '.
3754 gmtime( time() )." GMT\n";
3755 } else {
3756 print 'This page took '.
3757 '<span id="generating_time" class="time_span">'.
3758 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3759 ' seconds </span>'.
3760 ' and '.
3761 '<span id="generating_cmd">'.
3762 $number_of_git_cmds.
3763 '</span> git commands '.
3764 " to generate.\n";
3766 print "</div>\n"; # class="page_footer"
3769 if (defined $site_footer && -f $site_footer) {
3770 insert_file($site_footer);
3773 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3774 if (!$caching_enabled &&
3775 defined $action && $action eq 'blame_incremental') {
3776 print qq!<script type="text/javascript">\n!.
3777 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3778 qq! "!. href() .qq!");\n!.
3779 qq!</script>\n!;
3780 } elsif (gitweb_check_feature('javascript-actions')) {
3781 print qq!<script type="text/javascript">\n!.
3782 qq!window.onload = fixLinks;\n!.
3783 qq!</script>\n!;
3786 print "</body>\n" .
3787 "</html>";
3790 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3791 # Example: die_error(404, 'Hash not found')
3792 # By convention, use the following status codes (as defined in RFC 2616):
3793 # 400: Invalid or missing CGI parameters, or
3794 # requested object exists but has wrong type.
3795 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3796 # this server or project.
3797 # 404: Requested object/revision/project doesn't exist.
3798 # 500: The server isn't configured properly, or
3799 # an internal error occurred (e.g. failed assertions caused by bugs), or
3800 # an unknown error occurred (e.g. the git binary died unexpectedly).
3801 # 503: The server is currently unavailable (because it is overloaded,
3802 # or down for maintenance). Generally, this is a temporary state.
3803 sub die_error {
3804 my $status = shift || 500;
3805 my $error = esc_html(shift) || "Internal Server Error";
3806 my $extra = shift;
3807 my %opts = @_;
3809 my %http_responses = (
3810 400 => '400 Bad Request',
3811 403 => '403 Forbidden',
3812 404 => '404 Not Found',
3813 500 => '500 Internal Server Error',
3814 503 => '503 Service Unavailable',
3817 # Do not cache error pages
3818 capture_stop($cache, $capture) if ($capture && $caching_enabled);
3820 git_header_html($http_responses{$status}, undef, %opts);
3821 print <<EOF;
3822 <div class="page_body">
3823 <br /><br />
3824 $status - $error
3825 <br />
3827 if (defined $extra) {
3828 print "<hr />\n" .
3829 "$extra\n";
3831 print "</div>\n";
3833 git_footer_html();
3834 goto DONE_GITWEB
3835 unless ($opts{'-error_handler'});
3838 ## ----------------------------------------------------------------------
3839 ## functions printing or outputting HTML: navigation
3841 sub git_print_page_nav {
3842 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3843 $extra = '' if !defined $extra; # pager or formats
3845 my @navs = qw(summary shortlog log commit commitdiff tree);
3846 if ($suppress) {
3847 @navs = grep { $_ ne $suppress } @navs;
3850 my %arg = map { $_ => {action=>$_} } @navs;
3851 if (defined $head) {
3852 for (qw(commit commitdiff)) {
3853 $arg{$_}{'hash'} = $head;
3855 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3856 for (qw(shortlog log)) {
3857 $arg{$_}{'hash'} = $head;
3862 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3863 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3865 my @actions = gitweb_get_feature('actions');
3866 my %repl = (
3867 '%' => '%',
3868 'n' => $project, # project name
3869 'f' => $git_dir, # project path within filesystem
3870 'h' => $treehead || '', # current hash ('h' parameter)
3871 'b' => $treebase || '', # hash base ('hb' parameter)
3873 while (@actions) {
3874 my ($label, $link, $pos) = splice(@actions,0,3);
3875 # insert
3876 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3877 # munch munch
3878 $link =~ s/%([%nfhb])/$repl{$1}/g;
3879 $arg{$label}{'_href'} = $link;
3882 print "<div class=\"page_nav\">\n" .
3883 (join " | ",
3884 map { $_ eq $current ?
3885 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3886 } @navs);
3887 print "<br/>\n$extra<br/>\n" .
3888 "</div>\n";
3891 sub format_paging_nav {
3892 my ($action, $page, $has_next_link) = @_;
3893 my $paging_nav;
3896 if ($page > 0) {
3897 $paging_nav .=
3898 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3899 " &sdot; " .
3900 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3901 -accesskey => "p", -title => "Alt-p"}, "prev");
3902 } else {
3903 $paging_nav .= "first &sdot; prev";
3906 if ($has_next_link) {
3907 $paging_nav .= " &sdot; " .
3908 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3909 -accesskey => "n", -title => "Alt-n"}, "next");
3910 } else {
3911 $paging_nav .= " &sdot; next";
3914 return $paging_nav;
3917 ## ......................................................................
3918 ## functions printing or outputting HTML: div
3920 sub git_print_header_div {
3921 my ($action, $title, $hash, $hash_base) = @_;
3922 my %args = ();
3924 $args{'action'} = $action;
3925 $args{'hash'} = $hash if $hash;
3926 $args{'hash_base'} = $hash_base if $hash_base;
3928 print "<div class=\"header\">\n" .
3929 $cgi->a({-href => href(%args), -class => "title"},
3930 $title ? $title : $action) .
3931 "\n</div>\n";
3934 sub print_local_time {
3935 print format_local_time(@_);
3938 sub format_local_time {
3939 my $localtime = '';
3940 my %date = @_;
3941 if ($date{'hour_local'} < 6) {
3942 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3943 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3944 } else {
3945 $localtime .= sprintf(" (%02d:%02d %s)",
3946 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3949 return $localtime;
3952 # Outputs the author name and date in long form
3953 sub git_print_authorship {
3954 my $co = shift;
3955 my %opts = @_;
3956 my $tag = $opts{-tag} || 'div';
3957 my $author = $co->{'author_name'};
3959 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3960 print "<$tag class=\"author_date\">" .
3961 format_search_author($author, "author", esc_html($author)) .
3962 " [$ad{'rfc2822'}";
3963 print_local_time(%ad) if ($opts{-localtime});
3964 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3965 . "</$tag>\n";
3968 # Outputs table rows containing the full author or committer information,
3969 # in the format expected for 'commit' view (& similar).
3970 # Parameters are a commit hash reference, followed by the list of people
3971 # to output information for. If the list is empty it defaults to both
3972 # author and committer.
3973 sub git_print_authorship_rows {
3974 my $co = shift;
3975 # too bad we can't use @people = @_ || ('author', 'committer')
3976 my @people = @_;
3977 @people = ('author', 'committer') unless @people;
3978 foreach my $who (@people) {
3979 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3980 print "<tr><td>$who</td><td>" .
3981 format_search_author($co->{"${who}_name"}, $who,
3982 esc_html($co->{"${who}_name"})) . " " .
3983 format_search_author($co->{"${who}_email"}, $who,
3984 esc_html("<" . $co->{"${who}_email"} . ">")) .
3985 "</td><td rowspan=\"2\">" .
3986 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3987 "</td></tr>\n" .
3988 "<tr>" .
3989 "<td></td><td> $wd{'rfc2822'}";
3990 print_local_time(%wd);
3991 print "</td>" .
3992 "</tr>\n";
3996 sub git_print_page_path {
3997 my $name = shift;
3998 my $type = shift;
3999 my $hb = shift;
4002 print "<div class=\"page_path\">";
4003 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4004 -title => 'tree root'}, to_utf8("[$project]"));
4005 print " / ";
4006 if (defined $name) {
4007 my @dirname = split '/', $name;
4008 my $basename = pop @dirname;
4009 my $fullname = '';
4011 foreach my $dir (@dirname) {
4012 $fullname .= ($fullname ? '/' : '') . $dir;
4013 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4014 hash_base=>$hb),
4015 -title => $fullname}, esc_path($dir));
4016 print " / ";
4018 if (defined $type && $type eq 'blob') {
4019 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4020 hash_base=>$hb),
4021 -title => $name}, esc_path($basename));
4022 } elsif (defined $type && $type eq 'tree') {
4023 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4024 hash_base=>$hb),
4025 -title => $name}, esc_path($basename));
4026 print " / ";
4027 } else {
4028 print esc_path($basename);
4031 print "<br/></div>\n";
4034 sub git_print_log {
4035 my $log = shift;
4036 my %opts = @_;
4038 if ($opts{'-remove_title'}) {
4039 # remove title, i.e. first line of log
4040 shift @$log;
4042 # remove leading empty lines
4043 while (defined $log->[0] && $log->[0] eq "") {
4044 shift @$log;
4047 # print log
4048 my $signoff = 0;
4049 my $empty = 0;
4050 foreach my $line (@$log) {
4051 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4052 $signoff = 1;
4053 $empty = 0;
4054 if (! $opts{'-remove_signoff'}) {
4055 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4056 next;
4057 } else {
4058 # remove signoff lines
4059 next;
4061 } else {
4062 $signoff = 0;
4065 # print only one empty line
4066 # do not print empty line after signoff
4067 if ($line eq "") {
4068 next if ($empty || $signoff);
4069 $empty = 1;
4070 } else {
4071 $empty = 0;
4074 print format_log_line_html($line) . "<br/>\n";
4077 if ($opts{'-final_empty_line'}) {
4078 # end with single empty line
4079 print "<br/>\n" unless $empty;
4083 # return link target (what link points to)
4084 sub git_get_link_target {
4085 my $hash = shift;
4086 my $link_target;
4088 # read link
4089 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4090 or return;
4092 local $/ = undef;
4093 $link_target = <$fd>;
4095 close $fd
4096 or return;
4098 return $link_target;
4101 # given link target, and the directory (basedir) the link is in,
4102 # return target of link relative to top directory (top tree);
4103 # return undef if it is not possible (including absolute links).
4104 sub normalize_link_target {
4105 my ($link_target, $basedir) = @_;
4107 # absolute symlinks (beginning with '/') cannot be normalized
4108 return if (substr($link_target, 0, 1) eq '/');
4110 # normalize link target to path from top (root) tree (dir)
4111 my $path;
4112 if ($basedir) {
4113 $path = $basedir . '/' . $link_target;
4114 } else {
4115 # we are in top (root) tree (dir)
4116 $path = $link_target;
4119 # remove //, /./, and /../
4120 my @path_parts;
4121 foreach my $part (split('/', $path)) {
4122 # discard '.' and ''
4123 next if (!$part || $part eq '.');
4124 # handle '..'
4125 if ($part eq '..') {
4126 if (@path_parts) {
4127 pop @path_parts;
4128 } else {
4129 # link leads outside repository (outside top dir)
4130 return;
4132 } else {
4133 push @path_parts, $part;
4136 $path = join('/', @path_parts);
4138 return $path;
4141 # print tree entry (row of git_tree), but without encompassing <tr> element
4142 sub git_print_tree_entry {
4143 my ($t, $basedir, $hash_base, $have_blame) = @_;
4145 my %base_key = ();
4146 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4148 # The format of a table row is: mode list link. Where mode is
4149 # the mode of the entry, list is the name of the entry, an href,
4150 # and link is the action links of the entry.
4152 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4153 if (exists $t->{'size'}) {
4154 print "<td class=\"size\">$t->{'size'}</td>\n";
4156 if ($t->{'type'} eq "blob") {
4157 print "<td class=\"list\">" .
4158 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4159 file_name=>"$basedir$t->{'name'}", %base_key),
4160 -class => "list"}, esc_path($t->{'name'}));
4161 if (S_ISLNK(oct $t->{'mode'})) {
4162 my $link_target = git_get_link_target($t->{'hash'});
4163 if ($link_target) {
4164 my $norm_target = normalize_link_target($link_target, $basedir);
4165 if (defined $norm_target) {
4166 print " -> " .
4167 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4168 file_name=>$norm_target),
4169 -title => $norm_target}, esc_path($link_target));
4170 } else {
4171 print " -> " . esc_path($link_target);
4175 print "</td>\n";
4176 print "<td class=\"link\">";
4177 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4178 file_name=>"$basedir$t->{'name'}", %base_key)},
4179 "blob");
4180 if ($have_blame) {
4181 print " | " .
4182 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4183 file_name=>"$basedir$t->{'name'}", %base_key)},
4184 "blame");
4186 if (defined $hash_base) {
4187 print " | " .
4188 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4189 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4190 "history");
4192 print " | " .
4193 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4194 file_name=>"$basedir$t->{'name'}")},
4195 "raw");
4196 print "</td>\n";
4198 } elsif ($t->{'type'} eq "tree") {
4199 print "<td class=\"list\">";
4200 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4201 file_name=>"$basedir$t->{'name'}",
4202 %base_key)},
4203 esc_path($t->{'name'}));
4204 print "</td>\n";
4205 print "<td class=\"link\">";
4206 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4207 file_name=>"$basedir$t->{'name'}",
4208 %base_key)},
4209 "tree");
4210 if (defined $hash_base) {
4211 print " | " .
4212 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4213 file_name=>"$basedir$t->{'name'}")},
4214 "history");
4216 print "</td>\n";
4217 } else {
4218 # unknown object: we can only present history for it
4219 # (this includes 'commit' object, i.e. submodule support)
4220 print "<td class=\"list\">" .
4221 esc_path($t->{'name'}) .
4222 "</td>\n";
4223 print "<td class=\"link\">";
4224 if (defined $hash_base) {
4225 print $cgi->a({-href => href(action=>"history",
4226 hash_base=>$hash_base,
4227 file_name=>"$basedir$t->{'name'}")},
4228 "history");
4230 print "</td>\n";
4234 ## ......................................................................
4235 ## functions printing large fragments of HTML
4237 # get pre-image filenames for merge (combined) diff
4238 sub fill_from_file_info {
4239 my ($diff, @parents) = @_;
4241 $diff->{'from_file'} = [ ];
4242 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4243 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4244 if ($diff->{'status'}[$i] eq 'R' ||
4245 $diff->{'status'}[$i] eq 'C') {
4246 $diff->{'from_file'}[$i] =
4247 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4251 return $diff;
4254 # is current raw difftree line of file deletion
4255 sub is_deleted {
4256 my $diffinfo = shift;
4258 return $diffinfo->{'to_id'} eq ('0' x 40);
4261 # does patch correspond to [previous] difftree raw line
4262 # $diffinfo - hashref of parsed raw diff format
4263 # $patchinfo - hashref of parsed patch diff format
4264 # (the same keys as in $diffinfo)
4265 sub is_patch_split {
4266 my ($diffinfo, $patchinfo) = @_;
4268 return defined $diffinfo && defined $patchinfo
4269 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4273 sub git_difftree_body {
4274 my ($difftree, $hash, @parents) = @_;
4275 my ($parent) = $parents[0];
4276 my $have_blame = gitweb_check_feature('blame');
4277 print "<div class=\"list_head\">\n";
4278 if ($#{$difftree} > 10) {
4279 print(($#{$difftree} + 1) . " files changed:\n");
4281 print "</div>\n";
4283 print "<table class=\"" .
4284 (@parents > 1 ? "combined " : "") .
4285 "diff_tree\">\n";
4287 # header only for combined diff in 'commitdiff' view
4288 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4289 if ($has_header) {
4290 # table header
4291 print "<thead><tr>\n" .
4292 "<th></th><th></th>\n"; # filename, patchN link
4293 for (my $i = 0; $i < @parents; $i++) {
4294 my $par = $parents[$i];
4295 print "<th>" .
4296 $cgi->a({-href => href(action=>"commitdiff",
4297 hash=>$hash, hash_parent=>$par),
4298 -title => 'commitdiff to parent number ' .
4299 ($i+1) . ': ' . substr($par,0,7)},
4300 $i+1) .
4301 "&nbsp;</th>\n";
4303 print "</tr></thead>\n<tbody>\n";
4306 my $alternate = 1;
4307 my $patchno = 0;
4308 foreach my $line (@{$difftree}) {
4309 my $diff = parsed_difftree_line($line);
4311 if ($alternate) {
4312 print "<tr class=\"dark\">\n";
4313 } else {
4314 print "<tr class=\"light\">\n";
4316 $alternate ^= 1;
4318 if (exists $diff->{'nparents'}) { # combined diff
4320 fill_from_file_info($diff, @parents)
4321 unless exists $diff->{'from_file'};
4323 if (!is_deleted($diff)) {
4324 # file exists in the result (child) commit
4325 print "<td>" .
4326 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4327 file_name=>$diff->{'to_file'},
4328 hash_base=>$hash),
4329 -class => "list"}, esc_path($diff->{'to_file'})) .
4330 "</td>\n";
4331 } else {
4332 print "<td>" .
4333 esc_path($diff->{'to_file'}) .
4334 "</td>\n";
4337 if ($action eq 'commitdiff') {
4338 # link to patch
4339 $patchno++;
4340 print "<td class=\"link\">" .
4341 $cgi->a({-href => "#patch$patchno"}, "patch") .
4342 " | " .
4343 "</td>\n";
4346 my $has_history = 0;
4347 my $not_deleted = 0;
4348 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4349 my $hash_parent = $parents[$i];
4350 my $from_hash = $diff->{'from_id'}[$i];
4351 my $from_path = $diff->{'from_file'}[$i];
4352 my $status = $diff->{'status'}[$i];
4354 $has_history ||= ($status ne 'A');
4355 $not_deleted ||= ($status ne 'D');
4357 if ($status eq 'A') {
4358 print "<td class=\"link\" align=\"right\"> | </td>\n";
4359 } elsif ($status eq 'D') {
4360 print "<td class=\"link\">" .
4361 $cgi->a({-href => href(action=>"blob",
4362 hash_base=>$hash,
4363 hash=>$from_hash,
4364 file_name=>$from_path)},
4365 "blob" . ($i+1)) .
4366 " | </td>\n";
4367 } else {
4368 if ($diff->{'to_id'} eq $from_hash) {
4369 print "<td class=\"link nochange\">";
4370 } else {
4371 print "<td class=\"link\">";
4373 print $cgi->a({-href => href(action=>"blobdiff",
4374 hash=>$diff->{'to_id'},
4375 hash_parent=>$from_hash,
4376 hash_base=>$hash,
4377 hash_parent_base=>$hash_parent,
4378 file_name=>$diff->{'to_file'},
4379 file_parent=>$from_path)},
4380 "diff" . ($i+1)) .
4381 " | </td>\n";
4385 print "<td class=\"link\">";
4386 if ($not_deleted) {
4387 print $cgi->a({-href => href(action=>"blob",
4388 hash=>$diff->{'to_id'},
4389 file_name=>$diff->{'to_file'},
4390 hash_base=>$hash)},
4391 "blob");
4392 print " | " if ($has_history);
4394 if ($has_history) {
4395 print $cgi->a({-href => href(action=>"history",
4396 file_name=>$diff->{'to_file'},
4397 hash_base=>$hash)},
4398 "history");
4400 print "</td>\n";
4402 print "</tr>\n";
4403 next; # instead of 'else' clause, to avoid extra indent
4405 # else ordinary diff
4407 my ($to_mode_oct, $to_mode_str, $to_file_type);
4408 my ($from_mode_oct, $from_mode_str, $from_file_type);
4409 if ($diff->{'to_mode'} ne ('0' x 6)) {
4410 $to_mode_oct = oct $diff->{'to_mode'};
4411 if (S_ISREG($to_mode_oct)) { # only for regular file
4412 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4414 $to_file_type = file_type($diff->{'to_mode'});
4416 if ($diff->{'from_mode'} ne ('0' x 6)) {
4417 $from_mode_oct = oct $diff->{'from_mode'};
4418 if (S_ISREG($to_mode_oct)) { # only for regular file
4419 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4421 $from_file_type = file_type($diff->{'from_mode'});
4424 if ($diff->{'status'} eq "A") { # created
4425 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4426 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4427 $mode_chng .= "]</span>";
4428 print "<td>";
4429 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4430 hash_base=>$hash, file_name=>$diff->{'file'}),
4431 -class => "list"}, esc_path($diff->{'file'}));
4432 print "</td>\n";
4433 print "<td>$mode_chng</td>\n";
4434 print "<td class=\"link\">";
4435 if ($action eq 'commitdiff') {
4436 # link to patch
4437 $patchno++;
4438 print $cgi->a({-href => "#patch$patchno"}, "patch");
4439 print " | ";
4441 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4442 hash_base=>$hash, file_name=>$diff->{'file'})},
4443 "blob");
4444 print "</td>\n";
4446 } elsif ($diff->{'status'} eq "D") { # deleted
4447 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4448 print "<td>";
4449 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4450 hash_base=>$parent, file_name=>$diff->{'file'}),
4451 -class => "list"}, esc_path($diff->{'file'}));
4452 print "</td>\n";
4453 print "<td>$mode_chng</td>\n";
4454 print "<td class=\"link\">";
4455 if ($action eq 'commitdiff') {
4456 # link to patch
4457 $patchno++;
4458 print $cgi->a({-href => "#patch$patchno"}, "patch");
4459 print " | ";
4461 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4462 hash_base=>$parent, file_name=>$diff->{'file'})},
4463 "blob") . " | ";
4464 if ($have_blame) {
4465 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4466 file_name=>$diff->{'file'})},
4467 "blame") . " | ";
4469 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4470 file_name=>$diff->{'file'})},
4471 "history");
4472 print "</td>\n";
4474 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4475 my $mode_chnge = "";
4476 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4477 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4478 if ($from_file_type ne $to_file_type) {
4479 $mode_chnge .= " from $from_file_type to $to_file_type";
4481 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4482 if ($from_mode_str && $to_mode_str) {
4483 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4484 } elsif ($to_mode_str) {
4485 $mode_chnge .= " mode: $to_mode_str";
4488 $mode_chnge .= "]</span>\n";
4490 print "<td>";
4491 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4492 hash_base=>$hash, file_name=>$diff->{'file'}),
4493 -class => "list"}, esc_path($diff->{'file'}));
4494 print "</td>\n";
4495 print "<td>$mode_chnge</td>\n";
4496 print "<td class=\"link\">";
4497 if ($action eq 'commitdiff') {
4498 # link to patch
4499 $patchno++;
4500 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4501 " | ";
4502 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4503 # "commit" view and modified file (not onlu mode changed)
4504 print $cgi->a({-href => href(action=>"blobdiff",
4505 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4506 hash_base=>$hash, hash_parent_base=>$parent,
4507 file_name=>$diff->{'file'})},
4508 "diff") .
4509 " | ";
4511 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4512 hash_base=>$hash, file_name=>$diff->{'file'})},
4513 "blob") . " | ";
4514 if ($have_blame) {
4515 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4516 file_name=>$diff->{'file'})},
4517 "blame") . " | ";
4519 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4520 file_name=>$diff->{'file'})},
4521 "history");
4522 print "</td>\n";
4524 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4525 my %status_name = ('R' => 'moved', 'C' => 'copied');
4526 my $nstatus = $status_name{$diff->{'status'}};
4527 my $mode_chng = "";
4528 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4529 # mode also for directories, so we cannot use $to_mode_str
4530 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4532 print "<td>" .
4533 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4534 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4535 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4536 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4537 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4538 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4539 -class => "list"}, esc_path($diff->{'from_file'})) .
4540 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4541 "<td class=\"link\">";
4542 if ($action eq 'commitdiff') {
4543 # link to patch
4544 $patchno++;
4545 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4546 " | ";
4547 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4548 # "commit" view and modified file (not only pure rename or copy)
4549 print $cgi->a({-href => href(action=>"blobdiff",
4550 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4551 hash_base=>$hash, hash_parent_base=>$parent,
4552 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4553 "diff") .
4554 " | ";
4556 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4557 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4558 "blob") . " | ";
4559 if ($have_blame) {
4560 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4561 file_name=>$diff->{'to_file'})},
4562 "blame") . " | ";
4564 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4565 file_name=>$diff->{'to_file'})},
4566 "history");
4567 print "</td>\n";
4569 } # we should not encounter Unmerged (U) or Unknown (X) status
4570 print "</tr>\n";
4572 print "</tbody>" if $has_header;
4573 print "</table>\n";
4576 sub git_patchset_body {
4577 my ($fd, $difftree, $hash, @hash_parents) = @_;
4578 my ($hash_parent) = $hash_parents[0];
4580 my $is_combined = (@hash_parents > 1);
4581 my $patch_idx = 0;
4582 my $patch_number = 0;
4583 my $patch_line;
4584 my $diffinfo;
4585 my $to_name;
4586 my (%from, %to);
4588 print "<div class=\"patchset\">\n";
4590 # skip to first patch
4591 while ($patch_line = <$fd>) {
4592 chomp $patch_line;
4594 last if ($patch_line =~ m/^diff /);
4597 PATCH:
4598 while ($patch_line) {
4600 # parse "git diff" header line
4601 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4602 # $1 is from_name, which we do not use
4603 $to_name = unquote($2);
4604 $to_name =~ s!^b/!!;
4605 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4606 # $1 is 'cc' or 'combined', which we do not use
4607 $to_name = unquote($2);
4608 } else {
4609 $to_name = undef;
4612 # check if current patch belong to current raw line
4613 # and parse raw git-diff line if needed
4614 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4615 # this is continuation of a split patch
4616 print "<div class=\"patch cont\">\n";
4617 } else {
4618 # advance raw git-diff output if needed
4619 $patch_idx++ if defined $diffinfo;
4621 # read and prepare patch information
4622 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4624 # compact combined diff output can have some patches skipped
4625 # find which patch (using pathname of result) we are at now;
4626 if ($is_combined) {
4627 while ($to_name ne $diffinfo->{'to_file'}) {
4628 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4629 format_diff_cc_simplified($diffinfo, @hash_parents) .
4630 "</div>\n"; # class="patch"
4632 $patch_idx++;
4633 $patch_number++;
4635 last if $patch_idx > $#$difftree;
4636 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4640 # modifies %from, %to hashes
4641 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4643 # this is first patch for raw difftree line with $patch_idx index
4644 # we index @$difftree array from 0, but number patches from 1
4645 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4648 # git diff header
4649 #assert($patch_line =~ m/^diff /) if DEBUG;
4650 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4651 $patch_number++;
4652 # print "git diff" header
4653 print format_git_diff_header_line($patch_line, $diffinfo,
4654 \%from, \%to);
4656 # print extended diff header
4657 print "<div class=\"diff extended_header\">\n";
4658 EXTENDED_HEADER:
4659 while ($patch_line = <$fd>) {
4660 chomp $patch_line;
4662 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4664 print format_extended_diff_header_line($patch_line, $diffinfo,
4665 \%from, \%to);
4667 print "</div>\n"; # class="diff extended_header"
4669 # from-file/to-file diff header
4670 if (! $patch_line) {
4671 print "</div>\n"; # class="patch"
4672 last PATCH;
4674 next PATCH if ($patch_line =~ m/^diff /);
4675 #assert($patch_line =~ m/^---/) if DEBUG;
4677 my $last_patch_line = $patch_line;
4678 $patch_line = <$fd>;
4679 chomp $patch_line;
4680 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4682 print format_diff_from_to_header($last_patch_line, $patch_line,
4683 $diffinfo, \%from, \%to,
4684 @hash_parents);
4686 # the patch itself
4687 LINE:
4688 while ($patch_line = <$fd>) {
4689 chomp $patch_line;
4691 next PATCH if ($patch_line =~ m/^diff /);
4693 print format_diff_line($patch_line, \%from, \%to);
4696 } continue {
4697 print "</div>\n"; # class="patch"
4700 # for compact combined (--cc) format, with chunk and patch simplification
4701 # the patchset might be empty, but there might be unprocessed raw lines
4702 for (++$patch_idx if $patch_number > 0;
4703 $patch_idx < @$difftree;
4704 ++$patch_idx) {
4705 # read and prepare patch information
4706 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4708 # generate anchor for "patch" links in difftree / whatchanged part
4709 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4710 format_diff_cc_simplified($diffinfo, @hash_parents) .
4711 "</div>\n"; # class="patch"
4713 $patch_number++;
4716 if ($patch_number == 0) {
4717 if (@hash_parents > 1) {
4718 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4719 } else {
4720 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4724 print "</div>\n"; # class="patchset"
4727 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4729 # fills project list info (age, description, owner, forks) for each
4730 # project in the list, removing invalid projects from returned list
4731 # NOTE: modifies $projlist, but does not remove entries from it
4732 sub fill_project_list_info {
4733 my ($projlist, $check_forks) = @_;
4734 my @projects;
4736 my $show_ctags = gitweb_check_feature('ctags');
4737 PROJECT:
4738 foreach my $pr (@$projlist) {
4739 my (@activity) = git_get_last_activity($pr->{'path'});
4740 unless (@activity) {
4741 next PROJECT;
4743 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4744 if (!defined $pr->{'descr'}) {
4745 my $descr = git_get_project_description($pr->{'path'}) || "";
4746 $descr = to_utf8($descr);
4747 $pr->{'descr_long'} = $descr;
4748 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4750 if (!defined $pr->{'owner'}) {
4751 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4753 if ($check_forks) {
4754 my $pname = $pr->{'path'};
4755 if (($pname =~ s/\.git$//) &&
4756 ($pname !~ /\/$/) &&
4757 (-d "$projectroot/$pname")) {
4758 $pr->{'forks'} = "-d $projectroot/$pname";
4759 } else {
4760 $pr->{'forks'} = 0;
4763 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4764 push @projects, $pr;
4767 return @projects;
4770 # print 'sort by' <th> element, generating 'sort by $name' replay link
4771 # if that order is not selected
4772 sub print_sort_th {
4773 print format_sort_th(@_);
4776 sub format_sort_th {
4777 my ($name, $order, $header) = @_;
4778 my $sort_th = "";
4779 $header ||= ucfirst($name);
4781 if ($order eq $name) {
4782 $sort_th .= "<th>$header</th>\n";
4783 } else {
4784 $sort_th .= "<th>" .
4785 $cgi->a({-href => href(-replay=>1, order=>$name),
4786 -class => "header"}, $header) .
4787 "</th>\n";
4790 return $sort_th;
4793 sub git_project_list_body {
4794 # actually uses global variable $project
4795 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4797 my $check_forks = gitweb_check_feature('forks');
4798 my @projects = fill_project_list_info($projlist, $check_forks);
4800 $order ||= $default_projects_order;
4801 $from = 0 unless defined $from;
4802 $to = $#projects if (!defined $to || $#projects < $to);
4804 my %order_info = (
4805 project => { key => 'path', type => 'str' },
4806 descr => { key => 'descr_long', type => 'str' },
4807 owner => { key => 'owner', type => 'str' },
4808 age => { key => 'age', type => 'num' }
4810 my $oi = $order_info{$order};
4811 if ($oi->{'type'} eq 'str') {
4812 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4813 } else {
4814 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4817 my $show_ctags = gitweb_check_feature('ctags');
4818 if ($show_ctags) {
4819 my %ctags;
4820 foreach my $p (@projects) {
4821 foreach my $ct (keys %{$p->{'ctags'}}) {
4822 $ctags{$ct} += $p->{'ctags'}->{$ct};
4825 my $cloud = git_populate_project_tagcloud(\%ctags);
4826 print git_show_project_tagcloud($cloud, 64);
4829 print "<table class=\"project_list\">\n";
4830 unless ($no_header) {
4831 print "<tr>\n";
4832 if ($check_forks) {
4833 print "<th></th>\n";
4835 print_sort_th('project', $order, 'Project');
4836 print_sort_th('descr', $order, 'Description');
4837 print_sort_th('owner', $order, 'Owner');
4838 print_sort_th('age', $order, 'Last Change');
4839 print "<th></th>\n" . # for links
4840 "</tr>\n";
4842 my $alternate = 1;
4843 my $tagfilter = $cgi->param('by_tag');
4844 for (my $i = $from; $i <= $to; $i++) {
4845 my $pr = $projects[$i];
4847 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4848 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4849 and not $pr->{'descr_long'} =~ /$searchtext/;
4850 # Weed out forks or non-matching entries of search
4851 if ($check_forks) {
4852 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4853 $forkbase="^$forkbase" if $forkbase;
4854 next if not $searchtext and not $tagfilter and $show_ctags
4855 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4858 if ($alternate) {
4859 print "<tr class=\"dark\">\n";
4860 } else {
4861 print "<tr class=\"light\">\n";
4863 $alternate ^= 1;
4864 if ($check_forks) {
4865 print "<td>";
4866 if ($pr->{'forks'}) {
4867 print "<!-- $pr->{'forks'} -->\n";
4868 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4870 print "</td>\n";
4872 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4873 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4874 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4875 -class => "list", -title => $pr->{'descr_long'}},
4876 esc_html($pr->{'descr'})) . "</td>\n" .
4877 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4878 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4879 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4880 "<td class=\"link\">" .
4881 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4882 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4883 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4884 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4885 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4886 "</td>\n" .
4887 "</tr>\n";
4889 if (defined $extra) {
4890 print "<tr>\n";
4891 if ($check_forks) {
4892 print "<td></td>\n";
4894 print "<td colspan=\"5\">$extra</td>\n" .
4895 "</tr>\n";
4897 print "</table>\n";
4900 sub git_log_body {
4901 # uses global variable $project
4902 my ($commitlist, $from, $to, $refs, $extra) = @_;
4904 $from = 0 unless defined $from;
4905 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4907 for (my $i = 0; $i <= $to; $i++) {
4908 my %co = %{$commitlist->[$i]};
4909 next if !%co;
4910 my $commit = $co{'id'};
4911 my $ref = format_ref_marker($refs, $commit);
4912 my %ad = parse_date($co{'author_epoch'});
4913 git_print_header_div('commit',
4914 "<span class=\"age\">$co{'age_string'}</span>" .
4915 esc_html($co{'title'}) . $ref,
4916 $commit);
4917 print "<div class=\"title_text\">\n" .
4918 "<div class=\"log_link\">\n" .
4919 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4920 " | " .
4921 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4922 " | " .
4923 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4924 "<br/>\n" .
4925 "</div>\n";
4926 git_print_authorship(\%co, -tag => 'span');
4927 print "<br/>\n</div>\n";
4929 print "<div class=\"log_body\">\n";
4930 git_print_log($co{'comment'}, -final_empty_line=> 1);
4931 print "</div>\n";
4933 if ($extra) {
4934 print "<div class=\"page_nav\">\n";
4935 print "$extra\n";
4936 print "</div>\n";
4940 sub git_shortlog_body {
4941 # uses global variable $project
4942 my ($commitlist, $from, $to, $refs, $extra) = @_;
4944 $from = 0 unless defined $from;
4945 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4947 print "<table class=\"shortlog\">\n";
4948 my $alternate = 1;
4949 for (my $i = $from; $i <= $to; $i++) {
4950 my %co = %{$commitlist->[$i]};
4951 my $commit = $co{'id'};
4952 my $ref = format_ref_marker($refs, $commit);
4953 if ($alternate) {
4954 print "<tr class=\"dark\">\n";
4955 } else {
4956 print "<tr class=\"light\">\n";
4958 $alternate ^= 1;
4959 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4960 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4961 format_author_html('td', \%co, 10) . "<td>";
4962 print format_subject_html($co{'title'}, $co{'title_short'},
4963 href(action=>"commit", hash=>$commit), $ref);
4964 print "</td>\n" .
4965 "<td class=\"link\">" .
4966 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4967 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4968 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4969 my $snapshot_links = format_snapshot_links($commit);
4970 if (defined $snapshot_links) {
4971 print " | " . $snapshot_links;
4973 print "</td>\n" .
4974 "</tr>\n";
4976 if (defined $extra) {
4977 print "<tr>\n" .
4978 "<td colspan=\"4\">$extra</td>\n" .
4979 "</tr>\n";
4981 print "</table>\n";
4984 sub git_history_body {
4985 # Warning: assumes constant type (blob or tree) during history
4986 my ($commitlist, $from, $to, $refs, $extra,
4987 $file_name, $file_hash, $ftype) = @_;
4989 $from = 0 unless defined $from;
4990 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4992 print "<table class=\"history\">\n";
4993 my $alternate = 1;
4994 for (my $i = $from; $i <= $to; $i++) {
4995 my %co = %{$commitlist->[$i]};
4996 if (!%co) {
4997 next;
4999 my $commit = $co{'id'};
5001 my $ref = format_ref_marker($refs, $commit);
5003 if ($alternate) {
5004 print "<tr class=\"dark\">\n";
5005 } else {
5006 print "<tr class=\"light\">\n";
5008 $alternate ^= 1;
5009 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5010 # shortlog: format_author_html('td', \%co, 10)
5011 format_author_html('td', \%co, 15, 3) . "<td>";
5012 # originally git_history used chop_str($co{'title'}, 50)
5013 print format_subject_html($co{'title'}, $co{'title_short'},
5014 href(action=>"commit", hash=>$commit), $ref);
5015 print "</td>\n" .
5016 "<td class=\"link\">" .
5017 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5018 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5020 if ($ftype eq 'blob') {
5021 my $blob_current = $file_hash;
5022 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5023 if (defined $blob_current && defined $blob_parent &&
5024 $blob_current ne $blob_parent) {
5025 print " | " .
5026 $cgi->a({-href => href(action=>"blobdiff",
5027 hash=>$blob_current, hash_parent=>$blob_parent,
5028 hash_base=>$hash_base, hash_parent_base=>$commit,
5029 file_name=>$file_name)},
5030 "diff to current");
5033 print "</td>\n" .
5034 "</tr>\n";
5036 if (defined $extra) {
5037 print "<tr>\n" .
5038 "<td colspan=\"4\">$extra</td>\n" .
5039 "</tr>\n";
5041 print "</table>\n";
5044 sub git_tags_body {
5045 # uses global variable $project
5046 my ($taglist, $from, $to, $extra) = @_;
5047 $from = 0 unless defined $from;
5048 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5050 print "<table class=\"tags\">\n";
5051 my $alternate = 1;
5052 for (my $i = $from; $i <= $to; $i++) {
5053 my $entry = $taglist->[$i];
5054 my %tag = %$entry;
5055 my $comment = $tag{'subject'};
5056 my $comment_short;
5057 if (defined $comment) {
5058 $comment_short = chop_str($comment, 30, 5);
5060 if ($alternate) {
5061 print "<tr class=\"dark\">\n";
5062 } else {
5063 print "<tr class=\"light\">\n";
5065 $alternate ^= 1;
5066 if (defined $tag{'age'}) {
5067 print "<td><i>$tag{'age'}</i></td>\n";
5068 } else {
5069 print "<td></td>\n";
5071 print "<td>" .
5072 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5073 -class => "list name"}, esc_html($tag{'name'})) .
5074 "</td>\n" .
5075 "<td>";
5076 if (defined $comment) {
5077 print format_subject_html($comment, $comment_short,
5078 href(action=>"tag", hash=>$tag{'id'}));
5080 print "</td>\n" .
5081 "<td class=\"selflink\">";
5082 if ($tag{'type'} eq "tag") {
5083 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5084 } else {
5085 print "&nbsp;";
5087 print "</td>\n" .
5088 "<td class=\"link\">" . " | " .
5089 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5090 if ($tag{'reftype'} eq "commit") {
5091 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5092 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5093 } elsif ($tag{'reftype'} eq "blob") {
5094 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5096 print "</td>\n" .
5097 "</tr>";
5099 if (defined $extra) {
5100 print "<tr>\n" .
5101 "<td colspan=\"5\">$extra</td>\n" .
5102 "</tr>\n";
5104 print "</table>\n";
5107 sub git_heads_body {
5108 # uses global variable $project
5109 my ($headlist, $head, $from, $to, $extra) = @_;
5110 $from = 0 unless defined $from;
5111 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5113 print "<table class=\"heads\">\n";
5114 my $alternate = 1;
5115 for (my $i = $from; $i <= $to; $i++) {
5116 my $entry = $headlist->[$i];
5117 my %ref = %$entry;
5118 my $curr = $ref{'id'} eq $head;
5119 if ($alternate) {
5120 print "<tr class=\"dark\">\n";
5121 } else {
5122 print "<tr class=\"light\">\n";
5124 $alternate ^= 1;
5125 print "<td><i>$ref{'age'}</i></td>\n" .
5126 ($curr ? "<td class=\"current_head\">" : "<td>") .
5127 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5128 -class => "list name"},esc_html($ref{'name'})) .
5129 "</td>\n" .
5130 "<td class=\"link\">" .
5131 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5132 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5133 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
5134 "</td>\n" .
5135 "</tr>";
5137 if (defined $extra) {
5138 print "<tr>\n" .
5139 "<td colspan=\"3\">$extra</td>\n" .
5140 "</tr>\n";
5142 print "</table>\n";
5145 sub git_search_grep_body {
5146 my ($commitlist, $from, $to, $extra) = @_;
5147 $from = 0 unless defined $from;
5148 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5150 print "<table class=\"commit_search\">\n";
5151 my $alternate = 1;
5152 for (my $i = $from; $i <= $to; $i++) {
5153 my %co = %{$commitlist->[$i]};
5154 if (!%co) {
5155 next;
5157 my $commit = $co{'id'};
5158 if ($alternate) {
5159 print "<tr class=\"dark\">\n";
5160 } else {
5161 print "<tr class=\"light\">\n";
5163 $alternate ^= 1;
5164 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5165 format_author_html('td', \%co, 15, 5) .
5166 "<td>" .
5167 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5168 -class => "list subject"},
5169 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5170 my $comment = $co{'comment'};
5171 foreach my $line (@$comment) {
5172 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5173 my ($lead, $match, $trail) = ($1, $2, $3);
5174 $match = chop_str($match, 70, 5, 'center');
5175 my $contextlen = int((80 - length($match))/2);
5176 $contextlen = 30 if ($contextlen > 30);
5177 $lead = chop_str($lead, $contextlen, 10, 'left');
5178 $trail = chop_str($trail, $contextlen, 10, 'right');
5180 $lead = esc_html($lead);
5181 $match = esc_html($match);
5182 $trail = esc_html($trail);
5184 print "$lead<span class=\"match\">$match</span>$trail<br />";
5187 print "</td>\n" .
5188 "<td class=\"link\">" .
5189 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5190 " | " .
5191 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5192 " | " .
5193 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5194 print "</td>\n" .
5195 "</tr>\n";
5197 if (defined $extra) {
5198 print "<tr>\n" .
5199 "<td colspan=\"3\">$extra</td>\n" .
5200 "</tr>\n";
5202 print "</table>\n";
5205 ## ======================================================================
5206 ## ======================================================================
5207 ## actions
5209 sub git_project_list {
5210 my $order = $input_params{'order'};
5211 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5212 die_error(400, "Unknown order parameter");
5215 my @list = git_get_projects_list();
5216 if (!@list) {
5217 die_error(404, "No projects found");
5220 git_header_html();
5221 if (defined $home_text && -f $home_text) {
5222 print "<div class=\"index_include\">\n";
5223 insert_file($home_text);
5224 print "</div>\n";
5226 print $cgi->startform(-method => "get") .
5227 "<p class=\"projsearch\">Search:\n" .
5228 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5229 "</p>" .
5230 $cgi->end_form() . "\n";
5231 git_project_list_body(\@list, $order);
5232 git_footer_html();
5235 sub git_forks {
5236 my $order = $input_params{'order'};
5237 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5238 die_error(400, "Unknown order parameter");
5241 my @list = git_get_projects_list($project);
5242 if (!@list) {
5243 die_error(404, "No forks found");
5246 git_header_html();
5247 git_print_page_nav('','');
5248 git_print_header_div('summary', "$project forks");
5249 git_project_list_body(\@list, $order);
5250 git_footer_html();
5253 sub git_project_index {
5254 my @projects = git_get_projects_list($project);
5256 print $cgi->header(
5257 -type => 'text/plain',
5258 -charset => 'utf-8',
5259 -content_disposition => 'inline; filename="index.aux"');
5261 foreach my $pr (@projects) {
5262 if (!exists $pr->{'owner'}) {
5263 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5266 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5267 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5268 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5269 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5270 $path =~ s/ /\+/g;
5271 $owner =~ s/ /\+/g;
5273 print "$path $owner\n";
5277 sub git_summary {
5278 my $descr = git_get_project_description($project) || "none";
5279 my %co = parse_commit("HEAD");
5280 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5281 my $head = $co{'id'};
5283 my $owner = git_get_project_owner($project);
5285 my $refs = git_get_references();
5286 # These get_*_list functions return one more to allow us to see if
5287 # there are more ...
5288 my @taglist = git_get_tags_list(16);
5289 my @headlist = git_get_heads_list(16);
5290 my @forklist;
5291 my $check_forks = gitweb_check_feature('forks');
5293 if ($check_forks) {
5294 @forklist = git_get_projects_list($project);
5297 git_header_html();
5298 git_print_page_nav('summary','', $head);
5300 print "<div class=\"title\">&nbsp;</div>\n";
5301 print "<table class=\"projects_list\">\n" .
5302 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5303 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5304 if (defined $cd{'rfc2822'}) {
5305 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5308 # use per project git URL list in $projectroot/$project/cloneurl
5309 # or make project git URL from git base URL and project name
5310 my $url_tag = "URL";
5311 my @url_list = git_get_project_url_list($project);
5312 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5313 foreach my $git_url (@url_list) {
5314 next unless $git_url;
5315 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5316 $url_tag = "";
5319 # Tag cloud
5320 my $show_ctags = gitweb_check_feature('ctags');
5321 if ($show_ctags) {
5322 my $ctags = git_get_project_ctags($project);
5323 my $cloud = git_populate_project_tagcloud($ctags);
5324 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5325 print "</td>\n<td>" unless %$ctags;
5326 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5327 print "</td>\n<td>" if %$ctags;
5328 print git_show_project_tagcloud($cloud, 48);
5329 print "</td></tr>";
5332 print "</table>\n";
5334 # If XSS prevention is on, we don't include README.html.
5335 # TODO: Allow a readme in some safe format.
5336 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5337 print "<div class=\"title\">readme</div>\n" .
5338 "<div class=\"readme\">\n";
5339 insert_file("$projectroot/$project/README.html");
5340 print "\n</div>\n"; # class="readme"
5343 # we need to request one more than 16 (0..15) to check if
5344 # those 16 are all
5345 my @commitlist = $head ? parse_commits($head, 17) : ();
5346 if (@commitlist) {
5347 git_print_header_div('shortlog');
5348 git_shortlog_body(\@commitlist, 0, 15, $refs,
5349 $#commitlist <= 15 ? undef :
5350 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5353 if (@taglist) {
5354 git_print_header_div('tags');
5355 git_tags_body(\@taglist, 0, 15,
5356 $#taglist <= 15 ? undef :
5357 $cgi->a({-href => href(action=>"tags")}, "..."));
5360 if (@headlist) {
5361 git_print_header_div('heads');
5362 git_heads_body(\@headlist, $head, 0, 15,
5363 $#headlist <= 15 ? undef :
5364 $cgi->a({-href => href(action=>"heads")}, "..."));
5367 if (@forklist) {
5368 git_print_header_div('forks');
5369 git_project_list_body(\@forklist, 'age', 0, 15,
5370 $#forklist <= 15 ? undef :
5371 $cgi->a({-href => href(action=>"forks")}, "..."),
5372 'no_header');
5375 git_footer_html();
5378 sub git_tag {
5379 my %tag = parse_tag($hash);
5381 if (! %tag) {
5382 die_error(404, "Unknown tag object");
5385 my $head = git_get_head_hash($project);
5386 git_header_html();
5387 git_print_page_nav('','', $head,undef,$head);
5388 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5389 print "<div class=\"title_text\">\n" .
5390 "<table class=\"object_header\">\n" .
5391 "<tr>\n" .
5392 "<td>object</td>\n" .
5393 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5394 $tag{'object'}) . "</td>\n" .
5395 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5396 $tag{'type'}) . "</td>\n" .
5397 "</tr>\n";
5398 if (defined($tag{'author'})) {
5399 git_print_authorship_rows(\%tag, 'author');
5401 print "</table>\n\n" .
5402 "</div>\n";
5403 print "<div class=\"page_body\">";
5404 my $comment = $tag{'comment'};
5405 foreach my $line (@$comment) {
5406 chomp $line;
5407 print esc_html($line, -nbsp=>1) . "<br/>\n";
5409 print "</div>\n";
5410 git_footer_html();
5413 sub git_blame_common {
5414 my $format = shift || 'porcelain';
5415 if ($format eq 'porcelain' && $cgi->param('js') &&
5416 !$caching_enabled) {
5417 $format = 'incremental';
5418 $action = 'blame_incremental'; # for page title etc
5421 # permissions
5422 gitweb_check_feature('blame')
5423 or die_error(403, "Blame view not allowed");
5425 # error checking
5426 die_error(400, "No file name given") unless $file_name;
5427 $hash_base ||= git_get_head_hash($project);
5428 die_error(404, "Couldn't find base commit") unless $hash_base;
5429 my %co = parse_commit($hash_base)
5430 or die_error(404, "Commit not found");
5431 my $ftype = "blob";
5432 if (!defined $hash) {
5433 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5434 or die_error(404, "Error looking up file");
5435 } else {
5436 $ftype = git_get_type($hash);
5437 if ($ftype !~ "blob") {
5438 die_error(400, "Object is not a blob");
5442 my $fd;
5443 if ($format eq 'incremental') {
5444 # get file contents (as base)
5445 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5446 or die_error(500, "Open git-cat-file failed");
5447 } elsif ($format eq 'data') {
5448 # run git-blame --incremental
5449 open $fd, "-|", git_cmd(), "blame", "--incremental",
5450 $hash_base, "--", $file_name
5451 or die_error(500, "Open git-blame --incremental failed");
5452 } else {
5453 # run git-blame --porcelain
5454 open $fd, "-|", git_cmd(), "blame", '-p',
5455 $hash_base, '--', $file_name
5456 or die_error(500, "Open git-blame --porcelain failed");
5459 # incremental blame data returns early
5460 if ($format eq 'data') {
5461 print $cgi->header(
5462 -type=>"text/plain", -charset => "utf-8",
5463 -status=> "200 OK");
5464 local $| = 1; # output autoflush
5465 print while <$fd>;
5466 close $fd
5467 or print "ERROR $!\n";
5469 print 'END';
5470 if (!$caching_enabled &&
5471 defined $t0 && gitweb_check_feature('timed')) {
5472 print ' '.
5473 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5474 ' '.$number_of_git_cmds;
5476 print "\n";
5478 return;
5481 # page header
5482 git_header_html();
5483 my $formats_nav =
5484 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5485 "blob") .
5486 " | ";
5487 if ($format eq 'incremental') {
5488 $formats_nav .=
5489 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5490 "blame") . " (non-incremental)";
5491 } elsif (!$caching_enabled) {
5492 $formats_nav .=
5493 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5494 "blame") . " (incremental)";
5496 $formats_nav .=
5497 " | " .
5498 $cgi->a({-href => href(action=>"history", -replay=>1)},
5499 "history") .
5500 " | " .
5501 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5502 "HEAD");
5503 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5504 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5505 git_print_page_path($file_name, $ftype, $hash_base);
5507 # page body
5508 if ($format eq 'incremental') {
5509 print "<noscript>\n<div class=\"error\"><center><b>\n".
5510 "This page requires JavaScript to run.\n Use ".
5511 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5512 'this page').
5513 " instead.\n".
5514 "</b></center></div>\n</noscript>\n";
5516 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5519 print qq!<div class="page_body">\n!;
5520 print qq!<div id="progress_info">... / ...</div>\n!
5521 if ($format eq 'incremental');
5522 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5523 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5524 qq!<thead>\n!.
5525 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5526 qq!</thead>\n!.
5527 qq!<tbody>\n!;
5529 my @rev_color = qw(light dark);
5530 my $num_colors = scalar(@rev_color);
5531 my $current_color = 0;
5533 if ($format eq 'incremental') {
5534 my $color_class = $rev_color[$current_color];
5536 #contents of a file
5537 my $linenr = 0;
5538 LINE:
5539 while (my $line = <$fd>) {
5540 chomp $line;
5541 $linenr++;
5543 print qq!<tr id="l$linenr" class="$color_class">!.
5544 qq!<td class="sha1"><a href=""> </a></td>!.
5545 qq!<td class="linenr">!.
5546 qq!<a class="linenr" href="">$linenr</a></td>!;
5547 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5548 print qq!</tr>\n!;
5551 } else { # porcelain, i.e. ordinary blame
5552 my %metainfo = (); # saves information about commits
5554 # blame data
5555 LINE:
5556 while (my $line = <$fd>) {
5557 chomp $line;
5558 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5559 # no <lines in group> for subsequent lines in group of lines
5560 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5561 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5562 if (!exists $metainfo{$full_rev}) {
5563 $metainfo{$full_rev} = { 'nprevious' => 0 };
5565 my $meta = $metainfo{$full_rev};
5566 my $data;
5567 while ($data = <$fd>) {
5568 chomp $data;
5569 last if ($data =~ s/^\t//); # contents of line
5570 if ($data =~ /^(\S+)(?: (.*))?$/) {
5571 $meta->{$1} = $2 unless exists $meta->{$1};
5573 if ($data =~ /^previous /) {
5574 $meta->{'nprevious'}++;
5577 my $short_rev = substr($full_rev, 0, 8);
5578 my $author = $meta->{'author'};
5579 my %date =
5580 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5581 my $date = $date{'iso-tz'};
5582 if ($group_size) {
5583 $current_color = ($current_color + 1) % $num_colors;
5585 my $tr_class = $rev_color[$current_color];
5586 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5587 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5588 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5589 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5590 if ($group_size) {
5591 print "<td class=\"sha1\"";
5592 print " title=\"". esc_html($author) . ", $date\"";
5593 print " rowspan=\"$group_size\"" if ($group_size > 1);
5594 print ">";
5595 print $cgi->a({-href => href(action=>"commit",
5596 hash=>$full_rev,
5597 file_name=>$file_name)},
5598 esc_html($short_rev));
5599 if ($group_size >= 2) {
5600 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5601 if (@author_initials) {
5602 print "<br />" .
5603 esc_html(join('', @author_initials));
5604 # or join('.', ...)
5607 print "</td>\n";
5609 # 'previous' <sha1 of parent commit> <filename at commit>
5610 if (exists $meta->{'previous'} &&
5611 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5612 $meta->{'parent'} = $1;
5613 $meta->{'file_parent'} = unquote($2);
5615 my $linenr_commit =
5616 exists($meta->{'parent'}) ?
5617 $meta->{'parent'} : $full_rev;
5618 my $linenr_filename =
5619 exists($meta->{'file_parent'}) ?
5620 $meta->{'file_parent'} : unquote($meta->{'filename'});
5621 my $blamed = href(action => 'blame',
5622 file_name => $linenr_filename,
5623 hash_base => $linenr_commit);
5624 print "<td class=\"linenr\">";
5625 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5626 -class => "linenr" },
5627 esc_html($lineno));
5628 print "</td>";
5629 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5630 print "</tr>\n";
5631 } # end while
5635 # footer
5636 print "</tbody>\n".
5637 "</table>\n"; # class="blame"
5638 print "</div>\n"; # class="blame_body"
5639 close $fd
5640 or print "Reading blob failed\n";
5642 git_footer_html();
5645 sub git_blame {
5646 git_blame_common();
5649 sub git_blame_incremental {
5650 git_blame_common(!$caching_enabled ? 'incremental' : undef);
5653 sub git_blame_data {
5654 git_blame_common('data');
5657 sub git_tags {
5658 my $head = git_get_head_hash($project);
5659 git_header_html();
5660 git_print_page_nav('','', $head,undef,$head);
5661 git_print_header_div('summary', $project);
5663 my @tagslist = git_get_tags_list();
5664 if (@tagslist) {
5665 git_tags_body(\@tagslist);
5667 git_footer_html();
5670 sub git_heads {
5671 my $head = git_get_head_hash($project);
5672 git_header_html();
5673 git_print_page_nav('','', $head,undef,$head);
5674 git_print_header_div('summary', $project);
5676 my @headslist = git_get_heads_list();
5677 if (@headslist) {
5678 git_heads_body(\@headslist, $head);
5680 git_footer_html();
5683 sub git_blob_plain {
5684 my $type = shift;
5685 my $expires;
5687 if (!defined $hash) {
5688 if (defined $file_name) {
5689 my $base = $hash_base || git_get_head_hash($project);
5690 $hash = git_get_hash_by_path($base, $file_name, "blob")
5691 or die_error(404, "Cannot find file");
5692 } else {
5693 die_error(400, "No file name defined");
5695 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5696 # blobs defined by non-textual hash id's can be cached
5697 $expires = "+1d";
5700 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5701 or die_error(500, "Open git-cat-file blob '$hash' failed");
5703 # content-type (can include charset)
5704 $type = blob_contenttype($fd, $file_name, $type);
5706 # "save as" filename, even when no $file_name is given
5707 my $save_as = "$hash";
5708 if (defined $file_name) {
5709 $save_as = $file_name;
5710 } elsif ($type =~ m/^text\//) {
5711 $save_as .= '.txt';
5714 # With XSS prevention on, blobs of all types except a few known safe
5715 # ones are served with "Content-Disposition: attachment" to make sure
5716 # they don't run in our security domain. For certain image types,
5717 # blob view writes an <img> tag referring to blob_plain view, and we
5718 # want to be sure not to break that by serving the image as an
5719 # attachment (though Firefox 3 doesn't seem to care).
5720 my $sandbox = $prevent_xss &&
5721 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5723 print $cgi->header(
5724 -type => $type,
5725 -expires => $expires,
5726 -content_disposition =>
5727 ($sandbox ? 'attachment' : 'inline')
5728 . '; filename="' . $save_as . '"');
5729 local $/ = undef;
5730 binmode STDOUT, ':raw';
5731 print <$fd>;
5732 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5733 close $fd;
5736 sub git_blob {
5737 my $expires;
5739 if (!defined $hash) {
5740 if (defined $file_name) {
5741 my $base = $hash_base || git_get_head_hash($project);
5742 $hash = git_get_hash_by_path($base, $file_name, "blob")
5743 or die_error(404, "Cannot find file");
5744 } else {
5745 die_error(400, "No file name defined");
5747 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5748 # blobs defined by non-textual hash id's can be cached
5749 $expires = "+1d";
5752 my $have_blame = gitweb_check_feature('blame');
5753 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5754 or die_error(500, "Couldn't cat $file_name, $hash");
5755 my $mimetype = blob_mimetype($fd, $file_name);
5756 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5757 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5758 close $fd;
5759 return git_blob_plain($mimetype);
5761 # we can have blame only for text/* mimetype
5762 $have_blame &&= ($mimetype =~ m!^text/!);
5764 my $highlight = gitweb_check_feature('highlight');
5765 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5766 $fd = run_highlighter($fd, $highlight, $syntax)
5767 if $syntax;
5769 git_header_html(undef, $expires);
5770 my $formats_nav = '';
5771 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5772 if (defined $file_name) {
5773 if ($have_blame) {
5774 $formats_nav .=
5775 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5776 "blame") .
5777 " | ";
5779 $formats_nav .=
5780 $cgi->a({-href => href(action=>"history", -replay=>1)},
5781 "history") .
5782 " | " .
5783 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5784 "raw") .
5785 " | " .
5786 $cgi->a({-href => href(action=>"blob",
5787 hash_base=>"HEAD", file_name=>$file_name)},
5788 "HEAD");
5789 } else {
5790 $formats_nav .=
5791 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5792 "raw");
5794 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5795 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5796 } else {
5797 print "<div class=\"page_nav\">\n" .
5798 "<br/><br/></div>\n" .
5799 "<div class=\"title\">$hash</div>\n";
5801 git_print_page_path($file_name, "blob", $hash_base);
5802 print "<div class=\"page_body\">\n";
5803 if ($mimetype =~ m!^image/!) {
5804 print qq!<img type="$mimetype"!;
5805 if ($file_name) {
5806 print qq! alt="$file_name" title="$file_name"!;
5808 print qq! src="! .
5809 href(action=>"blob_plain", hash=>$hash,
5810 hash_base=>$hash_base, file_name=>$file_name) .
5811 qq!" />\n!;
5812 } else {
5813 my $nr;
5814 while (my $line = <$fd>) {
5815 chomp $line;
5816 $nr++;
5817 $line = untabify($line);
5818 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5819 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5822 close $fd
5823 or print "Reading blob failed.\n";
5824 print "</div>";
5825 git_footer_html();
5828 sub git_tree {
5829 if (!defined $hash_base) {
5830 $hash_base = "HEAD";
5832 if (!defined $hash) {
5833 if (defined $file_name) {
5834 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5835 } else {
5836 $hash = $hash_base;
5839 die_error(404, "No such tree") unless defined($hash);
5841 my $show_sizes = gitweb_check_feature('show-sizes');
5842 my $have_blame = gitweb_check_feature('blame');
5844 my @entries = ();
5846 local $/ = "\0";
5847 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5848 ($show_sizes ? '-l' : ()), @extra_options, $hash
5849 or die_error(500, "Open git-ls-tree failed");
5850 @entries = map { chomp; $_ } <$fd>;
5851 close $fd
5852 or die_error(404, "Reading tree failed");
5855 my $refs = git_get_references();
5856 my $ref = format_ref_marker($refs, $hash_base);
5857 git_header_html();
5858 my $basedir = '';
5859 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5860 my @views_nav = ();
5861 if (defined $file_name) {
5862 push @views_nav,
5863 $cgi->a({-href => href(action=>"history", -replay=>1)},
5864 "history"),
5865 $cgi->a({-href => href(action=>"tree",
5866 hash_base=>"HEAD", file_name=>$file_name)},
5867 "HEAD"),
5869 my $snapshot_links = format_snapshot_links($hash);
5870 if (defined $snapshot_links) {
5871 # FIXME: Should be available when we have no hash base as well.
5872 push @views_nav, $snapshot_links;
5874 git_print_page_nav('tree','', $hash_base, undef, undef,
5875 join(' | ', @views_nav));
5876 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5877 } else {
5878 undef $hash_base;
5879 print "<div class=\"page_nav\">\n";
5880 print "<br/><br/></div>\n";
5881 print "<div class=\"title\">$hash</div>\n";
5883 if (defined $file_name) {
5884 $basedir = $file_name;
5885 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5886 $basedir .= '/';
5888 git_print_page_path($file_name, 'tree', $hash_base);
5890 print "<div class=\"page_body\">\n";
5891 print "<table class=\"tree\">\n";
5892 my $alternate = 1;
5893 # '..' (top directory) link if possible
5894 if (defined $hash_base &&
5895 defined $file_name && $file_name =~ m![^/]+$!) {
5896 if ($alternate) {
5897 print "<tr class=\"dark\">\n";
5898 } else {
5899 print "<tr class=\"light\">\n";
5901 $alternate ^= 1;
5903 my $up = $file_name;
5904 $up =~ s!/?[^/]+$!!;
5905 undef $up unless $up;
5906 # based on git_print_tree_entry
5907 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5908 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5909 print '<td class="list">';
5910 print $cgi->a({-href => href(action=>"tree",
5911 hash_base=>$hash_base,
5912 file_name=>$up)},
5913 "..");
5914 print "</td>\n";
5915 print "<td class=\"link\"></td>\n";
5917 print "</tr>\n";
5919 foreach my $line (@entries) {
5920 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5922 if ($alternate) {
5923 print "<tr class=\"dark\">\n";
5924 } else {
5925 print "<tr class=\"light\">\n";
5927 $alternate ^= 1;
5929 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5931 print "</tr>\n";
5933 print "</table>\n" .
5934 "</div>";
5935 git_footer_html();
5938 sub snapshot_name {
5939 my ($project, $hash) = @_;
5941 # path/to/project.git -> project
5942 # path/to/project/.git -> project
5943 my $name = to_utf8($project);
5944 $name =~ s,([^/])/*\.git$,$1,;
5945 $name = basename($name);
5946 # sanitize name
5947 $name =~ s/[[:cntrl:]]/?/g;
5949 my $ver = $hash;
5950 if ($hash =~ /^[0-9a-fA-F]+$/) {
5951 # shorten SHA-1 hash
5952 my $full_hash = git_get_full_hash($project, $hash);
5953 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5954 $ver = git_get_short_hash($project, $hash);
5956 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5957 # tags don't need shortened SHA-1 hash
5958 $ver = $1;
5959 } else {
5960 # branches and other need shortened SHA-1 hash
5961 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5962 $ver = $1;
5964 $ver .= '-' . git_get_short_hash($project, $hash);
5966 # in case of hierarchical branch names
5967 $ver =~ s!/!.!g;
5969 # name = project-version_string
5970 $name = "$name-$ver";
5972 return wantarray ? ($name, $name) : $name;
5975 sub git_snapshot {
5976 my $format = $input_params{'snapshot_format'};
5977 if (!@snapshot_fmts) {
5978 die_error(403, "Snapshots not allowed");
5980 # default to first supported snapshot format
5981 $format ||= $snapshot_fmts[0];
5982 if ($format !~ m/^[a-z0-9]+$/) {
5983 die_error(400, "Invalid snapshot format parameter");
5984 } elsif (!exists($known_snapshot_formats{$format})) {
5985 die_error(400, "Unknown snapshot format");
5986 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5987 die_error(403, "Snapshot format not allowed");
5988 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5989 die_error(403, "Unsupported snapshot format");
5992 my $type = git_get_type("$hash^{}");
5993 if (!$type) {
5994 die_error(404, 'Object does not exist');
5995 } elsif ($type eq 'blob') {
5996 die_error(400, 'Object is not a tree-ish');
5999 my ($name, $prefix) = snapshot_name($project, $hash);
6000 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6001 my $cmd = quote_command(
6002 git_cmd(), 'archive',
6003 "--format=$known_snapshot_formats{$format}{'format'}",
6004 "--prefix=$prefix/", $hash);
6005 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6006 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6009 $filename =~ s/(["\\])/\\$1/g;
6010 print $cgi->header(
6011 -type => $known_snapshot_formats{$format}{'type'},
6012 -content_disposition => 'inline; filename="' . $filename . '"',
6013 -status => '200 OK');
6015 open my $fd, "-|", $cmd
6016 or die_error(500, "Execute git-archive failed");
6017 binmode STDOUT, ':raw';
6018 print <$fd>;
6019 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6020 close $fd;
6023 sub git_log_generic {
6024 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6026 my $head = git_get_head_hash($project);
6027 if (!defined $base) {
6028 $base = $head;
6030 if (!defined $page) {
6031 $page = 0;
6033 my $refs = git_get_references();
6035 my $commit_hash = $base;
6036 if (defined $parent) {
6037 $commit_hash = "$parent..$base";
6039 my @commitlist =
6040 parse_commits($commit_hash, 101, (100 * $page),
6041 defined $file_name ? ($file_name, "--full-history") : ());
6043 my $ftype;
6044 if (!defined $file_hash && defined $file_name) {
6045 # some commits could have deleted file in question,
6046 # and not have it in tree, but one of them has to have it
6047 for (my $i = 0; $i < @commitlist; $i++) {
6048 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6049 last if defined $file_hash;
6052 if (defined $file_hash) {
6053 $ftype = git_get_type($file_hash);
6055 if (defined $file_name && !defined $ftype) {
6056 die_error(500, "Unknown type of object");
6058 my %co;
6059 if (defined $file_name) {
6060 %co = parse_commit($base)
6061 or die_error(404, "Unknown commit object");
6065 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6066 my $next_link = '';
6067 if ($#commitlist >= 100) {
6068 $next_link =
6069 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6070 -accesskey => "n", -title => "Alt-n"}, "next");
6072 my $patch_max = gitweb_get_feature('patches');
6073 if ($patch_max && !defined $file_name) {
6074 if ($patch_max < 0 || @commitlist <= $patch_max) {
6075 $paging_nav .= " &sdot; " .
6076 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6077 "patches");
6081 git_header_html();
6082 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6083 if (defined $file_name) {
6084 git_print_header_div('commit', esc_html($co{'title'}), $base);
6085 } else {
6086 git_print_header_div('summary', $project)
6088 git_print_page_path($file_name, $ftype, $hash_base)
6089 if (defined $file_name);
6091 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6092 $file_name, $file_hash, $ftype);
6094 git_footer_html();
6097 sub git_log {
6098 git_log_generic('log', \&git_log_body,
6099 $hash, $hash_parent);
6102 sub git_commit {
6103 $hash ||= $hash_base || "HEAD";
6104 my %co = parse_commit($hash)
6105 or die_error(404, "Unknown commit object");
6107 my $parent = $co{'parent'};
6108 my $parents = $co{'parents'}; # listref
6110 # we need to prepare $formats_nav before any parameter munging
6111 my $formats_nav;
6112 if (!defined $parent) {
6113 # --root commitdiff
6114 $formats_nav .= '(initial)';
6115 } elsif (@$parents == 1) {
6116 # single parent commit
6117 $formats_nav .=
6118 '(parent: ' .
6119 $cgi->a({-href => href(action=>"commit",
6120 hash=>$parent)},
6121 esc_html(substr($parent, 0, 7))) .
6122 ')';
6123 } else {
6124 # merge commit
6125 $formats_nav .=
6126 '(merge: ' .
6127 join(' ', map {
6128 $cgi->a({-href => href(action=>"commit",
6129 hash=>$_)},
6130 esc_html(substr($_, 0, 7)));
6131 } @$parents ) .
6132 ')';
6134 if (gitweb_check_feature('patches') && @$parents <= 1) {
6135 $formats_nav .= " | " .
6136 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6137 "patch");
6140 if (!defined $parent) {
6141 $parent = "--root";
6143 my @difftree;
6144 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6145 @diff_opts,
6146 (@$parents <= 1 ? $parent : '-c'),
6147 $hash, "--"
6148 or die_error(500, "Open git-diff-tree failed");
6149 @difftree = map { chomp; $_ } <$fd>;
6150 close $fd or die_error(404, "Reading git-diff-tree failed");
6152 # non-textual hash id's can be cached
6153 my $expires;
6154 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6155 $expires = "+1d";
6157 my $refs = git_get_references();
6158 my $ref = format_ref_marker($refs, $co{'id'});
6160 git_header_html(undef, $expires);
6161 git_print_page_nav('commit', '',
6162 $hash, $co{'tree'}, $hash,
6163 $formats_nav);
6165 if (defined $co{'parent'}) {
6166 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6167 } else {
6168 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6170 print "<div class=\"title_text\">\n" .
6171 "<table class=\"object_header\">\n";
6172 git_print_authorship_rows(\%co);
6173 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6174 print "<tr>" .
6175 "<td>tree</td>" .
6176 "<td class=\"sha1\">" .
6177 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6178 class => "list"}, $co{'tree'}) .
6179 "</td>" .
6180 "<td class=\"link\">" .
6181 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6182 "tree");
6183 my $snapshot_links = format_snapshot_links($hash);
6184 if (defined $snapshot_links) {
6185 print " | " . $snapshot_links;
6187 print "</td>" .
6188 "</tr>\n";
6190 foreach my $par (@$parents) {
6191 print "<tr>" .
6192 "<td>parent</td>" .
6193 "<td class=\"sha1\">" .
6194 $cgi->a({-href => href(action=>"commit", hash=>$par),
6195 class => "list"}, $par) .
6196 "</td>" .
6197 "<td class=\"link\">" .
6198 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6199 " | " .
6200 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6201 "</td>" .
6202 "</tr>\n";
6204 print "</table>".
6205 "</div>\n";
6207 print "<div class=\"page_body\">\n";
6208 git_print_log($co{'comment'});
6209 print "</div>\n";
6211 git_difftree_body(\@difftree, $hash, @$parents);
6213 git_footer_html();
6216 sub git_object {
6217 # object is defined by:
6218 # - hash or hash_base alone
6219 # - hash_base and file_name
6220 my $type;
6222 # - hash or hash_base alone
6223 if ($hash || ($hash_base && !defined $file_name)) {
6224 my $object_id = $hash || $hash_base;
6226 open my $fd, "-|", quote_command(
6227 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6228 or die_error(404, "Object does not exist");
6229 $type = <$fd>;
6230 chomp $type;
6231 close $fd
6232 or die_error(404, "Object does not exist");
6234 # - hash_base and file_name
6235 } elsif ($hash_base && defined $file_name) {
6236 $file_name =~ s,/+$,,;
6238 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6239 or die_error(404, "Base object does not exist");
6241 # here errors should not hapen
6242 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6243 or die_error(500, "Open git-ls-tree failed");
6244 my $line = <$fd>;
6245 close $fd;
6247 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6248 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6249 die_error(404, "File or directory for given base does not exist");
6251 $type = $2;
6252 $hash = $3;
6253 } else {
6254 die_error(400, "Not enough information to find object");
6257 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6258 hash=>$hash, hash_base=>$hash_base,
6259 file_name=>$file_name),
6260 -status => '302 Found');
6263 sub git_blobdiff {
6264 my $format = shift || 'html';
6266 my $fd;
6267 my @difftree;
6268 my %diffinfo;
6269 my $expires;
6271 # preparing $fd and %diffinfo for git_patchset_body
6272 # new style URI
6273 if (defined $hash_base && defined $hash_parent_base) {
6274 if (defined $file_name) {
6275 # read raw output
6276 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6277 $hash_parent_base, $hash_base,
6278 "--", (defined $file_parent ? $file_parent : ()), $file_name
6279 or die_error(500, "Open git-diff-tree failed");
6280 @difftree = map { chomp; $_ } <$fd>;
6281 close $fd
6282 or die_error(404, "Reading git-diff-tree failed");
6283 @difftree
6284 or die_error(404, "Blob diff not found");
6286 } elsif (defined $hash &&
6287 $hash =~ /[0-9a-fA-F]{40}/) {
6288 # try to find filename from $hash
6290 # read filtered raw output
6291 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6292 $hash_parent_base, $hash_base, "--"
6293 or die_error(500, "Open git-diff-tree failed");
6294 @difftree =
6295 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6296 # $hash == to_id
6297 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6298 map { chomp; $_ } <$fd>;
6299 close $fd
6300 or die_error(404, "Reading git-diff-tree failed");
6301 @difftree
6302 or die_error(404, "Blob diff not found");
6304 } else {
6305 die_error(400, "Missing one of the blob diff parameters");
6308 if (@difftree > 1) {
6309 die_error(400, "Ambiguous blob diff specification");
6312 %diffinfo = parse_difftree_raw_line($difftree[0]);
6313 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6314 $file_name ||= $diffinfo{'to_file'};
6316 $hash_parent ||= $diffinfo{'from_id'};
6317 $hash ||= $diffinfo{'to_id'};
6319 # non-textual hash id's can be cached
6320 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6321 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6322 $expires = '+1d';
6325 # open patch output
6326 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6327 '-p', ($format eq 'html' ? "--full-index" : ()),
6328 $hash_parent_base, $hash_base,
6329 "--", (defined $file_parent ? $file_parent : ()), $file_name
6330 or die_error(500, "Open git-diff-tree failed");
6333 # old/legacy style URI -- not generated anymore since 1.4.3.
6334 if (!%diffinfo) {
6335 die_error('404 Not Found', "Missing one of the blob diff parameters")
6338 # header
6339 if ($format eq 'html') {
6340 my $formats_nav =
6341 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6342 "raw");
6343 git_header_html(undef, $expires);
6344 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6345 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6346 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6347 } else {
6348 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6349 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6351 if (defined $file_name) {
6352 git_print_page_path($file_name, "blob", $hash_base);
6353 } else {
6354 print "<div class=\"page_path\"></div>\n";
6357 } elsif ($format eq 'plain') {
6358 print $cgi->header(
6359 -type => 'text/plain',
6360 -charset => 'utf-8',
6361 -expires => $expires,
6362 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6364 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6366 } else {
6367 die_error(400, "Unknown blobdiff format");
6370 # patch
6371 if ($format eq 'html') {
6372 print "<div class=\"page_body\">\n";
6374 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6375 close $fd;
6377 print "</div>\n"; # class="page_body"
6378 git_footer_html();
6380 } else {
6381 while (my $line = <$fd>) {
6382 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6383 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6385 print $line;
6387 last if $line =~ m!^\+\+\+!;
6389 local $/ = undef;
6390 print <$fd>;
6391 close $fd;
6395 sub git_blobdiff_plain {
6396 git_blobdiff('plain');
6399 sub git_commitdiff {
6400 my %params = @_;
6401 my $format = $params{-format} || 'html';
6403 my ($patch_max) = gitweb_get_feature('patches');
6404 if ($format eq 'patch') {
6405 die_error(403, "Patch view not allowed") unless $patch_max;
6408 $hash ||= $hash_base || "HEAD";
6409 my %co = parse_commit($hash)
6410 or die_error(404, "Unknown commit object");
6412 # choose format for commitdiff for merge
6413 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6414 $hash_parent = '--cc';
6416 # we need to prepare $formats_nav before almost any parameter munging
6417 my $formats_nav;
6418 if ($format eq 'html') {
6419 $formats_nav =
6420 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6421 "raw");
6422 if ($patch_max && @{$co{'parents'}} <= 1) {
6423 $formats_nav .= " | " .
6424 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6425 "patch");
6428 if (defined $hash_parent &&
6429 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6430 # commitdiff with two commits given
6431 my $hash_parent_short = $hash_parent;
6432 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6433 $hash_parent_short = substr($hash_parent, 0, 7);
6435 $formats_nav .=
6436 ' (from';
6437 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6438 if ($co{'parents'}[$i] eq $hash_parent) {
6439 $formats_nav .= ' parent ' . ($i+1);
6440 last;
6443 $formats_nav .= ': ' .
6444 $cgi->a({-href => href(action=>"commitdiff",
6445 hash=>$hash_parent)},
6446 esc_html($hash_parent_short)) .
6447 ')';
6448 } elsif (!$co{'parent'}) {
6449 # --root commitdiff
6450 $formats_nav .= ' (initial)';
6451 } elsif (scalar @{$co{'parents'}} == 1) {
6452 # single parent commit
6453 $formats_nav .=
6454 ' (parent: ' .
6455 $cgi->a({-href => href(action=>"commitdiff",
6456 hash=>$co{'parent'})},
6457 esc_html(substr($co{'parent'}, 0, 7))) .
6458 ')';
6459 } else {
6460 # merge commit
6461 if ($hash_parent eq '--cc') {
6462 $formats_nav .= ' | ' .
6463 $cgi->a({-href => href(action=>"commitdiff",
6464 hash=>$hash, hash_parent=>'-c')},
6465 'combined');
6466 } else { # $hash_parent eq '-c'
6467 $formats_nav .= ' | ' .
6468 $cgi->a({-href => href(action=>"commitdiff",
6469 hash=>$hash, hash_parent=>'--cc')},
6470 'compact');
6472 $formats_nav .=
6473 ' (merge: ' .
6474 join(' ', map {
6475 $cgi->a({-href => href(action=>"commitdiff",
6476 hash=>$_)},
6477 esc_html(substr($_, 0, 7)));
6478 } @{$co{'parents'}} ) .
6479 ')';
6483 my $hash_parent_param = $hash_parent;
6484 if (!defined $hash_parent_param) {
6485 # --cc for multiple parents, --root for parentless
6486 $hash_parent_param =
6487 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6490 # read commitdiff
6491 my $fd;
6492 my @difftree;
6493 if ($format eq 'html') {
6494 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6495 "--no-commit-id", "--patch-with-raw", "--full-index",
6496 $hash_parent_param, $hash, "--"
6497 or die_error(500, "Open git-diff-tree failed");
6499 while (my $line = <$fd>) {
6500 chomp $line;
6501 # empty line ends raw part of diff-tree output
6502 last unless $line;
6503 push @difftree, scalar parse_difftree_raw_line($line);
6506 } elsif ($format eq 'plain') {
6507 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6508 '-p', $hash_parent_param, $hash, "--"
6509 or die_error(500, "Open git-diff-tree failed");
6510 } elsif ($format eq 'patch') {
6511 # For commit ranges, we limit the output to the number of
6512 # patches specified in the 'patches' feature.
6513 # For single commits, we limit the output to a single patch,
6514 # diverging from the git-format-patch default.
6515 my @commit_spec = ();
6516 if ($hash_parent) {
6517 if ($patch_max > 0) {
6518 push @commit_spec, "-$patch_max";
6520 push @commit_spec, '-n', "$hash_parent..$hash";
6521 } else {
6522 if ($params{-single}) {
6523 push @commit_spec, '-1';
6524 } else {
6525 if ($patch_max > 0) {
6526 push @commit_spec, "-$patch_max";
6528 push @commit_spec, "-n";
6530 push @commit_spec, '--root', $hash;
6532 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6533 '--encoding=utf8', '--stdout', @commit_spec
6534 or die_error(500, "Open git-format-patch failed");
6535 } else {
6536 die_error(400, "Unknown commitdiff format");
6539 # non-textual hash id's can be cached
6540 my $expires;
6541 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6542 $expires = "+1d";
6545 # write commit message
6546 if ($format eq 'html') {
6547 my $refs = git_get_references();
6548 my $ref = format_ref_marker($refs, $co{'id'});
6550 git_header_html(undef, $expires);
6551 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6552 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6553 print "<div class=\"title_text\">\n" .
6554 "<table class=\"object_header\">\n";
6555 git_print_authorship_rows(\%co);
6556 print "</table>".
6557 "</div>\n";
6558 print "<div class=\"page_body\">\n";
6559 if (@{$co{'comment'}} > 1) {
6560 print "<div class=\"log\">\n";
6561 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6562 print "</div>\n"; # class="log"
6565 } elsif ($format eq 'plain') {
6566 my $refs = git_get_references("tags");
6567 my $tagname = git_get_rev_name_tags($hash);
6568 my $filename = basename($project) . "-$hash.patch";
6570 print $cgi->header(
6571 -type => 'text/plain',
6572 -charset => 'utf-8',
6573 -expires => $expires,
6574 -content_disposition => 'inline; filename="' . "$filename" . '"');
6575 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6576 print "From: " . to_utf8($co{'author'}) . "\n";
6577 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6578 print "Subject: " . to_utf8($co{'title'}) . "\n";
6580 print "X-Git-Tag: $tagname\n" if $tagname;
6581 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6583 foreach my $line (@{$co{'comment'}}) {
6584 print to_utf8($line) . "\n";
6586 print "---\n\n";
6587 } elsif ($format eq 'patch') {
6588 my $filename = basename($project) . "-$hash.patch";
6590 print $cgi->header(
6591 -type => 'text/plain',
6592 -charset => 'utf-8',
6593 -expires => $expires,
6594 -content_disposition => 'inline; filename="' . "$filename" . '"');
6597 # write patch
6598 if ($format eq 'html') {
6599 my $use_parents = !defined $hash_parent ||
6600 $hash_parent eq '-c' || $hash_parent eq '--cc';
6601 git_difftree_body(\@difftree, $hash,
6602 $use_parents ? @{$co{'parents'}} : $hash_parent);
6603 print "<br/>\n";
6605 git_patchset_body($fd, \@difftree, $hash,
6606 $use_parents ? @{$co{'parents'}} : $hash_parent);
6607 close $fd;
6608 print "</div>\n"; # class="page_body"
6609 git_footer_html();
6611 } elsif ($format eq 'plain') {
6612 local $/ = undef;
6613 print <$fd>;
6614 close $fd
6615 or print "Reading git-diff-tree failed\n";
6616 } elsif ($format eq 'patch') {
6617 local $/ = undef;
6618 print <$fd>;
6619 close $fd
6620 or print "Reading git-format-patch failed\n";
6624 sub git_commitdiff_plain {
6625 git_commitdiff(-format => 'plain');
6628 # format-patch-style patches
6629 sub git_patch {
6630 git_commitdiff(-format => 'patch', -single => 1);
6633 sub git_patches {
6634 git_commitdiff(-format => 'patch');
6637 sub git_history {
6638 git_log_generic('history', \&git_history_body,
6639 $hash_base, $hash_parent_base,
6640 $file_name, $hash);
6643 sub git_search {
6644 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6645 if (!defined $searchtext) {
6646 die_error(400, "Text field is empty");
6648 if (!defined $hash) {
6649 $hash = git_get_head_hash($project);
6651 my %co = parse_commit($hash);
6652 if (!%co) {
6653 die_error(404, "Unknown commit object");
6655 if (!defined $page) {
6656 $page = 0;
6659 $searchtype ||= 'commit';
6660 if ($searchtype eq 'pickaxe') {
6661 # pickaxe may take all resources of your box and run for several minutes
6662 # with every query - so decide by yourself how public you make this feature
6663 gitweb_check_feature('pickaxe')
6664 or die_error(403, "Pickaxe is disabled");
6666 if ($searchtype eq 'grep') {
6667 gitweb_check_feature('grep')
6668 or die_error(403, "Grep is disabled");
6671 git_header_html();
6673 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6674 my $greptype;
6675 if ($searchtype eq 'commit') {
6676 $greptype = "--grep=";
6677 } elsif ($searchtype eq 'author') {
6678 $greptype = "--author=";
6679 } elsif ($searchtype eq 'committer') {
6680 $greptype = "--committer=";
6682 $greptype .= $searchtext;
6683 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6684 $greptype, '--regexp-ignore-case',
6685 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6687 my $paging_nav = '';
6688 if ($page > 0) {
6689 $paging_nav .=
6690 $cgi->a({-href => href(action=>"search", hash=>$hash,
6691 searchtext=>$searchtext,
6692 searchtype=>$searchtype)},
6693 "first");
6694 $paging_nav .= " &sdot; " .
6695 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6696 -accesskey => "p", -title => "Alt-p"}, "prev");
6697 } else {
6698 $paging_nav .= "first";
6699 $paging_nav .= " &sdot; prev";
6701 my $next_link = '';
6702 if ($#commitlist >= 100) {
6703 $next_link =
6704 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6705 -accesskey => "n", -title => "Alt-n"}, "next");
6706 $paging_nav .= " &sdot; $next_link";
6707 } else {
6708 $paging_nav .= " &sdot; next";
6711 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6712 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6713 if ($page == 0 && !@commitlist) {
6714 print "<p>No match.</p>\n";
6715 } else {
6716 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6720 if ($searchtype eq 'pickaxe') {
6721 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6722 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6724 print "<table class=\"pickaxe search\">\n";
6725 my $alternate = 1;
6726 local $/ = "\n";
6727 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6728 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6729 ($search_use_regexp ? '--pickaxe-regex' : ());
6730 undef %co;
6731 my @files;
6732 while (my $line = <$fd>) {
6733 chomp $line;
6734 next unless $line;
6736 my %set = parse_difftree_raw_line($line);
6737 if (defined $set{'commit'}) {
6738 # finish previous commit
6739 if (%co) {
6740 print "</td>\n" .
6741 "<td class=\"link\">" .
6742 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6743 " | " .
6744 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6745 print "</td>\n" .
6746 "</tr>\n";
6749 if ($alternate) {
6750 print "<tr class=\"dark\">\n";
6751 } else {
6752 print "<tr class=\"light\">\n";
6754 $alternate ^= 1;
6755 %co = parse_commit($set{'commit'});
6756 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6757 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6758 "<td><i>$author</i></td>\n" .
6759 "<td>" .
6760 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6761 -class => "list subject"},
6762 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6763 } elsif (defined $set{'to_id'}) {
6764 next if ($set{'to_id'} =~ m/^0{40}$/);
6766 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6767 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6768 -class => "list"},
6769 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6770 "<br/>\n";
6773 close $fd;
6775 # finish last commit (warning: repetition!)
6776 if (%co) {
6777 print "</td>\n" .
6778 "<td class=\"link\">" .
6779 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6780 " | " .
6781 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6782 print "</td>\n" .
6783 "</tr>\n";
6786 print "</table>\n";
6789 if ($searchtype eq 'grep') {
6790 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6791 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6793 print "<table class=\"grep_search\">\n";
6794 my $alternate = 1;
6795 my $matches = 0;
6796 local $/ = "\n";
6797 open my $fd, "-|", git_cmd(), 'grep', '-n',
6798 $search_use_regexp ? ('-E', '-i') : '-F',
6799 $searchtext, $co{'tree'};
6800 my $lastfile = '';
6801 while (my $line = <$fd>) {
6802 chomp $line;
6803 my ($file, $lno, $ltext, $binary);
6804 last if ($matches++ > 1000);
6805 if ($line =~ /^Binary file (.+) matches$/) {
6806 $file = $1;
6807 $binary = 1;
6808 } else {
6809 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6811 if ($file ne $lastfile) {
6812 $lastfile and print "</td></tr>\n";
6813 if ($alternate++) {
6814 print "<tr class=\"dark\">\n";
6815 } else {
6816 print "<tr class=\"light\">\n";
6818 print "<td class=\"list\">".
6819 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6820 file_name=>"$file"),
6821 -class => "list"}, esc_path($file));
6822 print "</td><td>\n";
6823 $lastfile = $file;
6825 if ($binary) {
6826 print "<div class=\"binary\">Binary file</div>\n";
6827 } else {
6828 $ltext = untabify($ltext);
6829 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6830 $ltext = esc_html($1, -nbsp=>1);
6831 $ltext .= '<span class="match">';
6832 $ltext .= esc_html($2, -nbsp=>1);
6833 $ltext .= '</span>';
6834 $ltext .= esc_html($3, -nbsp=>1);
6835 } else {
6836 $ltext = esc_html($ltext, -nbsp=>1);
6838 print "<div class=\"pre\">" .
6839 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6840 file_name=>"$file").'#l'.$lno,
6841 -class => "linenr"}, sprintf('%4i', $lno))
6842 . ' ' . $ltext . "</div>\n";
6845 if ($lastfile) {
6846 print "</td></tr>\n";
6847 if ($matches > 1000) {
6848 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6850 } else {
6851 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6853 close $fd;
6855 print "</table>\n";
6857 git_footer_html();
6860 sub git_search_help {
6861 git_header_html();
6862 git_print_page_nav('','', $hash,$hash,$hash);
6863 print <<EOT;
6864 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6865 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6866 the pattern entered is recognized as the POSIX extended
6867 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6868 insensitive).</p>
6869 <dl>
6870 <dt><b>commit</b></dt>
6871 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6873 my $have_grep = gitweb_check_feature('grep');
6874 if ($have_grep) {
6875 print <<EOT;
6876 <dt><b>grep</b></dt>
6877 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6878 a different one) are searched for the given pattern. On large trees, this search can take
6879 a while and put some strain on the server, so please use it with some consideration. Note that
6880 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6881 case-sensitive.</dd>
6884 print <<EOT;
6885 <dt><b>author</b></dt>
6886 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6887 <dt><b>committer</b></dt>
6888 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6890 my $have_pickaxe = gitweb_check_feature('pickaxe');
6891 if ($have_pickaxe) {
6892 print <<EOT;
6893 <dt><b>pickaxe</b></dt>
6894 <dd>All commits that caused the string to appear or disappear from any file (changes that
6895 added, removed or "modified" the string) will be listed. This search can take a while and
6896 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6897 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6900 print "</dl>\n";
6901 git_footer_html();
6904 sub git_shortlog {
6905 git_log_generic('shortlog', \&git_shortlog_body,
6906 $hash, $hash_parent);
6909 ## ......................................................................
6910 ## feeds (RSS, Atom; OPML)
6912 sub git_feed {
6913 my $format = shift || 'atom';
6914 my $have_blame = gitweb_check_feature('blame');
6916 # Atom: http://www.atomenabled.org/developers/syndication/
6917 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6918 if ($format ne 'rss' && $format ne 'atom') {
6919 die_error(400, "Unknown web feed format");
6922 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6923 my $head = $hash || 'HEAD';
6924 my @commitlist = parse_commits($head, 150, 0, $file_name);
6926 my %latest_commit;
6927 my %latest_date;
6928 my $content_type = "application/$format+xml";
6929 if (defined $cgi->http('HTTP_ACCEPT') &&
6930 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6931 # browser (feed reader) prefers text/xml
6932 $content_type = 'text/xml';
6934 if (defined($commitlist[0])) {
6935 %latest_commit = %{$commitlist[0]};
6936 my $latest_epoch = $latest_commit{'committer_epoch'};
6937 %latest_date = parse_date($latest_epoch);
6938 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6939 if (defined $if_modified) {
6940 my $since;
6941 if (eval { require HTTP::Date; 1; }) {
6942 $since = HTTP::Date::str2time($if_modified);
6943 } elsif (eval { require Time::ParseDate; 1; }) {
6944 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6946 if (defined $since && $latest_epoch <= $since) {
6947 print $cgi->header(
6948 -type => $content_type,
6949 -charset => 'utf-8',
6950 -last_modified => $latest_date{'rfc2822'},
6951 -status => '304 Not Modified');
6952 return;
6955 print $cgi->header(
6956 -type => $content_type,
6957 -charset => 'utf-8',
6958 -last_modified => $latest_date{'rfc2822'});
6959 } else {
6960 print $cgi->header(
6961 -type => $content_type,
6962 -charset => 'utf-8');
6965 # Optimization: skip generating the body if client asks only
6966 # for Last-Modified date.
6967 return if ($cgi->request_method() eq 'HEAD');
6969 # header variables
6970 my $title = "$site_name - $project/$action";
6971 my $feed_type = 'log';
6972 if (defined $hash) {
6973 $title .= " - '$hash'";
6974 $feed_type = 'branch log';
6975 if (defined $file_name) {
6976 $title .= " :: $file_name";
6977 $feed_type = 'history';
6979 } elsif (defined $file_name) {
6980 $title .= " - $file_name";
6981 $feed_type = 'history';
6983 $title .= " $feed_type";
6984 my $descr = git_get_project_description($project);
6985 if (defined $descr) {
6986 $descr = esc_html($descr);
6987 } else {
6988 $descr = "$project " .
6989 ($format eq 'rss' ? 'RSS' : 'Atom') .
6990 " feed";
6992 my $owner = git_get_project_owner($project);
6993 $owner = esc_html($owner);
6995 #header
6996 my $alt_url;
6997 if (defined $file_name) {
6998 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6999 } elsif (defined $hash) {
7000 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7001 } else {
7002 $alt_url = href(-full=>1, action=>"summary");
7004 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7005 if ($format eq 'rss') {
7006 print <<XML;
7007 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7008 <channel>
7010 print "<title>$title</title>\n" .
7011 "<link>$alt_url</link>\n" .
7012 "<description>$descr</description>\n" .
7013 "<language>en</language>\n" .
7014 # project owner is responsible for 'editorial' content
7015 "<managingEditor>$owner</managingEditor>\n";
7016 if (defined $logo || defined $favicon) {
7017 # prefer the logo to the favicon, since RSS
7018 # doesn't allow both
7019 my $img = esc_url($logo || $favicon);
7020 print "<image>\n" .
7021 "<url>$img</url>\n" .
7022 "<title>$title</title>\n" .
7023 "<link>$alt_url</link>\n" .
7024 "</image>\n";
7026 if (%latest_date) {
7027 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7028 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7030 print "<generator>gitweb v.$version/$git_version</generator>\n";
7031 } elsif ($format eq 'atom') {
7032 print <<XML;
7033 <feed xmlns="http://www.w3.org/2005/Atom">
7035 print "<title>$title</title>\n" .
7036 "<subtitle>$descr</subtitle>\n" .
7037 '<link rel="alternate" type="text/html" href="' .
7038 $alt_url . '" />' . "\n" .
7039 '<link rel="self" type="' . $content_type . '" href="' .
7040 $cgi->self_url() . '" />' . "\n" .
7041 "<id>" . href(-full=>1) . "</id>\n" .
7042 # use project owner for feed author
7043 "<author><name>$owner</name></author>\n";
7044 if (defined $favicon) {
7045 print "<icon>" . esc_url($favicon) . "</icon>\n";
7047 if (defined $logo_url) {
7048 # not twice as wide as tall: 72 x 27 pixels
7049 print "<logo>" . esc_url($logo) . "</logo>\n";
7051 if (! %latest_date) {
7052 # dummy date to keep the feed valid until commits trickle in:
7053 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7054 } else {
7055 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7057 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7060 # contents
7061 for (my $i = 0; $i <= $#commitlist; $i++) {
7062 my %co = %{$commitlist[$i]};
7063 my $commit = $co{'id'};
7064 # we read 150, we always show 30 and the ones more recent than 48 hours
7065 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7066 last;
7068 my %cd = parse_date($co{'author_epoch'});
7070 # get list of changed files
7071 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7072 $co{'parent'} || "--root",
7073 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7074 or next;
7075 my @difftree = map { chomp; $_ } <$fd>;
7076 close $fd
7077 or next;
7079 # print element (entry, item)
7080 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7081 if ($format eq 'rss') {
7082 print "<item>\n" .
7083 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7084 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7085 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7086 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7087 "<link>$co_url</link>\n" .
7088 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7089 "<content:encoded>" .
7090 "<![CDATA[\n";
7091 } elsif ($format eq 'atom') {
7092 print "<entry>\n" .
7093 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7094 "<updated>$cd{'iso-8601'}</updated>\n" .
7095 "<author>\n" .
7096 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7097 if ($co{'author_email'}) {
7098 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7100 print "</author>\n" .
7101 # use committer for contributor
7102 "<contributor>\n" .
7103 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7104 if ($co{'committer_email'}) {
7105 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7107 print "</contributor>\n" .
7108 "<published>$cd{'iso-8601'}</published>\n" .
7109 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7110 "<id>$co_url</id>\n" .
7111 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7112 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7114 my $comment = $co{'comment'};
7115 print "<pre>\n";
7116 foreach my $line (@$comment) {
7117 $line = esc_html($line);
7118 print "$line\n";
7120 print "</pre><ul>\n";
7121 foreach my $difftree_line (@difftree) {
7122 my %difftree = parse_difftree_raw_line($difftree_line);
7123 next if !$difftree{'from_id'};
7125 my $file = $difftree{'file'} || $difftree{'to_file'};
7127 print "<li>" .
7128 "[" .
7129 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7130 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7131 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7132 file_name=>$file, file_parent=>$difftree{'from_file'}),
7133 -title => "diff"}, 'D');
7134 if ($have_blame) {
7135 print $cgi->a({-href => href(-full=>1, action=>"blame",
7136 file_name=>$file, hash_base=>$commit),
7137 -title => "blame"}, 'B');
7139 # if this is not a feed of a file history
7140 if (!defined $file_name || $file_name ne $file) {
7141 print $cgi->a({-href => href(-full=>1, action=>"history",
7142 file_name=>$file, hash=>$commit),
7143 -title => "history"}, 'H');
7145 $file = esc_path($file);
7146 print "] ".
7147 "$file</li>\n";
7149 if ($format eq 'rss') {
7150 print "</ul>]]>\n" .
7151 "</content:encoded>\n" .
7152 "</item>\n";
7153 } elsif ($format eq 'atom') {
7154 print "</ul>\n</div>\n" .
7155 "</content>\n" .
7156 "</entry>\n";
7160 # end of feed
7161 if ($format eq 'rss') {
7162 print "</channel>\n</rss>\n";
7163 } elsif ($format eq 'atom') {
7164 print "</feed>\n";
7168 sub git_rss {
7169 git_feed('rss');
7172 sub git_atom {
7173 git_feed('atom');
7176 sub git_opml {
7177 my @list = git_get_projects_list();
7179 print $cgi->header(
7180 -type => 'text/xml',
7181 -charset => 'utf-8',
7182 -content_disposition => 'inline; filename="opml.xml"');
7184 print <<XML;
7185 <?xml version="1.0" encoding="utf-8"?>
7186 <opml version="1.0">
7187 <head>
7188 <title>$site_name OPML Export</title>
7189 </head>
7190 <body>
7191 <outline text="git RSS feeds">
7194 foreach my $pr (@list) {
7195 my %proj = %$pr;
7196 my $head = git_get_head_hash($proj{'path'});
7197 if (!defined $head) {
7198 next;
7200 $git_dir = "$projectroot/$proj{'path'}";
7201 my %co = parse_commit($head);
7202 if (!%co) {
7203 next;
7206 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7207 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7208 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7209 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7211 print <<XML;
7212 </outline>
7213 </body>
7214 </opml>