gitweb: Add optional output caching
[git/jnareb-git.git] / gitweb / gitweb.perl
blob32867098b2d7beec9faf1c876383eb3df2403cdf
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::SimpleFileCache 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) expiration time for objects placed in the cache, in seconds.
308 'expires_in' => 20,
310 # Set to _initialized_ instance of GitwebCache::Capture compatibile capturing
311 # engine, i.e. one implementing ->new() constructor, and ->capture($code)
312 # method. If unset (default), the GitwebCache::Capture::Simple would be used.
313 our $capture;
315 # You define site-wide feature defaults here; override them with
316 # $GITWEB_CONFIG as necessary.
317 our %feature = (
318 # feature => {
319 # 'sub' => feature-sub (subroutine),
320 # 'override' => allow-override (boolean),
321 # 'default' => [ default options...] (array reference)}
323 # if feature is overridable (it means that allow-override has true value),
324 # then feature-sub will be called with default options as parameters;
325 # return value of feature-sub indicates if to enable specified feature
327 # if there is no 'sub' key (no feature-sub), then feature cannot be
328 # overridden
330 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
331 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
332 # is enabled
334 # Enable the 'blame' blob view, showing the last commit that modified
335 # each line in the file. This can be very CPU-intensive.
337 # To enable system wide have in $GITWEB_CONFIG
338 # $feature{'blame'}{'default'} = [1];
339 # To have project specific config enable override in $GITWEB_CONFIG
340 # $feature{'blame'}{'override'} = 1;
341 # and in project config gitweb.blame = 0|1;
342 'blame' => {
343 'sub' => sub { feature_bool('blame', @_) },
344 'override' => 0,
345 'default' => [0]},
347 # Enable the 'snapshot' link, providing a compressed archive of any
348 # tree. This can potentially generate high traffic if you have large
349 # project.
351 # Value is a list of formats defined in %known_snapshot_formats that
352 # you wish to offer.
353 # To disable system wide have in $GITWEB_CONFIG
354 # $feature{'snapshot'}{'default'} = [];
355 # To have project specific config enable override in $GITWEB_CONFIG
356 # $feature{'snapshot'}{'override'} = 1;
357 # and in project config, a comma-separated list of formats or "none"
358 # to disable. Example: gitweb.snapshot = tbz2,zip;
359 'snapshot' => {
360 'sub' => \&feature_snapshot,
361 'override' => 0,
362 'default' => ['tgz']},
364 # Enable text search, which will list the commits which match author,
365 # committer or commit text to a given string. Enabled by default.
366 # Project specific override is not supported.
367 'search' => {
368 'override' => 0,
369 'default' => [1]},
371 # Enable grep search, which will list the files in currently selected
372 # tree containing the given string. Enabled by default. This can be
373 # potentially CPU-intensive, of course.
375 # To enable system wide have in $GITWEB_CONFIG
376 # $feature{'grep'}{'default'} = [1];
377 # To have project specific config enable override in $GITWEB_CONFIG
378 # $feature{'grep'}{'override'} = 1;
379 # and in project config gitweb.grep = 0|1;
380 'grep' => {
381 'sub' => sub { feature_bool('grep', @_) },
382 'override' => 0,
383 'default' => [1]},
385 # Enable the pickaxe search, which will list the commits that modified
386 # a given string in a file. This can be practical and quite faster
387 # alternative to 'blame', but still potentially CPU-intensive.
389 # To enable system wide have in $GITWEB_CONFIG
390 # $feature{'pickaxe'}{'default'} = [1];
391 # To have project specific config enable override in $GITWEB_CONFIG
392 # $feature{'pickaxe'}{'override'} = 1;
393 # and in project config gitweb.pickaxe = 0|1;
394 'pickaxe' => {
395 'sub' => sub { feature_bool('pickaxe', @_) },
396 'override' => 0,
397 'default' => [1]},
399 # Enable showing size of blobs in a 'tree' view, in a separate
400 # column, similar to what 'ls -l' does. This cost a bit of IO.
402 # To disable system wide have in $GITWEB_CONFIG
403 # $feature{'show-sizes'}{'default'} = [0];
404 # To have project specific config enable override in $GITWEB_CONFIG
405 # $feature{'show-sizes'}{'override'} = 1;
406 # and in project config gitweb.showsizes = 0|1;
407 'show-sizes' => {
408 'sub' => sub { feature_bool('showsizes', @_) },
409 'override' => 0,
410 'default' => [1]},
412 # Make gitweb use an alternative format of the URLs which can be
413 # more readable and natural-looking: project name is embedded
414 # directly in the path and the query string contains other
415 # auxiliary information. All gitweb installations recognize
416 # URL in either format; this configures in which formats gitweb
417 # generates links.
419 # To enable system wide have in $GITWEB_CONFIG
420 # $feature{'pathinfo'}{'default'} = [1];
421 # Project specific override is not supported.
423 # Note that you will need to change the default location of CSS,
424 # favicon, logo and possibly other files to an absolute URL. Also,
425 # if gitweb.cgi serves as your indexfile, you will need to force
426 # $my_uri to contain the script name in your $GITWEB_CONFIG.
427 'pathinfo' => {
428 'override' => 0,
429 'default' => [0]},
431 # Make gitweb consider projects in project root subdirectories
432 # to be forks of existing projects. Given project $projname.git,
433 # projects matching $projname/*.git will not be shown in the main
434 # projects list, instead a '+' mark will be added to $projname
435 # there and a 'forks' view will be enabled for the project, listing
436 # all the forks. If project list is taken from a file, forks have
437 # to be listed after the main project.
439 # To enable system wide have in $GITWEB_CONFIG
440 # $feature{'forks'}{'default'} = [1];
441 # Project specific override is not supported.
442 'forks' => {
443 'override' => 0,
444 'default' => [0]},
446 # Insert custom links to the action bar of all project pages.
447 # This enables you mainly to link to third-party scripts integrating
448 # into gitweb; e.g. git-browser for graphical history representation
449 # or custom web-based repository administration interface.
451 # The 'default' value consists of a list of triplets in the form
452 # (label, link, position) where position is the label after which
453 # to insert the link and link is a format string where %n expands
454 # to the project name, %f to the project path within the filesystem,
455 # %h to the current hash (h gitweb parameter) and %b to the current
456 # hash base (hb gitweb parameter); %% expands to %.
458 # To enable system wide have in $GITWEB_CONFIG e.g.
459 # $feature{'actions'}{'default'} = [('graphiclog',
460 # '/git-browser/by-commit.html?r=%n', 'summary')];
461 # Project specific override is not supported.
462 'actions' => {
463 'override' => 0,
464 'default' => []},
466 # Allow gitweb scan project content tags described in ctags/
467 # of project repository, and display the popular Web 2.0-ish
468 # "tag cloud" near the project list. Note that this is something
469 # COMPLETELY different from the normal Git tags.
471 # gitweb by itself can show existing tags, but it does not handle
472 # tagging itself; you need an external application for that.
473 # For an example script, check Girocco's cgi/tagproj.cgi.
474 # You may want to install the HTML::TagCloud Perl module to get
475 # a pretty tag cloud instead of just a list of tags.
477 # To enable system wide have in $GITWEB_CONFIG
478 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
479 # Project specific override is not supported.
480 'ctags' => {
481 'override' => 0,
482 'default' => [0]},
484 # The maximum number of patches in a patchset generated in patch
485 # view. Set this to 0 or undef to disable patch view, or to a
486 # negative number to remove any limit.
488 # To disable system wide have in $GITWEB_CONFIG
489 # $feature{'patches'}{'default'} = [0];
490 # To have project specific config enable override in $GITWEB_CONFIG
491 # $feature{'patches'}{'override'} = 1;
492 # and in project config gitweb.patches = 0|n;
493 # where n is the maximum number of patches allowed in a patchset.
494 'patches' => {
495 'sub' => \&feature_patches,
496 'override' => 0,
497 'default' => [16]},
499 # Avatar support. When this feature is enabled, views such as
500 # shortlog or commit will display an avatar associated with
501 # the email of the committer(s) and/or author(s).
503 # Currently available providers are gravatar and picon.
504 # If an unknown provider is specified, the feature is disabled.
506 # Gravatar depends on Digest::MD5.
507 # Picon currently relies on the indiana.edu database.
509 # To enable system wide have in $GITWEB_CONFIG
510 # $feature{'avatar'}{'default'} = ['<provider>'];
511 # where <provider> is either gravatar or picon.
512 # To have project specific config enable override in $GITWEB_CONFIG
513 # $feature{'avatar'}{'override'} = 1;
514 # and in project config gitweb.avatar = <provider>;
515 'avatar' => {
516 'sub' => \&feature_avatar,
517 'override' => 0,
518 'default' => ['']},
520 # Enable displaying how much time and how many git commands
521 # it took to generate and display page. Disabled by default.
522 # Project specific override is not supported.
523 'timed' => {
524 'override' => 0,
525 'default' => [0]},
527 # Enable turning some links into links to actions which require
528 # JavaScript to run (like 'blame_incremental'). Not enabled by
529 # default. Project specific override is currently not supported.
530 'javascript-actions' => {
531 'override' => 0,
532 'default' => [0]},
534 # Syntax highlighting support. This is based on Daniel Svensson's
535 # and Sham Chukoury's work in gitweb-xmms2.git.
536 # It requires the 'highlight' program present in $PATH,
537 # and therefore is disabled by default.
539 # To enable system wide have in $GITWEB_CONFIG
540 # $feature{'highlight'}{'default'} = [1];
542 'highlight' => {
543 'sub' => sub { feature_bool('highlight', @_) },
544 'override' => 0,
545 'default' => [0]},
548 sub gitweb_get_feature {
549 my ($name) = @_;
550 return unless exists $feature{$name};
551 my ($sub, $override, @defaults) = (
552 $feature{$name}{'sub'},
553 $feature{$name}{'override'},
554 @{$feature{$name}{'default'}});
555 # project specific override is possible only if we have project
556 our $git_dir; # global variable, declared later
557 if (!$override || !defined $git_dir) {
558 return @defaults;
560 if (!defined $sub) {
561 warn "feature $name is not overridable";
562 return @defaults;
564 return $sub->(@defaults);
567 # A wrapper to check if a given feature is enabled.
568 # With this, you can say
570 # my $bool_feat = gitweb_check_feature('bool_feat');
571 # gitweb_check_feature('bool_feat') or somecode;
573 # instead of
575 # my ($bool_feat) = gitweb_get_feature('bool_feat');
576 # (gitweb_get_feature('bool_feat'))[0] or somecode;
578 sub gitweb_check_feature {
579 return (gitweb_get_feature(@_))[0];
583 sub feature_bool {
584 my $key = shift;
585 my ($val) = git_get_project_config($key, '--bool');
587 if (!defined $val) {
588 return ($_[0]);
589 } elsif ($val eq 'true') {
590 return (1);
591 } elsif ($val eq 'false') {
592 return (0);
596 sub feature_snapshot {
597 my (@fmts) = @_;
599 my ($val) = git_get_project_config('snapshot');
601 if ($val) {
602 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
605 return @fmts;
608 sub feature_patches {
609 my @val = (git_get_project_config('patches', '--int'));
611 if (@val) {
612 return @val;
615 return ($_[0]);
618 sub feature_avatar {
619 my @val = (git_get_project_config('avatar'));
621 return @val ? @val : @_;
624 # checking HEAD file with -e is fragile if the repository was
625 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
626 # and then pruned.
627 sub check_head_link {
628 my ($dir) = @_;
629 my $headfile = "$dir/HEAD";
630 return ((-e $headfile) ||
631 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
634 sub check_export_ok {
635 my ($dir) = @_;
636 return (check_head_link($dir) &&
637 (!$export_ok || -e "$dir/$export_ok") &&
638 (!$export_auth_hook || $export_auth_hook->($dir)));
641 # process alternate names for backward compatibility
642 # filter out unsupported (unknown) snapshot formats
643 sub filter_snapshot_fmts {
644 my @fmts = @_;
646 @fmts = map {
647 exists $known_snapshot_format_aliases{$_} ?
648 $known_snapshot_format_aliases{$_} : $_} @fmts;
649 @fmts = grep {
650 exists $known_snapshot_formats{$_} &&
651 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
654 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
655 sub evaluate_gitweb_config {
656 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
657 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
658 # die if there are errors parsing config file
659 if (-e $GITWEB_CONFIG) {
660 do $GITWEB_CONFIG;
661 die $@ if $@;
662 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
663 do $GITWEB_CONFIG_SYSTEM;
664 die $@ if $@;
668 # Get loadavg of system, to compare against $maxload.
669 # Currently it requires '/proc/loadavg' present to get loadavg;
670 # if it is not present it returns 0, which means no load checking.
671 sub get_loadavg {
672 if( -e '/proc/loadavg' ){
673 open my $fd, '<', '/proc/loadavg'
674 or return 0;
675 my @load = split(/\s+/, scalar <$fd>);
676 close $fd;
678 # The first three columns measure CPU and IO utilization of the last one,
679 # five, and 10 minute periods. The fourth column shows the number of
680 # currently running processes and the total number of processes in the m/n
681 # format. The last column displays the last process ID used.
682 return $load[0] || 0;
684 # additional checks for load average should go here for things that don't export
685 # /proc/loadavg
687 return 0;
690 # version of the core git binary
691 our $git_version;
692 sub evaluate_git_version {
693 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
694 $number_of_git_cmds++;
697 sub check_loadavg {
698 if (defined $maxload && get_loadavg() > $maxload) {
699 die_error(503, "The load average on the server is too high");
703 # ======================================================================
704 # input validation and dispatch
706 # input parameters can be collected from a variety of sources (presently, CGI
707 # and PATH_INFO), so we define an %input_params hash that collects them all
708 # together during validation: this allows subsequent uses (e.g. href()) to be
709 # agnostic of the parameter origin
711 our %input_params = ();
713 # input parameters are stored with the long parameter name as key. This will
714 # also be used in the href subroutine to convert parameters to their CGI
715 # equivalent, and since the href() usage is the most frequent one, we store
716 # the name -> CGI key mapping here, instead of the reverse.
718 # XXX: Warning: If you touch this, check the search form for updating,
719 # too.
721 our @cgi_param_mapping = (
722 project => "p",
723 action => "a",
724 file_name => "f",
725 file_parent => "fp",
726 hash => "h",
727 hash_parent => "hp",
728 hash_base => "hb",
729 hash_parent_base => "hpb",
730 page => "pg",
731 order => "o",
732 searchtext => "s",
733 searchtype => "st",
734 snapshot_format => "sf",
735 extra_options => "opt",
736 search_use_regexp => "sr",
737 # this must be last entry (for manipulation from JavaScript)
738 javascript => "js"
740 our %cgi_param_mapping = @cgi_param_mapping;
742 # we will also need to know the possible actions, for validation
743 our %actions = (
744 "blame" => \&git_blame,
745 "blame_incremental" => \&git_blame_incremental,
746 "blame_data" => \&git_blame_data,
747 "blobdiff" => \&git_blobdiff,
748 "blobdiff_plain" => \&git_blobdiff_plain,
749 "blob" => \&git_blob,
750 "blob_plain" => \&git_blob_plain,
751 "commitdiff" => \&git_commitdiff,
752 "commitdiff_plain" => \&git_commitdiff_plain,
753 "commit" => \&git_commit,
754 "forks" => \&git_forks,
755 "heads" => \&git_heads,
756 "history" => \&git_history,
757 "log" => \&git_log,
758 "patch" => \&git_patch,
759 "patches" => \&git_patches,
760 "rss" => \&git_rss,
761 "atom" => \&git_atom,
762 "search" => \&git_search,
763 "search_help" => \&git_search_help,
764 "shortlog" => \&git_shortlog,
765 "summary" => \&git_summary,
766 "tag" => \&git_tag,
767 "tags" => \&git_tags,
768 "tree" => \&git_tree,
769 "snapshot" => \&git_snapshot,
770 "object" => \&git_object,
771 # those below don't need $project
772 "opml" => \&git_opml,
773 "project_list" => \&git_project_list,
774 "project_index" => \&git_project_index,
777 # finally, we have the hash of allowed extra_options for the commands that
778 # allow them
779 our %allowed_options = (
780 "--no-merges" => [ qw(rss atom log shortlog history) ],
783 # fill %input_params with the CGI parameters. All values except for 'opt'
784 # should be single values, but opt can be an array. We should probably
785 # build an array of parameters that can be multi-valued, but since for the time
786 # being it's only this one, we just single it out
787 sub evaluate_query_params {
788 our $cgi;
790 while (my ($name, $symbol) = each %cgi_param_mapping) {
791 if ($symbol eq 'opt') {
792 $input_params{$name} = [ $cgi->param($symbol) ];
793 } else {
794 $input_params{$name} = $cgi->param($symbol);
799 # now read PATH_INFO and update the parameter list for missing parameters
800 sub evaluate_path_info {
801 return if defined $input_params{'project'};
802 return if !$path_info;
803 $path_info =~ s,^/+,,;
804 return if !$path_info;
806 # find which part of PATH_INFO is project
807 my $project = $path_info;
808 $project =~ s,/+$,,;
809 while ($project && !check_head_link("$projectroot/$project")) {
810 $project =~ s,/*[^/]*$,,;
812 return unless $project;
813 $input_params{'project'} = $project;
815 # do not change any parameters if an action is given using the query string
816 return if $input_params{'action'};
817 $path_info =~ s,^\Q$project\E/*,,;
819 # next, check if we have an action
820 my $action = $path_info;
821 $action =~ s,/.*$,,;
822 if (exists $actions{$action}) {
823 $path_info =~ s,^$action/*,,;
824 $input_params{'action'} = $action;
827 # list of actions that want hash_base instead of hash, but can have no
828 # pathname (f) parameter
829 my @wants_base = (
830 'tree',
831 'history',
834 # we want to catch, among others
835 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
836 my ($parentrefname, $parentpathname, $refname, $pathname) =
837 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
839 # first, analyze the 'current' part
840 if (defined $pathname) {
841 # we got "branch:filename" or "branch:dir/"
842 # we could use git_get_type(branch:pathname), but:
843 # - it needs $git_dir
844 # - it does a git() call
845 # - the convention of terminating directories with a slash
846 # makes it superfluous
847 # - embedding the action in the PATH_INFO would make it even
848 # more superfluous
849 $pathname =~ s,^/+,,;
850 if (!$pathname || substr($pathname, -1) eq "/") {
851 $input_params{'action'} ||= "tree";
852 $pathname =~ s,/$,,;
853 } else {
854 # the default action depends on whether we had parent info
855 # or not
856 if ($parentrefname) {
857 $input_params{'action'} ||= "blobdiff_plain";
858 } else {
859 $input_params{'action'} ||= "blob_plain";
862 $input_params{'hash_base'} ||= $refname;
863 $input_params{'file_name'} ||= $pathname;
864 } elsif (defined $refname) {
865 # we got "branch". In this case we have to choose if we have to
866 # set hash or hash_base.
868 # Most of the actions without a pathname only want hash to be
869 # set, except for the ones specified in @wants_base that want
870 # hash_base instead. It should also be noted that hand-crafted
871 # links having 'history' as an action and no pathname or hash
872 # set will fail, but that happens regardless of PATH_INFO.
873 if (defined $parentrefname) {
874 # if there is parent let the default be 'shortlog' action
875 # (for http://git.example.com/repo.git/A..B links); if there
876 # is no parent, dispatch will detect type of object and set
877 # action appropriately if required (if action is not set)
878 $input_params{'action'} ||= "shortlog";
880 if ($input_params{'action'} &&
881 grep { $_ eq $input_params{'action'} } @wants_base) {
882 $input_params{'hash_base'} ||= $refname;
883 } else {
884 $input_params{'hash'} ||= $refname;
888 # next, handle the 'parent' part, if present
889 if (defined $parentrefname) {
890 # a missing pathspec defaults to the 'current' filename, allowing e.g.
891 # someproject/blobdiff/oldrev..newrev:/filename
892 if ($parentpathname) {
893 $parentpathname =~ s,^/+,,;
894 $parentpathname =~ s,/$,,;
895 $input_params{'file_parent'} ||= $parentpathname;
896 } else {
897 $input_params{'file_parent'} ||= $input_params{'file_name'};
899 # we assume that hash_parent_base is wanted if a path was specified,
900 # or if the action wants hash_base instead of hash
901 if (defined $input_params{'file_parent'} ||
902 grep { $_ eq $input_params{'action'} } @wants_base) {
903 $input_params{'hash_parent_base'} ||= $parentrefname;
904 } else {
905 $input_params{'hash_parent'} ||= $parentrefname;
909 # for the snapshot action, we allow URLs in the form
910 # $project/snapshot/$hash.ext
911 # where .ext determines the snapshot and gets removed from the
912 # passed $refname to provide the $hash.
914 # To be able to tell that $refname includes the format extension, we
915 # require the following two conditions to be satisfied:
916 # - the hash input parameter MUST have been set from the $refname part
917 # of the URL (i.e. they must be equal)
918 # - the snapshot format MUST NOT have been defined already (e.g. from
919 # CGI parameter sf)
920 # It's also useless to try any matching unless $refname has a dot,
921 # so we check for that too
922 if (defined $input_params{'action'} &&
923 $input_params{'action'} eq 'snapshot' &&
924 defined $refname && index($refname, '.') != -1 &&
925 $refname eq $input_params{'hash'} &&
926 !defined $input_params{'snapshot_format'}) {
927 # We loop over the known snapshot formats, checking for
928 # extensions. Allowed extensions are both the defined suffix
929 # (which includes the initial dot already) and the snapshot
930 # format key itself, with a prepended dot
931 while (my ($fmt, $opt) = each %known_snapshot_formats) {
932 my $hash = $refname;
933 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
934 next;
936 my $sfx = $1;
937 # a valid suffix was found, so set the snapshot format
938 # and reset the hash parameter
939 $input_params{'snapshot_format'} = $fmt;
940 $input_params{'hash'} = $hash;
941 # we also set the format suffix to the one requested
942 # in the URL: this way a request for e.g. .tgz returns
943 # a .tgz instead of a .tar.gz
944 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
945 last;
950 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
951 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
952 $searchtext, $search_regexp);
953 sub evaluate_and_validate_params {
954 our $action = $input_params{'action'};
955 if (defined $action) {
956 if (!validate_action($action)) {
957 die_error(400, "Invalid action parameter");
961 # parameters which are pathnames
962 our $project = $input_params{'project'};
963 if (defined $project) {
964 if (!validate_project($project)) {
965 undef $project;
966 die_error(404, "No such project");
970 our $file_name = $input_params{'file_name'};
971 if (defined $file_name) {
972 if (!validate_pathname($file_name)) {
973 die_error(400, "Invalid file parameter");
977 our $file_parent = $input_params{'file_parent'};
978 if (defined $file_parent) {
979 if (!validate_pathname($file_parent)) {
980 die_error(400, "Invalid file parent parameter");
984 # parameters which are refnames
985 our $hash = $input_params{'hash'};
986 if (defined $hash) {
987 if (!validate_refname($hash)) {
988 die_error(400, "Invalid hash parameter");
992 our $hash_parent = $input_params{'hash_parent'};
993 if (defined $hash_parent) {
994 if (!validate_refname($hash_parent)) {
995 die_error(400, "Invalid hash parent parameter");
999 our $hash_base = $input_params{'hash_base'};
1000 if (defined $hash_base) {
1001 if (!validate_refname($hash_base)) {
1002 die_error(400, "Invalid hash base parameter");
1006 our @extra_options = @{$input_params{'extra_options'}};
1007 # @extra_options is always defined, since it can only be (currently) set from
1008 # CGI, and $cgi->param() returns the empty array in array context if the param
1009 # is not set
1010 foreach my $opt (@extra_options) {
1011 if (not exists $allowed_options{$opt}) {
1012 die_error(400, "Invalid option parameter");
1014 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1015 die_error(400, "Invalid option parameter for this action");
1019 our $hash_parent_base = $input_params{'hash_parent_base'};
1020 if (defined $hash_parent_base) {
1021 if (!validate_refname($hash_parent_base)) {
1022 die_error(400, "Invalid hash parent base parameter");
1026 # other parameters
1027 our $page = $input_params{'page'};
1028 if (defined $page) {
1029 if ($page =~ m/[^0-9]/) {
1030 die_error(400, "Invalid page parameter");
1034 our $searchtype = $input_params{'searchtype'};
1035 if (defined $searchtype) {
1036 if ($searchtype =~ m/[^a-z]/) {
1037 die_error(400, "Invalid searchtype parameter");
1041 our $search_use_regexp = $input_params{'search_use_regexp'};
1043 our $searchtext = $input_params{'searchtext'};
1044 our $search_regexp;
1045 if (defined $searchtext) {
1046 if (length($searchtext) < 2) {
1047 die_error(403, "At least two characters are required for search parameter");
1049 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1053 # path to the current git repository
1054 our $git_dir;
1055 sub evaluate_git_dir {
1056 our $git_dir = "$projectroot/$project" if $project;
1059 our (@snapshot_fmts, $git_avatar);
1060 sub configure_gitweb_features {
1061 # list of supported snapshot formats
1062 our @snapshot_fmts = gitweb_get_feature('snapshot');
1063 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1065 # check that the avatar feature is set to a known provider name,
1066 # and for each provider check if the dependencies are satisfied.
1067 # if the provider name is invalid or the dependencies are not met,
1068 # reset $git_avatar to the empty string.
1069 our ($git_avatar) = gitweb_get_feature('avatar');
1070 if ($git_avatar eq 'gravatar') {
1071 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1072 } elsif ($git_avatar eq 'picon') {
1073 # no dependencies
1074 } else {
1075 $git_avatar = '';
1079 # custom error handler: 'die <message>' is Internal Server Error
1080 sub handle_errors_html {
1081 my $msg = shift; # it is already HTML escaped
1083 # to avoid infinite loop where error occurs in die_error,
1084 # change handler to default handler, disabling handle_errors_html
1085 set_message("Error occured when inside die_error:\n$msg");
1087 # you cannot jump out of die_error when called as error handler;
1088 # the subroutine set via CGI::Carp::set_message is called _after_
1089 # HTTP headers are already written, so it cannot write them itself
1090 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1092 set_message(\&handle_errors_html);
1094 # dispatch
1095 sub dispatch {
1096 if (!defined $action) {
1097 if (defined $hash) {
1098 $action = git_get_type($hash);
1099 } elsif (defined $hash_base && defined $file_name) {
1100 $action = git_get_type("$hash_base:$file_name");
1101 } elsif (defined $project) {
1102 $action = 'summary';
1103 } else {
1104 $action = 'project_list';
1107 if (!defined($actions{$action})) {
1108 die_error(400, "Unknown action");
1110 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1111 !$project) {
1112 die_error(400, "Project needed");
1115 if ($caching_enabled) {
1116 # human readable key identifying gitweb output
1117 my $output_key = href(-replay => 1, -full => 1, -path_info => 0);
1119 cache_output($cache, $capture, $output_key, $actions{$action});
1120 } else {
1121 $actions{$action}->();
1125 sub reset_timer {
1126 our $t0 = [Time::HiRes::gettimeofday()]
1127 if defined $t0;
1128 our $number_of_git_cmds = 0;
1131 sub run_request {
1132 reset_timer();
1134 evaluate_uri();
1135 evaluate_gitweb_config();
1136 evaluate_git_version();
1137 check_loadavg();
1138 configure_caching()
1139 if ($caching_enabled);
1141 # $projectroot and $projects_list might be set in gitweb config file
1142 $projects_list ||= $projectroot;
1144 evaluate_query_params();
1145 evaluate_path_info();
1146 evaluate_and_validate_params();
1147 evaluate_git_dir();
1149 configure_gitweb_features();
1151 dispatch();
1154 our $is_last_request = sub { 1 };
1155 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1156 our $CGI = 'CGI';
1157 our $cgi;
1158 sub configure_as_fcgi {
1159 require CGI::Fast;
1160 our $CGI = 'CGI::Fast';
1162 my $request_number = 0;
1163 # let each child service 100 requests
1164 our $is_last_request = sub { ++$request_number > 100 };
1166 sub evaluate_argv {
1167 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1168 configure_as_fcgi()
1169 if $script_name =~ /\.fcgi$/;
1171 return unless (@ARGV);
1173 require Getopt::Long;
1174 Getopt::Long::GetOptions(
1175 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1176 'nproc|n=i' => sub {
1177 my ($arg, $val) = @_;
1178 return unless eval { require FCGI::ProcManager; 1; };
1179 my $proc_manager = FCGI::ProcManager->new({
1180 n_processes => $val,
1182 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1183 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1184 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1189 sub run {
1190 evaluate_argv();
1192 $pre_listen_hook->()
1193 if $pre_listen_hook;
1195 REQUEST:
1196 while ($cgi = $CGI->new()) {
1197 $pre_dispatch_hook->()
1198 if $pre_dispatch_hook;
1200 run_request();
1202 $post_dispatch_hook->()
1203 if $post_dispatch_hook;
1205 last REQUEST if ($is_last_request->());
1208 DONE_GITWEB:
1212 sub configure_caching {
1213 if (!eval { require GitwebCache::CacheOutput; 1; }) {
1214 # cache is configured _before_ handling request, so $cgi is not defined,
1215 # so we can't just "die" with sending error message to web browser
1216 #die_error(500, "Caching enabled and GitwebCache::CacheOutput not found");
1218 # turn off caching and warn instead
1219 $caching_enabled = 0;
1220 warn "Caching enabled and GitwebCache::CacheOutput not found";
1222 GitwebCache::CacheOutput->import();
1224 # $cache might be initialized (instantiated) cache, i.e. cache object,
1225 # or it might be name of class, or it might be undefined
1226 unless (defined $cache && ref($cache)) {
1227 $cache ||= 'GitwebCache::SimpleFileCache';
1228 eval "require $cache";
1229 die $@ if $@;
1230 $cache = $cache->new({
1231 %cache_options,
1232 #'cache_root' => '/tmp/cache',
1233 #'cache_depth' => 2,
1234 #'expires_in' => 20, # in seconds (CHI compatibile)
1235 # (Cache::Cache compatibile initialization)
1236 'default_expires_in' => $cache_options{'expires_in'},
1237 # (CHI compatibile initialization)
1238 'root_dir' => $cache_options{'cache_root'},
1239 'depth' => $cache_options{'cache_depth'},
1242 unless (defined $capture && ref($capture)) {
1243 require GitwebCache::Capture::Simple;
1244 $capture = GitwebCache::Capture::Simple->new();
1248 run();
1250 if (defined caller) {
1251 # wrapped in a subroutine processing requests,
1252 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1253 return;
1254 } else {
1255 # pure CGI script, serving single request
1256 exit;
1259 ## ======================================================================
1260 ## action links
1262 # possible values of extra options
1263 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1264 # -replay => 1 - start from a current view (replay with modifications)
1265 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1266 sub href {
1267 my %params = @_;
1268 # default is to use -absolute url() i.e. $my_uri
1269 my $href = $params{-full} ? $my_url : $my_uri;
1271 $params{'project'} = $project unless exists $params{'project'};
1273 if ($params{-replay}) {
1274 while (my ($name, $symbol) = each %cgi_param_mapping) {
1275 if (!exists $params{$name}) {
1276 $params{$name} = $input_params{$name};
1281 my $use_pathinfo = gitweb_check_feature('pathinfo');
1282 if (defined $params{'project'} &&
1283 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1284 # try to put as many parameters as possible in PATH_INFO:
1285 # - project name
1286 # - action
1287 # - hash_parent or hash_parent_base:/file_parent
1288 # - hash or hash_base:/filename
1289 # - the snapshot_format as an appropriate suffix
1291 # When the script is the root DirectoryIndex for the domain,
1292 # $href here would be something like http://gitweb.example.com/
1293 # Thus, we strip any trailing / from $href, to spare us double
1294 # slashes in the final URL
1295 $href =~ s,/$,,;
1297 # Then add the project name, if present
1298 $href .= "/".esc_url($params{'project'});
1299 delete $params{'project'};
1301 # since we destructively absorb parameters, we keep this
1302 # boolean that remembers if we're handling a snapshot
1303 my $is_snapshot = $params{'action'} eq 'snapshot';
1305 # Summary just uses the project path URL, any other action is
1306 # added to the URL
1307 if (defined $params{'action'}) {
1308 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1309 delete $params{'action'};
1312 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1313 # stripping nonexistent or useless pieces
1314 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1315 || $params{'hash_parent'} || $params{'hash'});
1316 if (defined $params{'hash_base'}) {
1317 if (defined $params{'hash_parent_base'}) {
1318 $href .= esc_url($params{'hash_parent_base'});
1319 # skip the file_parent if it's the same as the file_name
1320 if (defined $params{'file_parent'}) {
1321 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1322 delete $params{'file_parent'};
1323 } elsif ($params{'file_parent'} !~ /\.\./) {
1324 $href .= ":/".esc_url($params{'file_parent'});
1325 delete $params{'file_parent'};
1328 $href .= "..";
1329 delete $params{'hash_parent'};
1330 delete $params{'hash_parent_base'};
1331 } elsif (defined $params{'hash_parent'}) {
1332 $href .= esc_url($params{'hash_parent'}). "..";
1333 delete $params{'hash_parent'};
1336 $href .= esc_url($params{'hash_base'});
1337 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1338 $href .= ":/".esc_url($params{'file_name'});
1339 delete $params{'file_name'};
1341 delete $params{'hash'};
1342 delete $params{'hash_base'};
1343 } elsif (defined $params{'hash'}) {
1344 $href .= esc_url($params{'hash'});
1345 delete $params{'hash'};
1348 # If the action was a snapshot, we can absorb the
1349 # snapshot_format parameter too
1350 if ($is_snapshot) {
1351 my $fmt = $params{'snapshot_format'};
1352 # snapshot_format should always be defined when href()
1353 # is called, but just in case some code forgets, we
1354 # fall back to the default
1355 $fmt ||= $snapshot_fmts[0];
1356 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1357 delete $params{'snapshot_format'};
1361 # now encode the parameters explicitly
1362 my @result = ();
1363 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1364 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1365 if (defined $params{$name}) {
1366 if (ref($params{$name}) eq "ARRAY") {
1367 foreach my $par (@{$params{$name}}) {
1368 push @result, $symbol . "=" . esc_param($par);
1370 } else {
1371 push @result, $symbol . "=" . esc_param($params{$name});
1375 $href .= "?" . join(';', @result) if scalar @result;
1377 return $href;
1381 ## ======================================================================
1382 ## validation, quoting/unquoting and escaping
1384 sub validate_action {
1385 my $input = shift || return undef;
1386 return undef unless exists $actions{$input};
1387 return $input;
1390 sub validate_project {
1391 my $input = shift || return undef;
1392 if (!validate_pathname($input) ||
1393 !(-d "$projectroot/$input") ||
1394 !check_export_ok("$projectroot/$input") ||
1395 ($strict_export && !project_in_list($input))) {
1396 return undef;
1397 } else {
1398 return $input;
1402 sub validate_pathname {
1403 my $input = shift || return undef;
1405 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1406 # at the beginning, at the end, and between slashes.
1407 # also this catches doubled slashes
1408 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1409 return undef;
1411 # no null characters
1412 if ($input =~ m!\0!) {
1413 return undef;
1415 return $input;
1418 sub validate_refname {
1419 my $input = shift || return undef;
1421 # textual hashes are O.K.
1422 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1423 return $input;
1425 # it must be correct pathname
1426 $input = validate_pathname($input)
1427 or return undef;
1428 # restrictions on ref name according to git-check-ref-format
1429 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1430 return undef;
1432 return $input;
1435 # decode sequences of octets in utf8 into Perl's internal form,
1436 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1437 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1438 sub to_utf8 {
1439 my $str = shift;
1440 return undef unless defined $str;
1441 if (utf8::valid($str)) {
1442 utf8::decode($str);
1443 return $str;
1444 } else {
1445 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1449 # quote unsafe chars, but keep the slash, even when it's not
1450 # correct, but quoted slashes look too horrible in bookmarks
1451 sub esc_param {
1452 my $str = shift;
1453 return undef unless defined $str;
1454 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1455 $str =~ s/ /\+/g;
1456 return $str;
1459 # quote unsafe chars in whole URL, so some characters cannot be quoted
1460 sub esc_url {
1461 my $str = shift;
1462 return undef unless defined $str;
1463 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1464 $str =~ s/ /\+/g;
1465 return $str;
1468 # replace invalid utf8 character with SUBSTITUTION sequence
1469 sub esc_html {
1470 my $str = shift;
1471 my %opts = @_;
1473 return undef unless defined $str;
1475 $str = to_utf8($str);
1476 $str = $cgi->escapeHTML($str);
1477 if ($opts{'-nbsp'}) {
1478 $str =~ s/ /&nbsp;/g;
1480 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1481 return $str;
1484 # quote control characters and escape filename to HTML
1485 sub esc_path {
1486 my $str = shift;
1487 my %opts = @_;
1489 return undef unless defined $str;
1491 $str = to_utf8($str);
1492 $str = $cgi->escapeHTML($str);
1493 if ($opts{'-nbsp'}) {
1494 $str =~ s/ /&nbsp;/g;
1496 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1497 return $str;
1500 # Make control characters "printable", using character escape codes (CEC)
1501 sub quot_cec {
1502 my $cntrl = shift;
1503 my %opts = @_;
1504 my %es = ( # character escape codes, aka escape sequences
1505 "\t" => '\t', # tab (HT)
1506 "\n" => '\n', # line feed (LF)
1507 "\r" => '\r', # carrige return (CR)
1508 "\f" => '\f', # form feed (FF)
1509 "\b" => '\b', # backspace (BS)
1510 "\a" => '\a', # alarm (bell) (BEL)
1511 "\e" => '\e', # escape (ESC)
1512 "\013" => '\v', # vertical tab (VT)
1513 "\000" => '\0', # nul character (NUL)
1515 my $chr = ( (exists $es{$cntrl})
1516 ? $es{$cntrl}
1517 : sprintf('\%2x', ord($cntrl)) );
1518 if ($opts{-nohtml}) {
1519 return $chr;
1520 } else {
1521 return "<span class=\"cntrl\">$chr</span>";
1525 # Alternatively use unicode control pictures codepoints,
1526 # Unicode "printable representation" (PR)
1527 sub quot_upr {
1528 my $cntrl = shift;
1529 my %opts = @_;
1531 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1532 if ($opts{-nohtml}) {
1533 return $chr;
1534 } else {
1535 return "<span class=\"cntrl\">$chr</span>";
1539 # git may return quoted and escaped filenames
1540 sub unquote {
1541 my $str = shift;
1543 sub unq {
1544 my $seq = shift;
1545 my %es = ( # character escape codes, aka escape sequences
1546 't' => "\t", # tab (HT, TAB)
1547 'n' => "\n", # newline (NL)
1548 'r' => "\r", # return (CR)
1549 'f' => "\f", # form feed (FF)
1550 'b' => "\b", # backspace (BS)
1551 'a' => "\a", # alarm (bell) (BEL)
1552 'e' => "\e", # escape (ESC)
1553 'v' => "\013", # vertical tab (VT)
1556 if ($seq =~ m/^[0-7]{1,3}$/) {
1557 # octal char sequence
1558 return chr(oct($seq));
1559 } elsif (exists $es{$seq}) {
1560 # C escape sequence, aka character escape code
1561 return $es{$seq};
1563 # quoted ordinary character
1564 return $seq;
1567 if ($str =~ m/^"(.*)"$/) {
1568 # needs unquoting
1569 $str = $1;
1570 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1572 return $str;
1575 # escape tabs (convert tabs to spaces)
1576 sub untabify {
1577 my $line = shift;
1579 while ((my $pos = index($line, "\t")) != -1) {
1580 if (my $count = (8 - ($pos % 8))) {
1581 my $spaces = ' ' x $count;
1582 $line =~ s/\t/$spaces/;
1586 return $line;
1589 sub project_in_list {
1590 my $project = shift;
1591 my @list = git_get_projects_list();
1592 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1595 ## ----------------------------------------------------------------------
1596 ## HTML aware string manipulation
1598 # Try to chop given string on a word boundary between position
1599 # $len and $len+$add_len. If there is no word boundary there,
1600 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1601 # (marking chopped part) would be longer than given string.
1602 sub chop_str {
1603 my $str = shift;
1604 my $len = shift;
1605 my $add_len = shift || 10;
1606 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1608 # Make sure perl knows it is utf8 encoded so we don't
1609 # cut in the middle of a utf8 multibyte char.
1610 $str = to_utf8($str);
1612 # allow only $len chars, but don't cut a word if it would fit in $add_len
1613 # if it doesn't fit, cut it if it's still longer than the dots we would add
1614 # remove chopped character entities entirely
1616 # when chopping in the middle, distribute $len into left and right part
1617 # return early if chopping wouldn't make string shorter
1618 if ($where eq 'center') {
1619 return $str if ($len + 5 >= length($str)); # filler is length 5
1620 $len = int($len/2);
1621 } else {
1622 return $str if ($len + 4 >= length($str)); # filler is length 4
1625 # regexps: ending and beginning with word part up to $add_len
1626 my $endre = qr/.{$len}\w{0,$add_len}/;
1627 my $begre = qr/\w{0,$add_len}.{$len}/;
1629 if ($where eq 'left') {
1630 $str =~ m/^(.*?)($begre)$/;
1631 my ($lead, $body) = ($1, $2);
1632 if (length($lead) > 4) {
1633 $lead = " ...";
1635 return "$lead$body";
1637 } elsif ($where eq 'center') {
1638 $str =~ m/^($endre)(.*)$/;
1639 my ($left, $str) = ($1, $2);
1640 $str =~ m/^(.*?)($begre)$/;
1641 my ($mid, $right) = ($1, $2);
1642 if (length($mid) > 5) {
1643 $mid = " ... ";
1645 return "$left$mid$right";
1647 } else {
1648 $str =~ m/^($endre)(.*)$/;
1649 my $body = $1;
1650 my $tail = $2;
1651 if (length($tail) > 4) {
1652 $tail = "... ";
1654 return "$body$tail";
1658 # takes the same arguments as chop_str, but also wraps a <span> around the
1659 # result with a title attribute if it does get chopped. Additionally, the
1660 # string is HTML-escaped.
1661 sub chop_and_escape_str {
1662 my ($str) = @_;
1664 my $chopped = chop_str(@_);
1665 if ($chopped eq $str) {
1666 return esc_html($chopped);
1667 } else {
1668 $str =~ s/[[:cntrl:]]/?/g;
1669 return $cgi->span({-title=>$str}, esc_html($chopped));
1673 ## ----------------------------------------------------------------------
1674 ## functions returning short strings
1676 # CSS class for given age value (in seconds)
1677 sub age_class {
1678 my $age = shift;
1680 if (!defined $age) {
1681 return "noage";
1682 } elsif ($age < 60*60*2) {
1683 return "age0";
1684 } elsif ($age < 60*60*24*2) {
1685 return "age1";
1686 } else {
1687 return "age2";
1691 # convert age in seconds to "nn units ago" string
1692 sub age_string {
1693 my $age = shift;
1694 my $age_str;
1696 if ($age > 60*60*24*365*2) {
1697 $age_str = (int $age/60/60/24/365);
1698 $age_str .= " years ago";
1699 } elsif ($age > 60*60*24*(365/12)*2) {
1700 $age_str = int $age/60/60/24/(365/12);
1701 $age_str .= " months ago";
1702 } elsif ($age > 60*60*24*7*2) {
1703 $age_str = int $age/60/60/24/7;
1704 $age_str .= " weeks ago";
1705 } elsif ($age > 60*60*24*2) {
1706 $age_str = int $age/60/60/24;
1707 $age_str .= " days ago";
1708 } elsif ($age > 60*60*2) {
1709 $age_str = int $age/60/60;
1710 $age_str .= " hours ago";
1711 } elsif ($age > 60*2) {
1712 $age_str = int $age/60;
1713 $age_str .= " min ago";
1714 } elsif ($age > 2) {
1715 $age_str = int $age;
1716 $age_str .= " sec ago";
1717 } else {
1718 $age_str .= " right now";
1720 return $age_str;
1723 use constant {
1724 S_IFINVALID => 0030000,
1725 S_IFGITLINK => 0160000,
1728 # submodule/subproject, a commit object reference
1729 sub S_ISGITLINK {
1730 my $mode = shift;
1732 return (($mode & S_IFMT) == S_IFGITLINK)
1735 # convert file mode in octal to symbolic file mode string
1736 sub mode_str {
1737 my $mode = oct shift;
1739 if (S_ISGITLINK($mode)) {
1740 return 'm---------';
1741 } elsif (S_ISDIR($mode & S_IFMT)) {
1742 return 'drwxr-xr-x';
1743 } elsif (S_ISLNK($mode)) {
1744 return 'lrwxrwxrwx';
1745 } elsif (S_ISREG($mode)) {
1746 # git cares only about the executable bit
1747 if ($mode & S_IXUSR) {
1748 return '-rwxr-xr-x';
1749 } else {
1750 return '-rw-r--r--';
1752 } else {
1753 return '----------';
1757 # convert file mode in octal to file type string
1758 sub file_type {
1759 my $mode = shift;
1761 if ($mode !~ m/^[0-7]+$/) {
1762 return $mode;
1763 } else {
1764 $mode = oct $mode;
1767 if (S_ISGITLINK($mode)) {
1768 return "submodule";
1769 } elsif (S_ISDIR($mode & S_IFMT)) {
1770 return "directory";
1771 } elsif (S_ISLNK($mode)) {
1772 return "symlink";
1773 } elsif (S_ISREG($mode)) {
1774 return "file";
1775 } else {
1776 return "unknown";
1780 # convert file mode in octal to file type description string
1781 sub file_type_long {
1782 my $mode = shift;
1784 if ($mode !~ m/^[0-7]+$/) {
1785 return $mode;
1786 } else {
1787 $mode = oct $mode;
1790 if (S_ISGITLINK($mode)) {
1791 return "submodule";
1792 } elsif (S_ISDIR($mode & S_IFMT)) {
1793 return "directory";
1794 } elsif (S_ISLNK($mode)) {
1795 return "symlink";
1796 } elsif (S_ISREG($mode)) {
1797 if ($mode & S_IXUSR) {
1798 return "executable";
1799 } else {
1800 return "file";
1802 } else {
1803 return "unknown";
1808 ## ----------------------------------------------------------------------
1809 ## functions returning short HTML fragments, or transforming HTML fragments
1810 ## which don't belong to other sections
1812 # format line of commit message.
1813 sub format_log_line_html {
1814 my $line = shift;
1816 $line = esc_html($line, -nbsp=>1);
1817 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1818 $cgi->a({-href => href(action=>"object", hash=>$1),
1819 -class => "text"}, $1);
1820 }eg;
1822 return $line;
1825 # format marker of refs pointing to given object
1827 # the destination action is chosen based on object type and current context:
1828 # - for annotated tags, we choose the tag view unless it's the current view
1829 # already, in which case we go to shortlog view
1830 # - for other refs, we keep the current view if we're in history, shortlog or
1831 # log view, and select shortlog otherwise
1832 sub format_ref_marker {
1833 my ($refs, $id) = @_;
1834 my $markers = '';
1836 if (defined $refs->{$id}) {
1837 foreach my $ref (@{$refs->{$id}}) {
1838 # this code exploits the fact that non-lightweight tags are the
1839 # only indirect objects, and that they are the only objects for which
1840 # we want to use tag instead of shortlog as action
1841 my ($type, $name) = qw();
1842 my $indirect = ($ref =~ s/\^\{\}$//);
1843 # e.g. tags/v2.6.11 or heads/next
1844 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1845 $type = $1;
1846 $name = $2;
1847 } else {
1848 $type = "ref";
1849 $name = $ref;
1852 my $class = $type;
1853 $class .= " indirect" if $indirect;
1855 my $dest_action = "shortlog";
1857 if ($indirect) {
1858 $dest_action = "tag" unless $action eq "tag";
1859 } elsif ($action =~ /^(history|(short)?log)$/) {
1860 $dest_action = $action;
1863 my $dest = "";
1864 $dest .= "refs/" unless $ref =~ m!^refs/!;
1865 $dest .= $ref;
1867 my $link = $cgi->a({
1868 -href => href(
1869 action=>$dest_action,
1870 hash=>$dest
1871 )}, $name);
1873 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1874 $link . "</span>";
1878 if ($markers) {
1879 return ' <span class="refs">'. $markers . '</span>';
1880 } else {
1881 return "";
1885 # format, perhaps shortened and with markers, title line
1886 sub format_subject_html {
1887 my ($long, $short, $href, $extra) = @_;
1888 $extra = '' unless defined($extra);
1890 if (length($short) < length($long)) {
1891 $long =~ s/[[:cntrl:]]/?/g;
1892 return $cgi->a({-href => $href, -class => "list subject",
1893 -title => to_utf8($long)},
1894 esc_html($short)) . $extra;
1895 } else {
1896 return $cgi->a({-href => $href, -class => "list subject"},
1897 esc_html($long)) . $extra;
1901 # Rather than recomputing the url for an email multiple times, we cache it
1902 # after the first hit. This gives a visible benefit in views where the avatar
1903 # for the same email is used repeatedly (e.g. shortlog).
1904 # The cache is shared by all avatar engines (currently gravatar only), which
1905 # are free to use it as preferred. Since only one avatar engine is used for any
1906 # given page, there's no risk for cache conflicts.
1907 our %avatar_cache = ();
1909 # Compute the picon url for a given email, by using the picon search service over at
1910 # http://www.cs.indiana.edu/picons/search.html
1911 sub picon_url {
1912 my $email = lc shift;
1913 if (!$avatar_cache{$email}) {
1914 my ($user, $domain) = split('@', $email);
1915 $avatar_cache{$email} =
1916 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1917 "$domain/$user/" .
1918 "users+domains+unknown/up/single";
1920 return $avatar_cache{$email};
1923 # Compute the gravatar url for a given email, if it's not in the cache already.
1924 # Gravatar stores only the part of the URL before the size, since that's the
1925 # one computationally more expensive. This also allows reuse of the cache for
1926 # different sizes (for this particular engine).
1927 sub gravatar_url {
1928 my $email = lc shift;
1929 my $size = shift;
1930 $avatar_cache{$email} ||=
1931 "http://www.gravatar.com/avatar/" .
1932 Digest::MD5::md5_hex($email) . "?s=";
1933 return $avatar_cache{$email} . $size;
1936 # Insert an avatar for the given $email at the given $size if the feature
1937 # is enabled.
1938 sub git_get_avatar {
1939 my ($email, %opts) = @_;
1940 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1941 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1942 $opts{-size} ||= 'default';
1943 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1944 my $url = "";
1945 if ($git_avatar eq 'gravatar') {
1946 $url = gravatar_url($email, $size);
1947 } elsif ($git_avatar eq 'picon') {
1948 $url = picon_url($email);
1950 # Other providers can be added by extending the if chain, defining $url
1951 # as needed. If no variant puts something in $url, we assume avatars
1952 # are completely disabled/unavailable.
1953 if ($url) {
1954 return $pre_white .
1955 "<img width=\"$size\" " .
1956 "class=\"avatar\" " .
1957 "src=\"$url\" " .
1958 "alt=\"\" " .
1959 "/>" . $post_white;
1960 } else {
1961 return "";
1965 sub format_search_author {
1966 my ($author, $searchtype, $displaytext) = @_;
1967 my $have_search = gitweb_check_feature('search');
1969 if ($have_search) {
1970 my $performed = "";
1971 if ($searchtype eq 'author') {
1972 $performed = "authored";
1973 } elsif ($searchtype eq 'committer') {
1974 $performed = "committed";
1977 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1978 searchtext=>$author,
1979 searchtype=>$searchtype), class=>"list",
1980 title=>"Search for commits $performed by $author"},
1981 $displaytext);
1983 } else {
1984 return $displaytext;
1988 # format the author name of the given commit with the given tag
1989 # the author name is chopped and escaped according to the other
1990 # optional parameters (see chop_str).
1991 sub format_author_html {
1992 my $tag = shift;
1993 my $co = shift;
1994 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1995 return "<$tag class=\"author\">" .
1996 format_search_author($co->{'author_name'}, "author",
1997 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1998 $author) .
1999 "</$tag>";
2002 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2003 sub format_git_diff_header_line {
2004 my $line = shift;
2005 my $diffinfo = shift;
2006 my ($from, $to) = @_;
2008 if ($diffinfo->{'nparents'}) {
2009 # combined diff
2010 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2011 if ($to->{'href'}) {
2012 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2013 esc_path($to->{'file'}));
2014 } else { # file was deleted (no href)
2015 $line .= esc_path($to->{'file'});
2017 } else {
2018 # "ordinary" diff
2019 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2020 if ($from->{'href'}) {
2021 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2022 'a/' . esc_path($from->{'file'}));
2023 } else { # file was added (no href)
2024 $line .= 'a/' . esc_path($from->{'file'});
2026 $line .= ' ';
2027 if ($to->{'href'}) {
2028 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2029 'b/' . esc_path($to->{'file'}));
2030 } else { # file was deleted
2031 $line .= 'b/' . esc_path($to->{'file'});
2035 return "<div class=\"diff header\">$line</div>\n";
2038 # format extended diff header line, before patch itself
2039 sub format_extended_diff_header_line {
2040 my $line = shift;
2041 my $diffinfo = shift;
2042 my ($from, $to) = @_;
2044 # match <path>
2045 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2046 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2047 esc_path($from->{'file'}));
2049 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2050 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2051 esc_path($to->{'file'}));
2053 # match single <mode>
2054 if ($line =~ m/\s(\d{6})$/) {
2055 $line .= '<span class="info"> (' .
2056 file_type_long($1) .
2057 ')</span>';
2059 # match <hash>
2060 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2061 # can match only for combined diff
2062 $line = 'index ';
2063 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2064 if ($from->{'href'}[$i]) {
2065 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2066 -class=>"hash"},
2067 substr($diffinfo->{'from_id'}[$i],0,7));
2068 } else {
2069 $line .= '0' x 7;
2071 # separator
2072 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2074 $line .= '..';
2075 if ($to->{'href'}) {
2076 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2077 substr($diffinfo->{'to_id'},0,7));
2078 } else {
2079 $line .= '0' x 7;
2082 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2083 # can match only for ordinary diff
2084 my ($from_link, $to_link);
2085 if ($from->{'href'}) {
2086 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2087 substr($diffinfo->{'from_id'},0,7));
2088 } else {
2089 $from_link = '0' x 7;
2091 if ($to->{'href'}) {
2092 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2093 substr($diffinfo->{'to_id'},0,7));
2094 } else {
2095 $to_link = '0' x 7;
2097 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2098 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2101 return $line . "<br/>\n";
2104 # format from-file/to-file diff header
2105 sub format_diff_from_to_header {
2106 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2107 my $line;
2108 my $result = '';
2110 $line = $from_line;
2111 #assert($line =~ m/^---/) if DEBUG;
2112 # no extra formatting for "^--- /dev/null"
2113 if (! $diffinfo->{'nparents'}) {
2114 # ordinary (single parent) diff
2115 if ($line =~ m!^--- "?a/!) {
2116 if ($from->{'href'}) {
2117 $line = '--- a/' .
2118 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2119 esc_path($from->{'file'}));
2120 } else {
2121 $line = '--- a/' .
2122 esc_path($from->{'file'});
2125 $result .= qq!<div class="diff from_file">$line</div>\n!;
2127 } else {
2128 # combined diff (merge commit)
2129 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2130 if ($from->{'href'}[$i]) {
2131 $line = '--- ' .
2132 $cgi->a({-href=>href(action=>"blobdiff",
2133 hash_parent=>$diffinfo->{'from_id'}[$i],
2134 hash_parent_base=>$parents[$i],
2135 file_parent=>$from->{'file'}[$i],
2136 hash=>$diffinfo->{'to_id'},
2137 hash_base=>$hash,
2138 file_name=>$to->{'file'}),
2139 -class=>"path",
2140 -title=>"diff" . ($i+1)},
2141 $i+1) .
2142 '/' .
2143 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2144 esc_path($from->{'file'}[$i]));
2145 } else {
2146 $line = '--- /dev/null';
2148 $result .= qq!<div class="diff from_file">$line</div>\n!;
2152 $line = $to_line;
2153 #assert($line =~ m/^\+\+\+/) if DEBUG;
2154 # no extra formatting for "^+++ /dev/null"
2155 if ($line =~ m!^\+\+\+ "?b/!) {
2156 if ($to->{'href'}) {
2157 $line = '+++ b/' .
2158 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2159 esc_path($to->{'file'}));
2160 } else {
2161 $line = '+++ b/' .
2162 esc_path($to->{'file'});
2165 $result .= qq!<div class="diff to_file">$line</div>\n!;
2167 return $result;
2170 # create note for patch simplified by combined diff
2171 sub format_diff_cc_simplified {
2172 my ($diffinfo, @parents) = @_;
2173 my $result = '';
2175 $result .= "<div class=\"diff header\">" .
2176 "diff --cc ";
2177 if (!is_deleted($diffinfo)) {
2178 $result .= $cgi->a({-href => href(action=>"blob",
2179 hash_base=>$hash,
2180 hash=>$diffinfo->{'to_id'},
2181 file_name=>$diffinfo->{'to_file'}),
2182 -class => "path"},
2183 esc_path($diffinfo->{'to_file'}));
2184 } else {
2185 $result .= esc_path($diffinfo->{'to_file'});
2187 $result .= "</div>\n" . # class="diff header"
2188 "<div class=\"diff nodifferences\">" .
2189 "Simple merge" .
2190 "</div>\n"; # class="diff nodifferences"
2192 return $result;
2195 # format patch (diff) line (not to be used for diff headers)
2196 sub format_diff_line {
2197 my $line = shift;
2198 my ($from, $to) = @_;
2199 my $diff_class = "";
2201 chomp $line;
2203 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2204 # combined diff
2205 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2206 if ($line =~ m/^\@{3}/) {
2207 $diff_class = " chunk_header";
2208 } elsif ($line =~ m/^\\/) {
2209 $diff_class = " incomplete";
2210 } elsif ($prefix =~ tr/+/+/) {
2211 $diff_class = " add";
2212 } elsif ($prefix =~ tr/-/-/) {
2213 $diff_class = " rem";
2215 } else {
2216 # assume ordinary diff
2217 my $char = substr($line, 0, 1);
2218 if ($char eq '+') {
2219 $diff_class = " add";
2220 } elsif ($char eq '-') {
2221 $diff_class = " rem";
2222 } elsif ($char eq '@') {
2223 $diff_class = " chunk_header";
2224 } elsif ($char eq "\\") {
2225 $diff_class = " incomplete";
2228 $line = untabify($line);
2229 if ($from && $to && $line =~ m/^\@{2} /) {
2230 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2231 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2233 $from_lines = 0 unless defined $from_lines;
2234 $to_lines = 0 unless defined $to_lines;
2236 if ($from->{'href'}) {
2237 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2238 -class=>"list"}, $from_text);
2240 if ($to->{'href'}) {
2241 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2242 -class=>"list"}, $to_text);
2244 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2245 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2246 return "<div class=\"diff$diff_class\">$line</div>\n";
2247 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2248 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2249 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2251 @from_text = split(' ', $ranges);
2252 for (my $i = 0; $i < @from_text; ++$i) {
2253 ($from_start[$i], $from_nlines[$i]) =
2254 (split(',', substr($from_text[$i], 1)), 0);
2257 $to_text = pop @from_text;
2258 $to_start = pop @from_start;
2259 $to_nlines = pop @from_nlines;
2261 $line = "<span class=\"chunk_info\">$prefix ";
2262 for (my $i = 0; $i < @from_text; ++$i) {
2263 if ($from->{'href'}[$i]) {
2264 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2265 -class=>"list"}, $from_text[$i]);
2266 } else {
2267 $line .= $from_text[$i];
2269 $line .= " ";
2271 if ($to->{'href'}) {
2272 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2273 -class=>"list"}, $to_text);
2274 } else {
2275 $line .= $to_text;
2277 $line .= " $prefix</span>" .
2278 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2279 return "<div class=\"diff$diff_class\">$line</div>\n";
2281 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2284 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2285 # linked. Pass the hash of the tree/commit to snapshot.
2286 sub format_snapshot_links {
2287 my ($hash) = @_;
2288 my $num_fmts = @snapshot_fmts;
2289 if ($num_fmts > 1) {
2290 # A parenthesized list of links bearing format names.
2291 # e.g. "snapshot (_tar.gz_ _zip_)"
2292 return "snapshot (" . join(' ', map
2293 $cgi->a({
2294 -href => href(
2295 action=>"snapshot",
2296 hash=>$hash,
2297 snapshot_format=>$_
2299 }, $known_snapshot_formats{$_}{'display'})
2300 , @snapshot_fmts) . ")";
2301 } elsif ($num_fmts == 1) {
2302 # A single "snapshot" link whose tooltip bears the format name.
2303 # i.e. "_snapshot_"
2304 my ($fmt) = @snapshot_fmts;
2305 return
2306 $cgi->a({
2307 -href => href(
2308 action=>"snapshot",
2309 hash=>$hash,
2310 snapshot_format=>$fmt
2312 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2313 }, "snapshot");
2314 } else { # $num_fmts == 0
2315 return undef;
2319 ## ......................................................................
2320 ## functions returning values to be passed, perhaps after some
2321 ## transformation, to other functions; e.g. returning arguments to href()
2323 # returns hash to be passed to href to generate gitweb URL
2324 # in -title key it returns description of link
2325 sub get_feed_info {
2326 my $format = shift || 'Atom';
2327 my %res = (action => lc($format));
2329 # feed links are possible only for project views
2330 return unless (defined $project);
2331 # some views should link to OPML, or to generic project feed,
2332 # or don't have specific feed yet (so they should use generic)
2333 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2335 my $branch;
2336 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2337 # from tag links; this also makes possible to detect branch links
2338 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2339 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2340 $branch = $1;
2342 # find log type for feed description (title)
2343 my $type = 'log';
2344 if (defined $file_name) {
2345 $type = "history of $file_name";
2346 $type .= "/" if ($action eq 'tree');
2347 $type .= " on '$branch'" if (defined $branch);
2348 } else {
2349 $type = "log of $branch" if (defined $branch);
2352 $res{-title} = $type;
2353 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2354 $res{'file_name'} = $file_name;
2356 return %res;
2359 ## ----------------------------------------------------------------------
2360 ## git utility subroutines, invoking git commands
2362 # returns path to the core git executable and the --git-dir parameter as list
2363 sub git_cmd {
2364 $number_of_git_cmds++;
2365 return $GIT, '--git-dir='.$git_dir;
2368 # quote the given arguments for passing them to the shell
2369 # quote_command("command", "arg 1", "arg with ' and ! characters")
2370 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2371 # Try to avoid using this function wherever possible.
2372 sub quote_command {
2373 return join(' ',
2374 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2377 # get HEAD ref of given project as hash
2378 sub git_get_head_hash {
2379 return git_get_full_hash(shift, 'HEAD');
2382 sub git_get_full_hash {
2383 return git_get_hash(@_);
2386 sub git_get_short_hash {
2387 return git_get_hash(@_, '--short=7');
2390 sub git_get_hash {
2391 my ($project, $hash, @options) = @_;
2392 my $o_git_dir = $git_dir;
2393 my $retval = undef;
2394 $git_dir = "$projectroot/$project";
2395 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2396 '--verify', '-q', @options, $hash) {
2397 $retval = <$fd>;
2398 chomp $retval if defined $retval;
2399 close $fd;
2401 if (defined $o_git_dir) {
2402 $git_dir = $o_git_dir;
2404 return $retval;
2407 # get type of given object
2408 sub git_get_type {
2409 my $hash = shift;
2411 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2412 my $type = <$fd>;
2413 close $fd or return;
2414 chomp $type;
2415 return $type;
2418 # repository configuration
2419 our $config_file = '';
2420 our %config;
2422 # store multiple values for single key as anonymous array reference
2423 # single values stored directly in the hash, not as [ <value> ]
2424 sub hash_set_multi {
2425 my ($hash, $key, $value) = @_;
2427 if (!exists $hash->{$key}) {
2428 $hash->{$key} = $value;
2429 } elsif (!ref $hash->{$key}) {
2430 $hash->{$key} = [ $hash->{$key}, $value ];
2431 } else {
2432 push @{$hash->{$key}}, $value;
2436 # return hash of git project configuration
2437 # optionally limited to some section, e.g. 'gitweb'
2438 sub git_parse_project_config {
2439 my $section_regexp = shift;
2440 my %config;
2442 local $/ = "\0";
2444 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2445 or return;
2447 while (my $keyval = <$fh>) {
2448 chomp $keyval;
2449 my ($key, $value) = split(/\n/, $keyval, 2);
2451 hash_set_multi(\%config, $key, $value)
2452 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2454 close $fh;
2456 return %config;
2459 # convert config value to boolean: 'true' or 'false'
2460 # no value, number > 0, 'true' and 'yes' values are true
2461 # rest of values are treated as false (never as error)
2462 sub config_to_bool {
2463 my $val = shift;
2465 return 1 if !defined $val; # section.key
2467 # strip leading and trailing whitespace
2468 $val =~ s/^\s+//;
2469 $val =~ s/\s+$//;
2471 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2472 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2475 # convert config value to simple decimal number
2476 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2477 # to be multiplied by 1024, 1048576, or 1073741824
2478 sub config_to_int {
2479 my $val = shift;
2481 # strip leading and trailing whitespace
2482 $val =~ s/^\s+//;
2483 $val =~ s/\s+$//;
2485 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2486 $unit = lc($unit);
2487 # unknown unit is treated as 1
2488 return $num * ($unit eq 'g' ? 1073741824 :
2489 $unit eq 'm' ? 1048576 :
2490 $unit eq 'k' ? 1024 : 1);
2492 return $val;
2495 # convert config value to array reference, if needed
2496 sub config_to_multi {
2497 my $val = shift;
2499 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2502 sub git_get_project_config {
2503 my ($key, $type) = @_;
2505 return unless defined $git_dir;
2507 # key sanity check
2508 return unless ($key);
2509 $key =~ s/^gitweb\.//;
2510 return if ($key =~ m/\W/);
2512 # type sanity check
2513 if (defined $type) {
2514 $type =~ s/^--//;
2515 $type = undef
2516 unless ($type eq 'bool' || $type eq 'int');
2519 # get config
2520 if (!defined $config_file ||
2521 $config_file ne "$git_dir/config") {
2522 %config = git_parse_project_config('gitweb');
2523 $config_file = "$git_dir/config";
2526 # check if config variable (key) exists
2527 return unless exists $config{"gitweb.$key"};
2529 # ensure given type
2530 if (!defined $type) {
2531 return $config{"gitweb.$key"};
2532 } elsif ($type eq 'bool') {
2533 # backward compatibility: 'git config --bool' returns true/false
2534 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2535 } elsif ($type eq 'int') {
2536 return config_to_int($config{"gitweb.$key"});
2538 return $config{"gitweb.$key"};
2541 # get hash of given path at given ref
2542 sub git_get_hash_by_path {
2543 my $base = shift;
2544 my $path = shift || return undef;
2545 my $type = shift;
2547 $path =~ s,/+$,,;
2549 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2550 or die_error(500, "Open git-ls-tree failed");
2551 my $line = <$fd>;
2552 close $fd or return undef;
2554 if (!defined $line) {
2555 # there is no tree or hash given by $path at $base
2556 return undef;
2559 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2560 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2561 if (defined $type && $type ne $2) {
2562 # type doesn't match
2563 return undef;
2565 return $3;
2568 # get path of entry with given hash at given tree-ish (ref)
2569 # used to get 'from' filename for combined diff (merge commit) for renames
2570 sub git_get_path_by_hash {
2571 my $base = shift || return;
2572 my $hash = shift || return;
2574 local $/ = "\0";
2576 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2577 or return undef;
2578 while (my $line = <$fd>) {
2579 chomp $line;
2581 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2582 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2583 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2584 close $fd;
2585 return $1;
2588 close $fd;
2589 return undef;
2592 ## ......................................................................
2593 ## git utility functions, directly accessing git repository
2595 sub git_get_project_description {
2596 my $path = shift;
2598 $git_dir = "$projectroot/$path";
2599 open my $fd, '<', "$git_dir/description"
2600 or return git_get_project_config('description');
2601 my $descr = <$fd>;
2602 close $fd;
2603 if (defined $descr) {
2604 chomp $descr;
2606 return $descr;
2609 sub git_get_project_ctags {
2610 my $path = shift;
2611 my $ctags = {};
2613 $git_dir = "$projectroot/$path";
2614 opendir my $dh, "$git_dir/ctags"
2615 or return $ctags;
2616 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2617 open my $ct, '<', $_ or next;
2618 my $val = <$ct>;
2619 chomp $val;
2620 close $ct;
2621 my $ctag = $_; $ctag =~ s#.*/##;
2622 $ctags->{$ctag} = $val;
2624 closedir $dh;
2625 $ctags;
2628 sub git_populate_project_tagcloud {
2629 my $ctags = shift;
2631 # First, merge different-cased tags; tags vote on casing
2632 my %ctags_lc;
2633 foreach (keys %$ctags) {
2634 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2635 if (not $ctags_lc{lc $_}->{topcount}
2636 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2637 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2638 $ctags_lc{lc $_}->{topname} = $_;
2642 my $cloud;
2643 if (eval { require HTML::TagCloud; 1; }) {
2644 $cloud = HTML::TagCloud->new;
2645 foreach (sort keys %ctags_lc) {
2646 # Pad the title with spaces so that the cloud looks
2647 # less crammed.
2648 my $title = $ctags_lc{$_}->{topname};
2649 $title =~ s/ /&nbsp;/g;
2650 $title =~ s/^/&nbsp;/g;
2651 $title =~ s/$/&nbsp;/g;
2652 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2654 } else {
2655 $cloud = \%ctags_lc;
2657 $cloud;
2660 sub git_show_project_tagcloud {
2661 my ($cloud, $count) = @_;
2662 print STDERR ref($cloud)."..\n";
2663 if (ref $cloud eq 'HTML::TagCloud') {
2664 return $cloud->html_and_css($count);
2665 } else {
2666 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2667 return '<p align="center">' . join (', ', map {
2668 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2669 } splice(@tags, 0, $count)) . '</p>';
2673 sub git_get_project_url_list {
2674 my $path = shift;
2676 $git_dir = "$projectroot/$path";
2677 open my $fd, '<', "$git_dir/cloneurl"
2678 or return wantarray ?
2679 @{ config_to_multi(git_get_project_config('url')) } :
2680 config_to_multi(git_get_project_config('url'));
2681 my @git_project_url_list = map { chomp; $_ } <$fd>;
2682 close $fd;
2684 return wantarray ? @git_project_url_list : \@git_project_url_list;
2687 sub git_get_projects_list {
2688 my ($filter) = @_;
2689 my @list;
2691 $filter ||= '';
2692 $filter =~ s/\.git$//;
2694 my $check_forks = gitweb_check_feature('forks');
2696 if (-d $projects_list) {
2697 # search in directory
2698 my $dir = $projects_list . ($filter ? "/$filter" : '');
2699 # remove the trailing "/"
2700 $dir =~ s!/+$!!;
2701 my $pfxlen = length("$dir");
2702 my $pfxdepth = ($dir =~ tr!/!!);
2704 File::Find::find({
2705 follow_fast => 1, # follow symbolic links
2706 follow_skip => 2, # ignore duplicates
2707 dangling_symlinks => 0, # ignore dangling symlinks, silently
2708 wanted => sub {
2709 # global variables
2710 our $project_maxdepth;
2711 our $projectroot;
2712 # skip project-list toplevel, if we get it.
2713 return if (m!^[/.]$!);
2714 # only directories can be git repositories
2715 return unless (-d $_);
2716 # don't traverse too deep (Find is super slow on os x)
2717 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2718 $File::Find::prune = 1;
2719 return;
2722 my $subdir = substr($File::Find::name, $pfxlen + 1);
2723 # we check related file in $projectroot
2724 my $path = ($filter ? "$filter/" : '') . $subdir;
2725 if (check_export_ok("$projectroot/$path")) {
2726 push @list, { path => $path };
2727 $File::Find::prune = 1;
2730 }, "$dir");
2732 } elsif (-f $projects_list) {
2733 # read from file(url-encoded):
2734 # 'git%2Fgit.git Linus+Torvalds'
2735 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2736 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2737 my %paths;
2738 open my $fd, '<', $projects_list or return;
2739 PROJECT:
2740 while (my $line = <$fd>) {
2741 chomp $line;
2742 my ($path, $owner) = split ' ', $line;
2743 $path = unescape($path);
2744 $owner = unescape($owner);
2745 if (!defined $path) {
2746 next;
2748 if ($filter ne '') {
2749 # looking for forks;
2750 my $pfx = substr($path, 0, length($filter));
2751 if ($pfx ne $filter) {
2752 next PROJECT;
2754 my $sfx = substr($path, length($filter));
2755 if ($sfx !~ /^\/.*\.git$/) {
2756 next PROJECT;
2758 } elsif ($check_forks) {
2759 PATH:
2760 foreach my $filter (keys %paths) {
2761 # looking for forks;
2762 my $pfx = substr($path, 0, length($filter));
2763 if ($pfx ne $filter) {
2764 next PATH;
2766 my $sfx = substr($path, length($filter));
2767 if ($sfx !~ /^\/.*\.git$/) {
2768 next PATH;
2770 # is a fork, don't include it in
2771 # the list
2772 next PROJECT;
2775 if (check_export_ok("$projectroot/$path")) {
2776 my $pr = {
2777 path => $path,
2778 owner => to_utf8($owner),
2780 push @list, $pr;
2781 (my $forks_path = $path) =~ s/\.git$//;
2782 $paths{$forks_path}++;
2785 close $fd;
2787 return @list;
2790 our $gitweb_project_owner = undef;
2791 sub git_get_project_list_from_file {
2793 return if (defined $gitweb_project_owner);
2795 $gitweb_project_owner = {};
2796 # read from file (url-encoded):
2797 # 'git%2Fgit.git Linus+Torvalds'
2798 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2799 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2800 if (-f $projects_list) {
2801 open(my $fd, '<', $projects_list);
2802 while (my $line = <$fd>) {
2803 chomp $line;
2804 my ($pr, $ow) = split ' ', $line;
2805 $pr = unescape($pr);
2806 $ow = unescape($ow);
2807 $gitweb_project_owner->{$pr} = to_utf8($ow);
2809 close $fd;
2813 sub git_get_project_owner {
2814 my $project = shift;
2815 my $owner;
2817 return undef unless $project;
2818 $git_dir = "$projectroot/$project";
2820 if (!defined $gitweb_project_owner) {
2821 git_get_project_list_from_file();
2824 if (exists $gitweb_project_owner->{$project}) {
2825 $owner = $gitweb_project_owner->{$project};
2827 if (!defined $owner){
2828 $owner = git_get_project_config('owner');
2830 if (!defined $owner) {
2831 $owner = get_file_owner("$git_dir");
2834 return $owner;
2837 sub git_get_last_activity {
2838 my ($path) = @_;
2839 my $fd;
2841 $git_dir = "$projectroot/$path";
2842 open($fd, "-|", git_cmd(), 'for-each-ref',
2843 '--format=%(committer)',
2844 '--sort=-committerdate',
2845 '--count=1',
2846 'refs/heads') or return;
2847 my $most_recent = <$fd>;
2848 close $fd or return;
2849 if (defined $most_recent &&
2850 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2851 my $timestamp = $1;
2852 my $age = time - $timestamp;
2853 return ($age, age_string($age));
2855 return (undef, undef);
2858 sub git_get_references {
2859 my $type = shift || "";
2860 my %refs;
2861 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2862 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2863 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2864 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2865 or return;
2867 while (my $line = <$fd>) {
2868 chomp $line;
2869 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2870 if (defined $refs{$1}) {
2871 push @{$refs{$1}}, $2;
2872 } else {
2873 $refs{$1} = [ $2 ];
2877 close $fd or return;
2878 return \%refs;
2881 sub git_get_rev_name_tags {
2882 my $hash = shift || return undef;
2884 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2885 or return;
2886 my $name_rev = <$fd>;
2887 close $fd;
2889 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2890 return $1;
2891 } else {
2892 # catches also '$hash undefined' output
2893 return undef;
2897 ## ----------------------------------------------------------------------
2898 ## parse to hash functions
2900 sub parse_date {
2901 my $epoch = shift;
2902 my $tz = shift || "-0000";
2904 my %date;
2905 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2906 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2907 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2908 $date{'hour'} = $hour;
2909 $date{'minute'} = $min;
2910 $date{'mday'} = $mday;
2911 $date{'day'} = $days[$wday];
2912 $date{'month'} = $months[$mon];
2913 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2914 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2915 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2916 $mday, $months[$mon], $hour ,$min;
2917 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2918 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2920 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2921 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2922 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2923 $date{'hour_local'} = $hour;
2924 $date{'minute_local'} = $min;
2925 $date{'tz_local'} = $tz;
2926 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2927 1900+$year, $mon+1, $mday,
2928 $hour, $min, $sec, $tz);
2929 return %date;
2932 sub parse_tag {
2933 my $tag_id = shift;
2934 my %tag;
2935 my @comment;
2937 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2938 $tag{'id'} = $tag_id;
2939 while (my $line = <$fd>) {
2940 chomp $line;
2941 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2942 $tag{'object'} = $1;
2943 } elsif ($line =~ m/^type (.+)$/) {
2944 $tag{'type'} = $1;
2945 } elsif ($line =~ m/^tag (.+)$/) {
2946 $tag{'name'} = $1;
2947 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2948 $tag{'author'} = $1;
2949 $tag{'author_epoch'} = $2;
2950 $tag{'author_tz'} = $3;
2951 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2952 $tag{'author_name'} = $1;
2953 $tag{'author_email'} = $2;
2954 } else {
2955 $tag{'author_name'} = $tag{'author'};
2957 } elsif ($line =~ m/--BEGIN/) {
2958 push @comment, $line;
2959 last;
2960 } elsif ($line eq "") {
2961 last;
2964 push @comment, <$fd>;
2965 $tag{'comment'} = \@comment;
2966 close $fd or return;
2967 if (!defined $tag{'name'}) {
2968 return
2970 return %tag
2973 sub parse_commit_text {
2974 my ($commit_text, $withparents) = @_;
2975 my @commit_lines = split '\n', $commit_text;
2976 my %co;
2978 pop @commit_lines; # Remove '\0'
2980 if (! @commit_lines) {
2981 return;
2984 my $header = shift @commit_lines;
2985 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2986 return;
2988 ($co{'id'}, my @parents) = split ' ', $header;
2989 while (my $line = shift @commit_lines) {
2990 last if $line eq "\n";
2991 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2992 $co{'tree'} = $1;
2993 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2994 push @parents, $1;
2995 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2996 $co{'author'} = to_utf8($1);
2997 $co{'author_epoch'} = $2;
2998 $co{'author_tz'} = $3;
2999 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3000 $co{'author_name'} = $1;
3001 $co{'author_email'} = $2;
3002 } else {
3003 $co{'author_name'} = $co{'author'};
3005 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3006 $co{'committer'} = to_utf8($1);
3007 $co{'committer_epoch'} = $2;
3008 $co{'committer_tz'} = $3;
3009 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3010 $co{'committer_name'} = $1;
3011 $co{'committer_email'} = $2;
3012 } else {
3013 $co{'committer_name'} = $co{'committer'};
3017 if (!defined $co{'tree'}) {
3018 return;
3020 $co{'parents'} = \@parents;
3021 $co{'parent'} = $parents[0];
3023 foreach my $title (@commit_lines) {
3024 $title =~ s/^ //;
3025 if ($title ne "") {
3026 $co{'title'} = chop_str($title, 80, 5);
3027 # remove leading stuff of merges to make the interesting part visible
3028 if (length($title) > 50) {
3029 $title =~ s/^Automatic //;
3030 $title =~ s/^merge (of|with) /Merge ... /i;
3031 if (length($title) > 50) {
3032 $title =~ s/(http|rsync):\/\///;
3034 if (length($title) > 50) {
3035 $title =~ s/(master|www|rsync)\.//;
3037 if (length($title) > 50) {
3038 $title =~ s/kernel.org:?//;
3040 if (length($title) > 50) {
3041 $title =~ s/\/pub\/scm//;
3044 $co{'title_short'} = chop_str($title, 50, 5);
3045 last;
3048 if (! defined $co{'title'} || $co{'title'} eq "") {
3049 $co{'title'} = $co{'title_short'} = '(no commit message)';
3051 # remove added spaces
3052 foreach my $line (@commit_lines) {
3053 $line =~ s/^ //;
3055 $co{'comment'} = \@commit_lines;
3057 my $age = time - $co{'committer_epoch'};
3058 $co{'age'} = $age;
3059 $co{'age_string'} = age_string($age);
3060 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3061 if ($age > 60*60*24*7*2) {
3062 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3063 $co{'age_string_age'} = $co{'age_string'};
3064 } else {
3065 $co{'age_string_date'} = $co{'age_string'};
3066 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3068 return %co;
3071 sub parse_commit {
3072 my ($commit_id) = @_;
3073 my %co;
3075 local $/ = "\0";
3077 open my $fd, "-|", git_cmd(), "rev-list",
3078 "--parents",
3079 "--header",
3080 "--max-count=1",
3081 $commit_id,
3082 "--",
3083 or die_error(500, "Open git-rev-list failed");
3084 %co = parse_commit_text(<$fd>, 1);
3085 close $fd;
3087 return %co;
3090 sub parse_commits {
3091 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3092 my @cos;
3094 $maxcount ||= 1;
3095 $skip ||= 0;
3097 local $/ = "\0";
3099 open my $fd, "-|", git_cmd(), "rev-list",
3100 "--header",
3101 @args,
3102 ("--max-count=" . $maxcount),
3103 ("--skip=" . $skip),
3104 @extra_options,
3105 $commit_id,
3106 "--",
3107 ($filename ? ($filename) : ())
3108 or die_error(500, "Open git-rev-list failed");
3109 while (my $line = <$fd>) {
3110 my %co = parse_commit_text($line);
3111 push @cos, \%co;
3113 close $fd;
3115 return wantarray ? @cos : \@cos;
3118 # parse line of git-diff-tree "raw" output
3119 sub parse_difftree_raw_line {
3120 my $line = shift;
3121 my %res;
3123 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3124 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3125 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3126 $res{'from_mode'} = $1;
3127 $res{'to_mode'} = $2;
3128 $res{'from_id'} = $3;
3129 $res{'to_id'} = $4;
3130 $res{'status'} = $5;
3131 $res{'similarity'} = $6;
3132 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3133 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3134 } else {
3135 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3138 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3139 # combined diff (for merge commit)
3140 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3141 $res{'nparents'} = length($1);
3142 $res{'from_mode'} = [ split(' ', $2) ];
3143 $res{'to_mode'} = pop @{$res{'from_mode'}};
3144 $res{'from_id'} = [ split(' ', $3) ];
3145 $res{'to_id'} = pop @{$res{'from_id'}};
3146 $res{'status'} = [ split('', $4) ];
3147 $res{'to_file'} = unquote($5);
3149 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3150 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3151 $res{'commit'} = $1;
3154 return wantarray ? %res : \%res;
3157 # wrapper: return parsed line of git-diff-tree "raw" output
3158 # (the argument might be raw line, or parsed info)
3159 sub parsed_difftree_line {
3160 my $line_or_ref = shift;
3162 if (ref($line_or_ref) eq "HASH") {
3163 # pre-parsed (or generated by hand)
3164 return $line_or_ref;
3165 } else {
3166 return parse_difftree_raw_line($line_or_ref);
3170 # parse line of git-ls-tree output
3171 sub parse_ls_tree_line {
3172 my $line = shift;
3173 my %opts = @_;
3174 my %res;
3176 if ($opts{'-l'}) {
3177 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3178 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3180 $res{'mode'} = $1;
3181 $res{'type'} = $2;
3182 $res{'hash'} = $3;
3183 $res{'size'} = $4;
3184 if ($opts{'-z'}) {
3185 $res{'name'} = $5;
3186 } else {
3187 $res{'name'} = unquote($5);
3189 } else {
3190 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3191 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3193 $res{'mode'} = $1;
3194 $res{'type'} = $2;
3195 $res{'hash'} = $3;
3196 if ($opts{'-z'}) {
3197 $res{'name'} = $4;
3198 } else {
3199 $res{'name'} = unquote($4);
3203 return wantarray ? %res : \%res;
3206 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3207 sub parse_from_to_diffinfo {
3208 my ($diffinfo, $from, $to, @parents) = @_;
3210 if ($diffinfo->{'nparents'}) {
3211 # combined diff
3212 $from->{'file'} = [];
3213 $from->{'href'} = [];
3214 fill_from_file_info($diffinfo, @parents)
3215 unless exists $diffinfo->{'from_file'};
3216 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3217 $from->{'file'}[$i] =
3218 defined $diffinfo->{'from_file'}[$i] ?
3219 $diffinfo->{'from_file'}[$i] :
3220 $diffinfo->{'to_file'};
3221 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3222 $from->{'href'}[$i] = href(action=>"blob",
3223 hash_base=>$parents[$i],
3224 hash=>$diffinfo->{'from_id'}[$i],
3225 file_name=>$from->{'file'}[$i]);
3226 } else {
3227 $from->{'href'}[$i] = undef;
3230 } else {
3231 # ordinary (not combined) diff
3232 $from->{'file'} = $diffinfo->{'from_file'};
3233 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3234 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3235 hash=>$diffinfo->{'from_id'},
3236 file_name=>$from->{'file'});
3237 } else {
3238 delete $from->{'href'};
3242 $to->{'file'} = $diffinfo->{'to_file'};
3243 if (!is_deleted($diffinfo)) { # file exists in result
3244 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3245 hash=>$diffinfo->{'to_id'},
3246 file_name=>$to->{'file'});
3247 } else {
3248 delete $to->{'href'};
3252 ## ......................................................................
3253 ## parse to array of hashes functions
3255 sub git_get_heads_list {
3256 my $limit = shift;
3257 my @headslist;
3259 open my $fd, '-|', git_cmd(), 'for-each-ref',
3260 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3261 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3262 'refs/heads'
3263 or return;
3264 while (my $line = <$fd>) {
3265 my %ref_item;
3267 chomp $line;
3268 my ($refinfo, $committerinfo) = split(/\0/, $line);
3269 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3270 my ($committer, $epoch, $tz) =
3271 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3272 $ref_item{'fullname'} = $name;
3273 $name =~ s!^refs/heads/!!;
3275 $ref_item{'name'} = $name;
3276 $ref_item{'id'} = $hash;
3277 $ref_item{'title'} = $title || '(no commit message)';
3278 $ref_item{'epoch'} = $epoch;
3279 if ($epoch) {
3280 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3281 } else {
3282 $ref_item{'age'} = "unknown";
3285 push @headslist, \%ref_item;
3287 close $fd;
3289 return wantarray ? @headslist : \@headslist;
3292 sub git_get_tags_list {
3293 my $limit = shift;
3294 my @tagslist;
3296 open my $fd, '-|', git_cmd(), 'for-each-ref',
3297 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3298 '--format=%(objectname) %(objecttype) %(refname) '.
3299 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3300 'refs/tags'
3301 or return;
3302 while (my $line = <$fd>) {
3303 my %ref_item;
3305 chomp $line;
3306 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3307 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3308 my ($creator, $epoch, $tz) =
3309 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3310 $ref_item{'fullname'} = $name;
3311 $name =~ s!^refs/tags/!!;
3313 $ref_item{'type'} = $type;
3314 $ref_item{'id'} = $id;
3315 $ref_item{'name'} = $name;
3316 if ($type eq "tag") {
3317 $ref_item{'subject'} = $title;
3318 $ref_item{'reftype'} = $reftype;
3319 $ref_item{'refid'} = $refid;
3320 } else {
3321 $ref_item{'reftype'} = $type;
3322 $ref_item{'refid'} = $id;
3325 if ($type eq "tag" || $type eq "commit") {
3326 $ref_item{'epoch'} = $epoch;
3327 if ($epoch) {
3328 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3329 } else {
3330 $ref_item{'age'} = "unknown";
3334 push @tagslist, \%ref_item;
3336 close $fd;
3338 return wantarray ? @tagslist : \@tagslist;
3341 ## ----------------------------------------------------------------------
3342 ## filesystem-related functions
3344 sub get_file_owner {
3345 my $path = shift;
3347 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3348 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3349 if (!defined $gcos) {
3350 return undef;
3352 my $owner = $gcos;
3353 $owner =~ s/[,;].*$//;
3354 return to_utf8($owner);
3357 # assume that file exists
3358 sub insert_file {
3359 my $filename = shift;
3361 open my $fd, '<', $filename;
3362 print map { to_utf8($_) } <$fd>;
3363 close $fd;
3366 ## ......................................................................
3367 ## mimetype related functions
3369 sub mimetype_guess_file {
3370 my $filename = shift;
3371 my $mimemap = shift;
3372 -r $mimemap or return undef;
3374 my %mimemap;
3375 open(my $mh, '<', $mimemap) or return undef;
3376 while (<$mh>) {
3377 next if m/^#/; # skip comments
3378 my ($mimetype, $exts) = split(/\t+/);
3379 if (defined $exts) {
3380 my @exts = split(/\s+/, $exts);
3381 foreach my $ext (@exts) {
3382 $mimemap{$ext} = $mimetype;
3386 close($mh);
3388 $filename =~ /\.([^.]*)$/;
3389 return $mimemap{$1};
3392 sub mimetype_guess {
3393 my $filename = shift;
3394 my $mime;
3395 $filename =~ /\./ or return undef;
3397 if ($mimetypes_file) {
3398 my $file = $mimetypes_file;
3399 if ($file !~ m!^/!) { # if it is relative path
3400 # it is relative to project
3401 $file = "$projectroot/$project/$file";
3403 $mime = mimetype_guess_file($filename, $file);
3405 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3406 return $mime;
3409 sub blob_mimetype {
3410 my $fd = shift;
3411 my $filename = shift;
3413 if ($filename) {
3414 my $mime = mimetype_guess($filename);
3415 $mime and return $mime;
3418 # just in case
3419 return $default_blob_plain_mimetype unless $fd;
3421 if (-T $fd) {
3422 return 'text/plain';
3423 } elsif (! $filename) {
3424 return 'application/octet-stream';
3425 } elsif ($filename =~ m/\.png$/i) {
3426 return 'image/png';
3427 } elsif ($filename =~ m/\.gif$/i) {
3428 return 'image/gif';
3429 } elsif ($filename =~ m/\.jpe?g$/i) {
3430 return 'image/jpeg';
3431 } else {
3432 return 'application/octet-stream';
3436 sub blob_contenttype {
3437 my ($fd, $file_name, $type) = @_;
3439 $type ||= blob_mimetype($fd, $file_name);
3440 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3441 $type .= "; charset=$default_text_plain_charset";
3444 return $type;
3447 # guess file syntax for syntax highlighting; return undef if no highlighting
3448 # the name of syntax can (in the future) depend on syntax highlighter used
3449 sub guess_file_syntax {
3450 my ($highlight, $mimetype, $file_name) = @_;
3451 return undef unless ($highlight && defined $file_name);
3452 my $basename = basename($file_name, '.in');
3453 return $highlight_basename{$basename}
3454 if exists $highlight_basename{$basename};
3456 $basename =~ /\.([^.]*)$/;
3457 my $ext = $1 or return undef;
3458 return $highlight_ext{$ext}
3459 if exists $highlight_ext{$ext};
3461 return undef;
3464 # run highlighter and return FD of its output,
3465 # or return original FD if no highlighting
3466 sub run_highlighter {
3467 my ($fd, $highlight, $syntax) = @_;
3468 return $fd unless ($highlight && defined $syntax);
3470 close $fd
3471 or die_error(404, "Reading blob failed");
3472 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3473 quote_command($highlight_bin).
3474 " --xhtml --fragment --syntax $syntax |"
3475 or die_error(500, "Couldn't open file or run syntax highlighter");
3476 return $fd;
3479 ## ======================================================================
3480 ## functions printing HTML: header, footer, error page
3482 sub get_page_title {
3483 my $title = to_utf8($site_name);
3485 return $title unless (defined $project);
3486 $title .= " - " . to_utf8($project);
3488 return $title unless (defined $action);
3489 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3491 return $title unless (defined $file_name);
3492 $title .= " - " . esc_path($file_name);
3493 if ($action eq "tree" && $file_name !~ m|/$|) {
3494 $title .= "/";
3497 return $title;
3500 sub git_header_html {
3501 my $status = shift || "200 OK";
3502 my $expires = shift;
3503 my %opts = @_;
3505 my $title = get_page_title();
3506 my $content_type;
3507 # require explicit support from the UA if we are to send the page as
3508 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3509 # we have to do this because MSIE sometimes globs '*/*', pretending to
3510 # support xhtml+xml but choking when it gets what it asked for.
3511 # Disable content-type negotiation when caching (use mimetype good for all).
3512 if (!$caching_enabled &&
3513 defined $cgi->http('HTTP_ACCEPT') &&
3514 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3515 $cgi->Accept('application/xhtml+xml') != 0) {
3516 $content_type = 'application/xhtml+xml';
3517 } else {
3518 $content_type = 'text/html';
3520 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3521 -status=> $status, -expires => $expires)
3522 unless ($opts{'-no_http_header'});
3523 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3524 print <<EOF;
3525 <?xml version="1.0" encoding="utf-8"?>
3526 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3527 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3528 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3529 <!-- git core binaries version $git_version -->
3530 <head>
3531 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3532 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3533 <meta name="robots" content="index, nofollow"/>
3534 <title>$title</title>
3536 # the stylesheet, favicon etc urls won't work correctly with path_info
3537 # unless we set the appropriate base URL
3538 # if caching is enabled we can get it from cache for path_info when it
3539 # is generated without path_info
3540 if ($ENV{'PATH_INFO'} || $caching_enabled) {
3541 print "<base href=\"".esc_url($base_url)."\" />\n";
3543 # print out each stylesheet that exist, providing backwards capability
3544 # for those people who defined $stylesheet in a config file
3545 if (defined $stylesheet) {
3546 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3547 } else {
3548 foreach my $stylesheet (@stylesheets) {
3549 next unless $stylesheet;
3550 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3553 if (defined $project) {
3554 my %href_params = get_feed_info();
3555 if (!exists $href_params{'-title'}) {
3556 $href_params{'-title'} = 'log';
3559 foreach my $format qw(RSS Atom) {
3560 my $type = lc($format);
3561 my %link_attr = (
3562 '-rel' => 'alternate',
3563 '-title' => "$project - $href_params{'-title'} - $format feed",
3564 '-type' => "application/$type+xml"
3567 $href_params{'action'} = $type;
3568 $link_attr{'-href'} = href(%href_params);
3569 print "<link ".
3570 "rel=\"$link_attr{'-rel'}\" ".
3571 "title=\"$link_attr{'-title'}\" ".
3572 "href=\"$link_attr{'-href'}\" ".
3573 "type=\"$link_attr{'-type'}\" ".
3574 "/>\n";
3576 $href_params{'extra_options'} = '--no-merges';
3577 $link_attr{'-href'} = href(%href_params);
3578 $link_attr{'-title'} .= ' (no merges)';
3579 print "<link ".
3580 "rel=\"$link_attr{'-rel'}\" ".
3581 "title=\"$link_attr{'-title'}\" ".
3582 "href=\"$link_attr{'-href'}\" ".
3583 "type=\"$link_attr{'-type'}\" ".
3584 "/>\n";
3587 } else {
3588 printf('<link rel="alternate" title="%s projects list" '.
3589 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3590 $site_name, href(project=>undef, action=>"project_index"));
3591 printf('<link rel="alternate" title="%s projects feeds" '.
3592 'href="%s" type="text/x-opml" />'."\n",
3593 $site_name, href(project=>undef, action=>"opml"));
3595 if (defined $favicon) {
3596 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3599 print "</head>\n" .
3600 "<body>\n";
3602 if (defined $site_header && -f $site_header) {
3603 insert_file($site_header);
3606 print "<div class=\"page_header\">\n" .
3607 $cgi->a({-href => esc_url($logo_url),
3608 -title => $logo_label},
3609 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3610 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3611 if (defined $project) {
3612 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3613 if (defined $action) {
3614 print " / $action";
3616 print "\n";
3618 print "</div>\n";
3620 my $have_search = gitweb_check_feature('search');
3621 if (defined $project && $have_search) {
3622 if (!defined $searchtext) {
3623 $searchtext = "";
3625 my $search_hash;
3626 if (defined $hash_base) {
3627 $search_hash = $hash_base;
3628 } elsif (defined $hash) {
3629 $search_hash = $hash;
3630 } else {
3631 $search_hash = "HEAD";
3633 my $action = $my_uri;
3634 my $use_pathinfo = gitweb_check_feature('pathinfo');
3635 if ($use_pathinfo) {
3636 $action .= "/".esc_url($project);
3638 print $cgi->startform(-method => "get", -action => $action) .
3639 "<div class=\"search\">\n" .
3640 (!$use_pathinfo &&
3641 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3642 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3643 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3644 $cgi->popup_menu(-name => 'st', -default => 'commit',
3645 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3646 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3647 " search:\n",
3648 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3649 "<span title=\"Extended regular expression\">" .
3650 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3651 -checked => $search_use_regexp) .
3652 "</span>" .
3653 "</div>" .
3654 $cgi->end_form() . "\n";
3658 sub git_footer_html {
3659 my $feed_class = 'rss_logo';
3661 print "<div class=\"page_footer\">\n";
3662 if (defined $project) {
3663 my $descr = git_get_project_description($project);
3664 if (defined $descr) {
3665 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3668 my %href_params = get_feed_info();
3669 if (!%href_params) {
3670 $feed_class .= ' generic';
3672 $href_params{'-title'} ||= 'log';
3674 foreach my $format qw(RSS Atom) {
3675 $href_params{'action'} = lc($format);
3676 print $cgi->a({-href => href(%href_params),
3677 -title => "$href_params{'-title'} $format feed",
3678 -class => $feed_class}, $format)."\n";
3681 } else {
3682 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3683 -class => $feed_class}, "OPML") . " ";
3684 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3685 -class => $feed_class}, "TXT") . "\n";
3687 print "</div>\n"; # class="page_footer"
3689 # timing info doesn't make much sense with output (response) caching,
3690 # so when caching is enabled gitweb prints the time of page generation
3691 if ((defined $t0 || $caching_enabled) &&
3692 gitweb_check_feature('timed')) {
3693 print "<div id=\"generating_info\">\n";
3694 if ($caching_enabled) {
3695 print 'This page was generated at '.
3696 gmtime( time() )." GMT\n";
3697 } else {
3698 print 'This page took '.
3699 '<span id="generating_time" class="time_span">'.
3700 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3701 ' seconds </span>'.
3702 ' and '.
3703 '<span id="generating_cmd">'.
3704 $number_of_git_cmds.
3705 '</span> git commands '.
3706 " to generate.\n";
3708 print "</div>\n"; # class="page_footer"
3711 if (defined $site_footer && -f $site_footer) {
3712 insert_file($site_footer);
3715 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3716 if (!$caching_enabled &&
3717 defined $action && $action eq 'blame_incremental') {
3718 print qq!<script type="text/javascript">\n!.
3719 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3720 qq! "!. href() .qq!");\n!.
3721 qq!</script>\n!;
3722 } elsif (gitweb_check_feature('javascript-actions')) {
3723 print qq!<script type="text/javascript">\n!.
3724 qq!window.onload = fixLinks;\n!.
3725 qq!</script>\n!;
3728 print "</body>\n" .
3729 "</html>";
3732 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3733 # Example: die_error(404, 'Hash not found')
3734 # By convention, use the following status codes (as defined in RFC 2616):
3735 # 400: Invalid or missing CGI parameters, or
3736 # requested object exists but has wrong type.
3737 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3738 # this server or project.
3739 # 404: Requested object/revision/project doesn't exist.
3740 # 500: The server isn't configured properly, or
3741 # an internal error occurred (e.g. failed assertions caused by bugs), or
3742 # an unknown error occurred (e.g. the git binary died unexpectedly).
3743 # 503: The server is currently unavailable (because it is overloaded,
3744 # or down for maintenance). Generally, this is a temporary state.
3745 sub die_error {
3746 my $status = shift || 500;
3747 my $error = esc_html(shift) || "Internal Server Error";
3748 my $extra = shift;
3749 my %opts = @_;
3751 my %http_responses = (
3752 400 => '400 Bad Request',
3753 403 => '403 Forbidden',
3754 404 => '404 Not Found',
3755 500 => '500 Internal Server Error',
3756 503 => '503 Service Unavailable',
3759 # Do not cache error pages
3760 capture_stop($cache, $capture) if ($capture && $caching_enabled);
3762 git_header_html($http_responses{$status}, undef, %opts);
3763 print <<EOF;
3764 <div class="page_body">
3765 <br /><br />
3766 $status - $error
3767 <br />
3769 if (defined $extra) {
3770 print "<hr />\n" .
3771 "$extra\n";
3773 print "</div>\n";
3775 git_footer_html();
3776 goto DONE_GITWEB
3777 unless ($opts{'-error_handler'});
3780 ## ----------------------------------------------------------------------
3781 ## functions printing or outputting HTML: navigation
3783 sub git_print_page_nav {
3784 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3785 $extra = '' if !defined $extra; # pager or formats
3787 my @navs = qw(summary shortlog log commit commitdiff tree);
3788 if ($suppress) {
3789 @navs = grep { $_ ne $suppress } @navs;
3792 my %arg = map { $_ => {action=>$_} } @navs;
3793 if (defined $head) {
3794 for (qw(commit commitdiff)) {
3795 $arg{$_}{'hash'} = $head;
3797 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3798 for (qw(shortlog log)) {
3799 $arg{$_}{'hash'} = $head;
3804 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3805 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3807 my @actions = gitweb_get_feature('actions');
3808 my %repl = (
3809 '%' => '%',
3810 'n' => $project, # project name
3811 'f' => $git_dir, # project path within filesystem
3812 'h' => $treehead || '', # current hash ('h' parameter)
3813 'b' => $treebase || '', # hash base ('hb' parameter)
3815 while (@actions) {
3816 my ($label, $link, $pos) = splice(@actions,0,3);
3817 # insert
3818 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3819 # munch munch
3820 $link =~ s/%([%nfhb])/$repl{$1}/g;
3821 $arg{$label}{'_href'} = $link;
3824 print "<div class=\"page_nav\">\n" .
3825 (join " | ",
3826 map { $_ eq $current ?
3827 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3828 } @navs);
3829 print "<br/>\n$extra<br/>\n" .
3830 "</div>\n";
3833 sub format_paging_nav {
3834 my ($action, $page, $has_next_link) = @_;
3835 my $paging_nav;
3838 if ($page > 0) {
3839 $paging_nav .=
3840 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3841 " &sdot; " .
3842 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3843 -accesskey => "p", -title => "Alt-p"}, "prev");
3844 } else {
3845 $paging_nav .= "first &sdot; prev";
3848 if ($has_next_link) {
3849 $paging_nav .= " &sdot; " .
3850 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3851 -accesskey => "n", -title => "Alt-n"}, "next");
3852 } else {
3853 $paging_nav .= " &sdot; next";
3856 return $paging_nav;
3859 ## ......................................................................
3860 ## functions printing or outputting HTML: div
3862 sub git_print_header_div {
3863 my ($action, $title, $hash, $hash_base) = @_;
3864 my %args = ();
3866 $args{'action'} = $action;
3867 $args{'hash'} = $hash if $hash;
3868 $args{'hash_base'} = $hash_base if $hash_base;
3870 print "<div class=\"header\">\n" .
3871 $cgi->a({-href => href(%args), -class => "title"},
3872 $title ? $title : $action) .
3873 "\n</div>\n";
3876 sub print_local_time {
3877 print format_local_time(@_);
3880 sub format_local_time {
3881 my $localtime = '';
3882 my %date = @_;
3883 if ($date{'hour_local'} < 6) {
3884 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3885 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3886 } else {
3887 $localtime .= sprintf(" (%02d:%02d %s)",
3888 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3891 return $localtime;
3894 # Outputs the author name and date in long form
3895 sub git_print_authorship {
3896 my $co = shift;
3897 my %opts = @_;
3898 my $tag = $opts{-tag} || 'div';
3899 my $author = $co->{'author_name'};
3901 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3902 print "<$tag class=\"author_date\">" .
3903 format_search_author($author, "author", esc_html($author)) .
3904 " [$ad{'rfc2822'}";
3905 print_local_time(%ad) if ($opts{-localtime});
3906 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3907 . "</$tag>\n";
3910 # Outputs table rows containing the full author or committer information,
3911 # in the format expected for 'commit' view (& similar).
3912 # Parameters are a commit hash reference, followed by the list of people
3913 # to output information for. If the list is empty it defaults to both
3914 # author and committer.
3915 sub git_print_authorship_rows {
3916 my $co = shift;
3917 # too bad we can't use @people = @_ || ('author', 'committer')
3918 my @people = @_;
3919 @people = ('author', 'committer') unless @people;
3920 foreach my $who (@people) {
3921 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3922 print "<tr><td>$who</td><td>" .
3923 format_search_author($co->{"${who}_name"}, $who,
3924 esc_html($co->{"${who}_name"})) . " " .
3925 format_search_author($co->{"${who}_email"}, $who,
3926 esc_html("<" . $co->{"${who}_email"} . ">")) .
3927 "</td><td rowspan=\"2\">" .
3928 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3929 "</td></tr>\n" .
3930 "<tr>" .
3931 "<td></td><td> $wd{'rfc2822'}";
3932 print_local_time(%wd);
3933 print "</td>" .
3934 "</tr>\n";
3938 sub git_print_page_path {
3939 my $name = shift;
3940 my $type = shift;
3941 my $hb = shift;
3944 print "<div class=\"page_path\">";
3945 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3946 -title => 'tree root'}, to_utf8("[$project]"));
3947 print " / ";
3948 if (defined $name) {
3949 my @dirname = split '/', $name;
3950 my $basename = pop @dirname;
3951 my $fullname = '';
3953 foreach my $dir (@dirname) {
3954 $fullname .= ($fullname ? '/' : '') . $dir;
3955 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3956 hash_base=>$hb),
3957 -title => $fullname}, esc_path($dir));
3958 print " / ";
3960 if (defined $type && $type eq 'blob') {
3961 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3962 hash_base=>$hb),
3963 -title => $name}, esc_path($basename));
3964 } elsif (defined $type && $type eq 'tree') {
3965 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3966 hash_base=>$hb),
3967 -title => $name}, esc_path($basename));
3968 print " / ";
3969 } else {
3970 print esc_path($basename);
3973 print "<br/></div>\n";
3976 sub git_print_log {
3977 my $log = shift;
3978 my %opts = @_;
3980 if ($opts{'-remove_title'}) {
3981 # remove title, i.e. first line of log
3982 shift @$log;
3984 # remove leading empty lines
3985 while (defined $log->[0] && $log->[0] eq "") {
3986 shift @$log;
3989 # print log
3990 my $signoff = 0;
3991 my $empty = 0;
3992 foreach my $line (@$log) {
3993 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3994 $signoff = 1;
3995 $empty = 0;
3996 if (! $opts{'-remove_signoff'}) {
3997 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3998 next;
3999 } else {
4000 # remove signoff lines
4001 next;
4003 } else {
4004 $signoff = 0;
4007 # print only one empty line
4008 # do not print empty line after signoff
4009 if ($line eq "") {
4010 next if ($empty || $signoff);
4011 $empty = 1;
4012 } else {
4013 $empty = 0;
4016 print format_log_line_html($line) . "<br/>\n";
4019 if ($opts{'-final_empty_line'}) {
4020 # end with single empty line
4021 print "<br/>\n" unless $empty;
4025 # return link target (what link points to)
4026 sub git_get_link_target {
4027 my $hash = shift;
4028 my $link_target;
4030 # read link
4031 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4032 or return;
4034 local $/ = undef;
4035 $link_target = <$fd>;
4037 close $fd
4038 or return;
4040 return $link_target;
4043 # given link target, and the directory (basedir) the link is in,
4044 # return target of link relative to top directory (top tree);
4045 # return undef if it is not possible (including absolute links).
4046 sub normalize_link_target {
4047 my ($link_target, $basedir) = @_;
4049 # absolute symlinks (beginning with '/') cannot be normalized
4050 return if (substr($link_target, 0, 1) eq '/');
4052 # normalize link target to path from top (root) tree (dir)
4053 my $path;
4054 if ($basedir) {
4055 $path = $basedir . '/' . $link_target;
4056 } else {
4057 # we are in top (root) tree (dir)
4058 $path = $link_target;
4061 # remove //, /./, and /../
4062 my @path_parts;
4063 foreach my $part (split('/', $path)) {
4064 # discard '.' and ''
4065 next if (!$part || $part eq '.');
4066 # handle '..'
4067 if ($part eq '..') {
4068 if (@path_parts) {
4069 pop @path_parts;
4070 } else {
4071 # link leads outside repository (outside top dir)
4072 return;
4074 } else {
4075 push @path_parts, $part;
4078 $path = join('/', @path_parts);
4080 return $path;
4083 # print tree entry (row of git_tree), but without encompassing <tr> element
4084 sub git_print_tree_entry {
4085 my ($t, $basedir, $hash_base, $have_blame) = @_;
4087 my %base_key = ();
4088 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4090 # The format of a table row is: mode list link. Where mode is
4091 # the mode of the entry, list is the name of the entry, an href,
4092 # and link is the action links of the entry.
4094 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4095 if (exists $t->{'size'}) {
4096 print "<td class=\"size\">$t->{'size'}</td>\n";
4098 if ($t->{'type'} eq "blob") {
4099 print "<td class=\"list\">" .
4100 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4101 file_name=>"$basedir$t->{'name'}", %base_key),
4102 -class => "list"}, esc_path($t->{'name'}));
4103 if (S_ISLNK(oct $t->{'mode'})) {
4104 my $link_target = git_get_link_target($t->{'hash'});
4105 if ($link_target) {
4106 my $norm_target = normalize_link_target($link_target, $basedir);
4107 if (defined $norm_target) {
4108 print " -> " .
4109 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4110 file_name=>$norm_target),
4111 -title => $norm_target}, esc_path($link_target));
4112 } else {
4113 print " -> " . esc_path($link_target);
4117 print "</td>\n";
4118 print "<td class=\"link\">";
4119 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4120 file_name=>"$basedir$t->{'name'}", %base_key)},
4121 "blob");
4122 if ($have_blame) {
4123 print " | " .
4124 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4125 file_name=>"$basedir$t->{'name'}", %base_key)},
4126 "blame");
4128 if (defined $hash_base) {
4129 print " | " .
4130 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4131 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4132 "history");
4134 print " | " .
4135 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4136 file_name=>"$basedir$t->{'name'}")},
4137 "raw");
4138 print "</td>\n";
4140 } elsif ($t->{'type'} eq "tree") {
4141 print "<td class=\"list\">";
4142 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4143 file_name=>"$basedir$t->{'name'}",
4144 %base_key)},
4145 esc_path($t->{'name'}));
4146 print "</td>\n";
4147 print "<td class=\"link\">";
4148 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4149 file_name=>"$basedir$t->{'name'}",
4150 %base_key)},
4151 "tree");
4152 if (defined $hash_base) {
4153 print " | " .
4154 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4155 file_name=>"$basedir$t->{'name'}")},
4156 "history");
4158 print "</td>\n";
4159 } else {
4160 # unknown object: we can only present history for it
4161 # (this includes 'commit' object, i.e. submodule support)
4162 print "<td class=\"list\">" .
4163 esc_path($t->{'name'}) .
4164 "</td>\n";
4165 print "<td class=\"link\">";
4166 if (defined $hash_base) {
4167 print $cgi->a({-href => href(action=>"history",
4168 hash_base=>$hash_base,
4169 file_name=>"$basedir$t->{'name'}")},
4170 "history");
4172 print "</td>\n";
4176 ## ......................................................................
4177 ## functions printing large fragments of HTML
4179 # get pre-image filenames for merge (combined) diff
4180 sub fill_from_file_info {
4181 my ($diff, @parents) = @_;
4183 $diff->{'from_file'} = [ ];
4184 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4185 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4186 if ($diff->{'status'}[$i] eq 'R' ||
4187 $diff->{'status'}[$i] eq 'C') {
4188 $diff->{'from_file'}[$i] =
4189 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4193 return $diff;
4196 # is current raw difftree line of file deletion
4197 sub is_deleted {
4198 my $diffinfo = shift;
4200 return $diffinfo->{'to_id'} eq ('0' x 40);
4203 # does patch correspond to [previous] difftree raw line
4204 # $diffinfo - hashref of parsed raw diff format
4205 # $patchinfo - hashref of parsed patch diff format
4206 # (the same keys as in $diffinfo)
4207 sub is_patch_split {
4208 my ($diffinfo, $patchinfo) = @_;
4210 return defined $diffinfo && defined $patchinfo
4211 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4215 sub git_difftree_body {
4216 my ($difftree, $hash, @parents) = @_;
4217 my ($parent) = $parents[0];
4218 my $have_blame = gitweb_check_feature('blame');
4219 print "<div class=\"list_head\">\n";
4220 if ($#{$difftree} > 10) {
4221 print(($#{$difftree} + 1) . " files changed:\n");
4223 print "</div>\n";
4225 print "<table class=\"" .
4226 (@parents > 1 ? "combined " : "") .
4227 "diff_tree\">\n";
4229 # header only for combined diff in 'commitdiff' view
4230 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4231 if ($has_header) {
4232 # table header
4233 print "<thead><tr>\n" .
4234 "<th></th><th></th>\n"; # filename, patchN link
4235 for (my $i = 0; $i < @parents; $i++) {
4236 my $par = $parents[$i];
4237 print "<th>" .
4238 $cgi->a({-href => href(action=>"commitdiff",
4239 hash=>$hash, hash_parent=>$par),
4240 -title => 'commitdiff to parent number ' .
4241 ($i+1) . ': ' . substr($par,0,7)},
4242 $i+1) .
4243 "&nbsp;</th>\n";
4245 print "</tr></thead>\n<tbody>\n";
4248 my $alternate = 1;
4249 my $patchno = 0;
4250 foreach my $line (@{$difftree}) {
4251 my $diff = parsed_difftree_line($line);
4253 if ($alternate) {
4254 print "<tr class=\"dark\">\n";
4255 } else {
4256 print "<tr class=\"light\">\n";
4258 $alternate ^= 1;
4260 if (exists $diff->{'nparents'}) { # combined diff
4262 fill_from_file_info($diff, @parents)
4263 unless exists $diff->{'from_file'};
4265 if (!is_deleted($diff)) {
4266 # file exists in the result (child) commit
4267 print "<td>" .
4268 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4269 file_name=>$diff->{'to_file'},
4270 hash_base=>$hash),
4271 -class => "list"}, esc_path($diff->{'to_file'})) .
4272 "</td>\n";
4273 } else {
4274 print "<td>" .
4275 esc_path($diff->{'to_file'}) .
4276 "</td>\n";
4279 if ($action eq 'commitdiff') {
4280 # link to patch
4281 $patchno++;
4282 print "<td class=\"link\">" .
4283 $cgi->a({-href => "#patch$patchno"}, "patch") .
4284 " | " .
4285 "</td>\n";
4288 my $has_history = 0;
4289 my $not_deleted = 0;
4290 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4291 my $hash_parent = $parents[$i];
4292 my $from_hash = $diff->{'from_id'}[$i];
4293 my $from_path = $diff->{'from_file'}[$i];
4294 my $status = $diff->{'status'}[$i];
4296 $has_history ||= ($status ne 'A');
4297 $not_deleted ||= ($status ne 'D');
4299 if ($status eq 'A') {
4300 print "<td class=\"link\" align=\"right\"> | </td>\n";
4301 } elsif ($status eq 'D') {
4302 print "<td class=\"link\">" .
4303 $cgi->a({-href => href(action=>"blob",
4304 hash_base=>$hash,
4305 hash=>$from_hash,
4306 file_name=>$from_path)},
4307 "blob" . ($i+1)) .
4308 " | </td>\n";
4309 } else {
4310 if ($diff->{'to_id'} eq $from_hash) {
4311 print "<td class=\"link nochange\">";
4312 } else {
4313 print "<td class=\"link\">";
4315 print $cgi->a({-href => href(action=>"blobdiff",
4316 hash=>$diff->{'to_id'},
4317 hash_parent=>$from_hash,
4318 hash_base=>$hash,
4319 hash_parent_base=>$hash_parent,
4320 file_name=>$diff->{'to_file'},
4321 file_parent=>$from_path)},
4322 "diff" . ($i+1)) .
4323 " | </td>\n";
4327 print "<td class=\"link\">";
4328 if ($not_deleted) {
4329 print $cgi->a({-href => href(action=>"blob",
4330 hash=>$diff->{'to_id'},
4331 file_name=>$diff->{'to_file'},
4332 hash_base=>$hash)},
4333 "blob");
4334 print " | " if ($has_history);
4336 if ($has_history) {
4337 print $cgi->a({-href => href(action=>"history",
4338 file_name=>$diff->{'to_file'},
4339 hash_base=>$hash)},
4340 "history");
4342 print "</td>\n";
4344 print "</tr>\n";
4345 next; # instead of 'else' clause, to avoid extra indent
4347 # else ordinary diff
4349 my ($to_mode_oct, $to_mode_str, $to_file_type);
4350 my ($from_mode_oct, $from_mode_str, $from_file_type);
4351 if ($diff->{'to_mode'} ne ('0' x 6)) {
4352 $to_mode_oct = oct $diff->{'to_mode'};
4353 if (S_ISREG($to_mode_oct)) { # only for regular file
4354 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4356 $to_file_type = file_type($diff->{'to_mode'});
4358 if ($diff->{'from_mode'} ne ('0' x 6)) {
4359 $from_mode_oct = oct $diff->{'from_mode'};
4360 if (S_ISREG($to_mode_oct)) { # only for regular file
4361 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4363 $from_file_type = file_type($diff->{'from_mode'});
4366 if ($diff->{'status'} eq "A") { # created
4367 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4368 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4369 $mode_chng .= "]</span>";
4370 print "<td>";
4371 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4372 hash_base=>$hash, file_name=>$diff->{'file'}),
4373 -class => "list"}, esc_path($diff->{'file'}));
4374 print "</td>\n";
4375 print "<td>$mode_chng</td>\n";
4376 print "<td class=\"link\">";
4377 if ($action eq 'commitdiff') {
4378 # link to patch
4379 $patchno++;
4380 print $cgi->a({-href => "#patch$patchno"}, "patch");
4381 print " | ";
4383 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4384 hash_base=>$hash, file_name=>$diff->{'file'})},
4385 "blob");
4386 print "</td>\n";
4388 } elsif ($diff->{'status'} eq "D") { # deleted
4389 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4390 print "<td>";
4391 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4392 hash_base=>$parent, file_name=>$diff->{'file'}),
4393 -class => "list"}, esc_path($diff->{'file'}));
4394 print "</td>\n";
4395 print "<td>$mode_chng</td>\n";
4396 print "<td class=\"link\">";
4397 if ($action eq 'commitdiff') {
4398 # link to patch
4399 $patchno++;
4400 print $cgi->a({-href => "#patch$patchno"}, "patch");
4401 print " | ";
4403 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4404 hash_base=>$parent, file_name=>$diff->{'file'})},
4405 "blob") . " | ";
4406 if ($have_blame) {
4407 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4408 file_name=>$diff->{'file'})},
4409 "blame") . " | ";
4411 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4412 file_name=>$diff->{'file'})},
4413 "history");
4414 print "</td>\n";
4416 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4417 my $mode_chnge = "";
4418 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4419 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4420 if ($from_file_type ne $to_file_type) {
4421 $mode_chnge .= " from $from_file_type to $to_file_type";
4423 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4424 if ($from_mode_str && $to_mode_str) {
4425 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4426 } elsif ($to_mode_str) {
4427 $mode_chnge .= " mode: $to_mode_str";
4430 $mode_chnge .= "]</span>\n";
4432 print "<td>";
4433 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4434 hash_base=>$hash, file_name=>$diff->{'file'}),
4435 -class => "list"}, esc_path($diff->{'file'}));
4436 print "</td>\n";
4437 print "<td>$mode_chnge</td>\n";
4438 print "<td class=\"link\">";
4439 if ($action eq 'commitdiff') {
4440 # link to patch
4441 $patchno++;
4442 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4443 " | ";
4444 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4445 # "commit" view and modified file (not onlu mode changed)
4446 print $cgi->a({-href => href(action=>"blobdiff",
4447 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4448 hash_base=>$hash, hash_parent_base=>$parent,
4449 file_name=>$diff->{'file'})},
4450 "diff") .
4451 " | ";
4453 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4454 hash_base=>$hash, file_name=>$diff->{'file'})},
4455 "blob") . " | ";
4456 if ($have_blame) {
4457 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4458 file_name=>$diff->{'file'})},
4459 "blame") . " | ";
4461 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4462 file_name=>$diff->{'file'})},
4463 "history");
4464 print "</td>\n";
4466 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4467 my %status_name = ('R' => 'moved', 'C' => 'copied');
4468 my $nstatus = $status_name{$diff->{'status'}};
4469 my $mode_chng = "";
4470 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4471 # mode also for directories, so we cannot use $to_mode_str
4472 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4474 print "<td>" .
4475 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4476 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4477 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4478 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4479 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4480 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4481 -class => "list"}, esc_path($diff->{'from_file'})) .
4482 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4483 "<td class=\"link\">";
4484 if ($action eq 'commitdiff') {
4485 # link to patch
4486 $patchno++;
4487 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4488 " | ";
4489 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4490 # "commit" view and modified file (not only pure rename or copy)
4491 print $cgi->a({-href => href(action=>"blobdiff",
4492 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4493 hash_base=>$hash, hash_parent_base=>$parent,
4494 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4495 "diff") .
4496 " | ";
4498 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4499 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4500 "blob") . " | ";
4501 if ($have_blame) {
4502 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4503 file_name=>$diff->{'to_file'})},
4504 "blame") . " | ";
4506 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4507 file_name=>$diff->{'to_file'})},
4508 "history");
4509 print "</td>\n";
4511 } # we should not encounter Unmerged (U) or Unknown (X) status
4512 print "</tr>\n";
4514 print "</tbody>" if $has_header;
4515 print "</table>\n";
4518 sub git_patchset_body {
4519 my ($fd, $difftree, $hash, @hash_parents) = @_;
4520 my ($hash_parent) = $hash_parents[0];
4522 my $is_combined = (@hash_parents > 1);
4523 my $patch_idx = 0;
4524 my $patch_number = 0;
4525 my $patch_line;
4526 my $diffinfo;
4527 my $to_name;
4528 my (%from, %to);
4530 print "<div class=\"patchset\">\n";
4532 # skip to first patch
4533 while ($patch_line = <$fd>) {
4534 chomp $patch_line;
4536 last if ($patch_line =~ m/^diff /);
4539 PATCH:
4540 while ($patch_line) {
4542 # parse "git diff" header line
4543 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4544 # $1 is from_name, which we do not use
4545 $to_name = unquote($2);
4546 $to_name =~ s!^b/!!;
4547 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4548 # $1 is 'cc' or 'combined', which we do not use
4549 $to_name = unquote($2);
4550 } else {
4551 $to_name = undef;
4554 # check if current patch belong to current raw line
4555 # and parse raw git-diff line if needed
4556 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4557 # this is continuation of a split patch
4558 print "<div class=\"patch cont\">\n";
4559 } else {
4560 # advance raw git-diff output if needed
4561 $patch_idx++ if defined $diffinfo;
4563 # read and prepare patch information
4564 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4566 # compact combined diff output can have some patches skipped
4567 # find which patch (using pathname of result) we are at now;
4568 if ($is_combined) {
4569 while ($to_name ne $diffinfo->{'to_file'}) {
4570 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4571 format_diff_cc_simplified($diffinfo, @hash_parents) .
4572 "</div>\n"; # class="patch"
4574 $patch_idx++;
4575 $patch_number++;
4577 last if $patch_idx > $#$difftree;
4578 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4582 # modifies %from, %to hashes
4583 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4585 # this is first patch for raw difftree line with $patch_idx index
4586 # we index @$difftree array from 0, but number patches from 1
4587 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4590 # git diff header
4591 #assert($patch_line =~ m/^diff /) if DEBUG;
4592 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4593 $patch_number++;
4594 # print "git diff" header
4595 print format_git_diff_header_line($patch_line, $diffinfo,
4596 \%from, \%to);
4598 # print extended diff header
4599 print "<div class=\"diff extended_header\">\n";
4600 EXTENDED_HEADER:
4601 while ($patch_line = <$fd>) {
4602 chomp $patch_line;
4604 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4606 print format_extended_diff_header_line($patch_line, $diffinfo,
4607 \%from, \%to);
4609 print "</div>\n"; # class="diff extended_header"
4611 # from-file/to-file diff header
4612 if (! $patch_line) {
4613 print "</div>\n"; # class="patch"
4614 last PATCH;
4616 next PATCH if ($patch_line =~ m/^diff /);
4617 #assert($patch_line =~ m/^---/) if DEBUG;
4619 my $last_patch_line = $patch_line;
4620 $patch_line = <$fd>;
4621 chomp $patch_line;
4622 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4624 print format_diff_from_to_header($last_patch_line, $patch_line,
4625 $diffinfo, \%from, \%to,
4626 @hash_parents);
4628 # the patch itself
4629 LINE:
4630 while ($patch_line = <$fd>) {
4631 chomp $patch_line;
4633 next PATCH if ($patch_line =~ m/^diff /);
4635 print format_diff_line($patch_line, \%from, \%to);
4638 } continue {
4639 print "</div>\n"; # class="patch"
4642 # for compact combined (--cc) format, with chunk and patch simplification
4643 # the patchset might be empty, but there might be unprocessed raw lines
4644 for (++$patch_idx if $patch_number > 0;
4645 $patch_idx < @$difftree;
4646 ++$patch_idx) {
4647 # read and prepare patch information
4648 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4650 # generate anchor for "patch" links in difftree / whatchanged part
4651 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4652 format_diff_cc_simplified($diffinfo, @hash_parents) .
4653 "</div>\n"; # class="patch"
4655 $patch_number++;
4658 if ($patch_number == 0) {
4659 if (@hash_parents > 1) {
4660 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4661 } else {
4662 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4666 print "</div>\n"; # class="patchset"
4669 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4671 # fills project list info (age, description, owner, forks) for each
4672 # project in the list, removing invalid projects from returned list
4673 # NOTE: modifies $projlist, but does not remove entries from it
4674 sub fill_project_list_info {
4675 my ($projlist, $check_forks) = @_;
4676 my @projects;
4678 my $show_ctags = gitweb_check_feature('ctags');
4679 PROJECT:
4680 foreach my $pr (@$projlist) {
4681 my (@activity) = git_get_last_activity($pr->{'path'});
4682 unless (@activity) {
4683 next PROJECT;
4685 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4686 if (!defined $pr->{'descr'}) {
4687 my $descr = git_get_project_description($pr->{'path'}) || "";
4688 $descr = to_utf8($descr);
4689 $pr->{'descr_long'} = $descr;
4690 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4692 if (!defined $pr->{'owner'}) {
4693 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4695 if ($check_forks) {
4696 my $pname = $pr->{'path'};
4697 if (($pname =~ s/\.git$//) &&
4698 ($pname !~ /\/$/) &&
4699 (-d "$projectroot/$pname")) {
4700 $pr->{'forks'} = "-d $projectroot/$pname";
4701 } else {
4702 $pr->{'forks'} = 0;
4705 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4706 push @projects, $pr;
4709 return @projects;
4712 # print 'sort by' <th> element, generating 'sort by $name' replay link
4713 # if that order is not selected
4714 sub print_sort_th {
4715 print format_sort_th(@_);
4718 sub format_sort_th {
4719 my ($name, $order, $header) = @_;
4720 my $sort_th = "";
4721 $header ||= ucfirst($name);
4723 if ($order eq $name) {
4724 $sort_th .= "<th>$header</th>\n";
4725 } else {
4726 $sort_th .= "<th>" .
4727 $cgi->a({-href => href(-replay=>1, order=>$name),
4728 -class => "header"}, $header) .
4729 "</th>\n";
4732 return $sort_th;
4735 sub git_project_list_body {
4736 # actually uses global variable $project
4737 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4739 my $check_forks = gitweb_check_feature('forks');
4740 my @projects = fill_project_list_info($projlist, $check_forks);
4742 $order ||= $default_projects_order;
4743 $from = 0 unless defined $from;
4744 $to = $#projects if (!defined $to || $#projects < $to);
4746 my %order_info = (
4747 project => { key => 'path', type => 'str' },
4748 descr => { key => 'descr_long', type => 'str' },
4749 owner => { key => 'owner', type => 'str' },
4750 age => { key => 'age', type => 'num' }
4752 my $oi = $order_info{$order};
4753 if ($oi->{'type'} eq 'str') {
4754 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4755 } else {
4756 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4759 my $show_ctags = gitweb_check_feature('ctags');
4760 if ($show_ctags) {
4761 my %ctags;
4762 foreach my $p (@projects) {
4763 foreach my $ct (keys %{$p->{'ctags'}}) {
4764 $ctags{$ct} += $p->{'ctags'}->{$ct};
4767 my $cloud = git_populate_project_tagcloud(\%ctags);
4768 print git_show_project_tagcloud($cloud, 64);
4771 print "<table class=\"project_list\">\n";
4772 unless ($no_header) {
4773 print "<tr>\n";
4774 if ($check_forks) {
4775 print "<th></th>\n";
4777 print_sort_th('project', $order, 'Project');
4778 print_sort_th('descr', $order, 'Description');
4779 print_sort_th('owner', $order, 'Owner');
4780 print_sort_th('age', $order, 'Last Change');
4781 print "<th></th>\n" . # for links
4782 "</tr>\n";
4784 my $alternate = 1;
4785 my $tagfilter = $cgi->param('by_tag');
4786 for (my $i = $from; $i <= $to; $i++) {
4787 my $pr = $projects[$i];
4789 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4790 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4791 and not $pr->{'descr_long'} =~ /$searchtext/;
4792 # Weed out forks or non-matching entries of search
4793 if ($check_forks) {
4794 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4795 $forkbase="^$forkbase" if $forkbase;
4796 next if not $searchtext and not $tagfilter and $show_ctags
4797 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4800 if ($alternate) {
4801 print "<tr class=\"dark\">\n";
4802 } else {
4803 print "<tr class=\"light\">\n";
4805 $alternate ^= 1;
4806 if ($check_forks) {
4807 print "<td>";
4808 if ($pr->{'forks'}) {
4809 print "<!-- $pr->{'forks'} -->\n";
4810 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4812 print "</td>\n";
4814 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4815 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4816 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4817 -class => "list", -title => $pr->{'descr_long'}},
4818 esc_html($pr->{'descr'})) . "</td>\n" .
4819 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4820 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4821 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4822 "<td class=\"link\">" .
4823 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4824 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4825 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4826 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4827 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4828 "</td>\n" .
4829 "</tr>\n";
4831 if (defined $extra) {
4832 print "<tr>\n";
4833 if ($check_forks) {
4834 print "<td></td>\n";
4836 print "<td colspan=\"5\">$extra</td>\n" .
4837 "</tr>\n";
4839 print "</table>\n";
4842 sub git_log_body {
4843 # uses global variable $project
4844 my ($commitlist, $from, $to, $refs, $extra) = @_;
4846 $from = 0 unless defined $from;
4847 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4849 for (my $i = 0; $i <= $to; $i++) {
4850 my %co = %{$commitlist->[$i]};
4851 next if !%co;
4852 my $commit = $co{'id'};
4853 my $ref = format_ref_marker($refs, $commit);
4854 my %ad = parse_date($co{'author_epoch'});
4855 git_print_header_div('commit',
4856 "<span class=\"age\">$co{'age_string'}</span>" .
4857 esc_html($co{'title'}) . $ref,
4858 $commit);
4859 print "<div class=\"title_text\">\n" .
4860 "<div class=\"log_link\">\n" .
4861 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4862 " | " .
4863 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4864 " | " .
4865 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4866 "<br/>\n" .
4867 "</div>\n";
4868 git_print_authorship(\%co, -tag => 'span');
4869 print "<br/>\n</div>\n";
4871 print "<div class=\"log_body\">\n";
4872 git_print_log($co{'comment'}, -final_empty_line=> 1);
4873 print "</div>\n";
4875 if ($extra) {
4876 print "<div class=\"page_nav\">\n";
4877 print "$extra\n";
4878 print "</div>\n";
4882 sub git_shortlog_body {
4883 # uses global variable $project
4884 my ($commitlist, $from, $to, $refs, $extra) = @_;
4886 $from = 0 unless defined $from;
4887 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4889 print "<table class=\"shortlog\">\n";
4890 my $alternate = 1;
4891 for (my $i = $from; $i <= $to; $i++) {
4892 my %co = %{$commitlist->[$i]};
4893 my $commit = $co{'id'};
4894 my $ref = format_ref_marker($refs, $commit);
4895 if ($alternate) {
4896 print "<tr class=\"dark\">\n";
4897 } else {
4898 print "<tr class=\"light\">\n";
4900 $alternate ^= 1;
4901 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4902 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4903 format_author_html('td', \%co, 10) . "<td>";
4904 print format_subject_html($co{'title'}, $co{'title_short'},
4905 href(action=>"commit", hash=>$commit), $ref);
4906 print "</td>\n" .
4907 "<td class=\"link\">" .
4908 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4909 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4910 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4911 my $snapshot_links = format_snapshot_links($commit);
4912 if (defined $snapshot_links) {
4913 print " | " . $snapshot_links;
4915 print "</td>\n" .
4916 "</tr>\n";
4918 if (defined $extra) {
4919 print "<tr>\n" .
4920 "<td colspan=\"4\">$extra</td>\n" .
4921 "</tr>\n";
4923 print "</table>\n";
4926 sub git_history_body {
4927 # Warning: assumes constant type (blob or tree) during history
4928 my ($commitlist, $from, $to, $refs, $extra,
4929 $file_name, $file_hash, $ftype) = @_;
4931 $from = 0 unless defined $from;
4932 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4934 print "<table class=\"history\">\n";
4935 my $alternate = 1;
4936 for (my $i = $from; $i <= $to; $i++) {
4937 my %co = %{$commitlist->[$i]};
4938 if (!%co) {
4939 next;
4941 my $commit = $co{'id'};
4943 my $ref = format_ref_marker($refs, $commit);
4945 if ($alternate) {
4946 print "<tr class=\"dark\">\n";
4947 } else {
4948 print "<tr class=\"light\">\n";
4950 $alternate ^= 1;
4951 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4952 # shortlog: format_author_html('td', \%co, 10)
4953 format_author_html('td', \%co, 15, 3) . "<td>";
4954 # originally git_history used chop_str($co{'title'}, 50)
4955 print format_subject_html($co{'title'}, $co{'title_short'},
4956 href(action=>"commit", hash=>$commit), $ref);
4957 print "</td>\n" .
4958 "<td class=\"link\">" .
4959 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4960 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4962 if ($ftype eq 'blob') {
4963 my $blob_current = $file_hash;
4964 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4965 if (defined $blob_current && defined $blob_parent &&
4966 $blob_current ne $blob_parent) {
4967 print " | " .
4968 $cgi->a({-href => href(action=>"blobdiff",
4969 hash=>$blob_current, hash_parent=>$blob_parent,
4970 hash_base=>$hash_base, hash_parent_base=>$commit,
4971 file_name=>$file_name)},
4972 "diff to current");
4975 print "</td>\n" .
4976 "</tr>\n";
4978 if (defined $extra) {
4979 print "<tr>\n" .
4980 "<td colspan=\"4\">$extra</td>\n" .
4981 "</tr>\n";
4983 print "</table>\n";
4986 sub git_tags_body {
4987 # uses global variable $project
4988 my ($taglist, $from, $to, $extra) = @_;
4989 $from = 0 unless defined $from;
4990 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4992 print "<table class=\"tags\">\n";
4993 my $alternate = 1;
4994 for (my $i = $from; $i <= $to; $i++) {
4995 my $entry = $taglist->[$i];
4996 my %tag = %$entry;
4997 my $comment = $tag{'subject'};
4998 my $comment_short;
4999 if (defined $comment) {
5000 $comment_short = chop_str($comment, 30, 5);
5002 if ($alternate) {
5003 print "<tr class=\"dark\">\n";
5004 } else {
5005 print "<tr class=\"light\">\n";
5007 $alternate ^= 1;
5008 if (defined $tag{'age'}) {
5009 print "<td><i>$tag{'age'}</i></td>\n";
5010 } else {
5011 print "<td></td>\n";
5013 print "<td>" .
5014 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5015 -class => "list name"}, esc_html($tag{'name'})) .
5016 "</td>\n" .
5017 "<td>";
5018 if (defined $comment) {
5019 print format_subject_html($comment, $comment_short,
5020 href(action=>"tag", hash=>$tag{'id'}));
5022 print "</td>\n" .
5023 "<td class=\"selflink\">";
5024 if ($tag{'type'} eq "tag") {
5025 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5026 } else {
5027 print "&nbsp;";
5029 print "</td>\n" .
5030 "<td class=\"link\">" . " | " .
5031 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5032 if ($tag{'reftype'} eq "commit") {
5033 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5034 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5035 } elsif ($tag{'reftype'} eq "blob") {
5036 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5038 print "</td>\n" .
5039 "</tr>";
5041 if (defined $extra) {
5042 print "<tr>\n" .
5043 "<td colspan=\"5\">$extra</td>\n" .
5044 "</tr>\n";
5046 print "</table>\n";
5049 sub git_heads_body {
5050 # uses global variable $project
5051 my ($headlist, $head, $from, $to, $extra) = @_;
5052 $from = 0 unless defined $from;
5053 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5055 print "<table class=\"heads\">\n";
5056 my $alternate = 1;
5057 for (my $i = $from; $i <= $to; $i++) {
5058 my $entry = $headlist->[$i];
5059 my %ref = %$entry;
5060 my $curr = $ref{'id'} eq $head;
5061 if ($alternate) {
5062 print "<tr class=\"dark\">\n";
5063 } else {
5064 print "<tr class=\"light\">\n";
5066 $alternate ^= 1;
5067 print "<td><i>$ref{'age'}</i></td>\n" .
5068 ($curr ? "<td class=\"current_head\">" : "<td>") .
5069 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5070 -class => "list name"},esc_html($ref{'name'})) .
5071 "</td>\n" .
5072 "<td class=\"link\">" .
5073 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5074 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5075 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
5076 "</td>\n" .
5077 "</tr>";
5079 if (defined $extra) {
5080 print "<tr>\n" .
5081 "<td colspan=\"3\">$extra</td>\n" .
5082 "</tr>\n";
5084 print "</table>\n";
5087 sub git_search_grep_body {
5088 my ($commitlist, $from, $to, $extra) = @_;
5089 $from = 0 unless defined $from;
5090 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5092 print "<table class=\"commit_search\">\n";
5093 my $alternate = 1;
5094 for (my $i = $from; $i <= $to; $i++) {
5095 my %co = %{$commitlist->[$i]};
5096 if (!%co) {
5097 next;
5099 my $commit = $co{'id'};
5100 if ($alternate) {
5101 print "<tr class=\"dark\">\n";
5102 } else {
5103 print "<tr class=\"light\">\n";
5105 $alternate ^= 1;
5106 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5107 format_author_html('td', \%co, 15, 5) .
5108 "<td>" .
5109 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5110 -class => "list subject"},
5111 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5112 my $comment = $co{'comment'};
5113 foreach my $line (@$comment) {
5114 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5115 my ($lead, $match, $trail) = ($1, $2, $3);
5116 $match = chop_str($match, 70, 5, 'center');
5117 my $contextlen = int((80 - length($match))/2);
5118 $contextlen = 30 if ($contextlen > 30);
5119 $lead = chop_str($lead, $contextlen, 10, 'left');
5120 $trail = chop_str($trail, $contextlen, 10, 'right');
5122 $lead = esc_html($lead);
5123 $match = esc_html($match);
5124 $trail = esc_html($trail);
5126 print "$lead<span class=\"match\">$match</span>$trail<br />";
5129 print "</td>\n" .
5130 "<td class=\"link\">" .
5131 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5132 " | " .
5133 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5134 " | " .
5135 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5136 print "</td>\n" .
5137 "</tr>\n";
5139 if (defined $extra) {
5140 print "<tr>\n" .
5141 "<td colspan=\"3\">$extra</td>\n" .
5142 "</tr>\n";
5144 print "</table>\n";
5147 ## ======================================================================
5148 ## ======================================================================
5149 ## actions
5151 sub git_project_list {
5152 my $order = $input_params{'order'};
5153 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5154 die_error(400, "Unknown order parameter");
5157 my @list = git_get_projects_list();
5158 if (!@list) {
5159 die_error(404, "No projects found");
5162 git_header_html();
5163 if (defined $home_text && -f $home_text) {
5164 print "<div class=\"index_include\">\n";
5165 insert_file($home_text);
5166 print "</div>\n";
5168 print $cgi->startform(-method => "get") .
5169 "<p class=\"projsearch\">Search:\n" .
5170 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5171 "</p>" .
5172 $cgi->end_form() . "\n";
5173 git_project_list_body(\@list, $order);
5174 git_footer_html();
5177 sub git_forks {
5178 my $order = $input_params{'order'};
5179 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5180 die_error(400, "Unknown order parameter");
5183 my @list = git_get_projects_list($project);
5184 if (!@list) {
5185 die_error(404, "No forks found");
5188 git_header_html();
5189 git_print_page_nav('','');
5190 git_print_header_div('summary', "$project forks");
5191 git_project_list_body(\@list, $order);
5192 git_footer_html();
5195 sub git_project_index {
5196 my @projects = git_get_projects_list($project);
5198 print $cgi->header(
5199 -type => 'text/plain',
5200 -charset => 'utf-8',
5201 -content_disposition => 'inline; filename="index.aux"');
5203 foreach my $pr (@projects) {
5204 if (!exists $pr->{'owner'}) {
5205 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5208 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5209 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5210 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5211 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5212 $path =~ s/ /\+/g;
5213 $owner =~ s/ /\+/g;
5215 print "$path $owner\n";
5219 sub git_summary {
5220 my $descr = git_get_project_description($project) || "none";
5221 my %co = parse_commit("HEAD");
5222 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5223 my $head = $co{'id'};
5225 my $owner = git_get_project_owner($project);
5227 my $refs = git_get_references();
5228 # These get_*_list functions return one more to allow us to see if
5229 # there are more ...
5230 my @taglist = git_get_tags_list(16);
5231 my @headlist = git_get_heads_list(16);
5232 my @forklist;
5233 my $check_forks = gitweb_check_feature('forks');
5235 if ($check_forks) {
5236 @forklist = git_get_projects_list($project);
5239 git_header_html();
5240 git_print_page_nav('summary','', $head);
5242 print "<div class=\"title\">&nbsp;</div>\n";
5243 print "<table class=\"projects_list\">\n" .
5244 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5245 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5246 if (defined $cd{'rfc2822'}) {
5247 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5250 # use per project git URL list in $projectroot/$project/cloneurl
5251 # or make project git URL from git base URL and project name
5252 my $url_tag = "URL";
5253 my @url_list = git_get_project_url_list($project);
5254 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5255 foreach my $git_url (@url_list) {
5256 next unless $git_url;
5257 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5258 $url_tag = "";
5261 # Tag cloud
5262 my $show_ctags = gitweb_check_feature('ctags');
5263 if ($show_ctags) {
5264 my $ctags = git_get_project_ctags($project);
5265 my $cloud = git_populate_project_tagcloud($ctags);
5266 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5267 print "</td>\n<td>" unless %$ctags;
5268 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5269 print "</td>\n<td>" if %$ctags;
5270 print git_show_project_tagcloud($cloud, 48);
5271 print "</td></tr>";
5274 print "</table>\n";
5276 # If XSS prevention is on, we don't include README.html.
5277 # TODO: Allow a readme in some safe format.
5278 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5279 print "<div class=\"title\">readme</div>\n" .
5280 "<div class=\"readme\">\n";
5281 insert_file("$projectroot/$project/README.html");
5282 print "\n</div>\n"; # class="readme"
5285 # we need to request one more than 16 (0..15) to check if
5286 # those 16 are all
5287 my @commitlist = $head ? parse_commits($head, 17) : ();
5288 if (@commitlist) {
5289 git_print_header_div('shortlog');
5290 git_shortlog_body(\@commitlist, 0, 15, $refs,
5291 $#commitlist <= 15 ? undef :
5292 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5295 if (@taglist) {
5296 git_print_header_div('tags');
5297 git_tags_body(\@taglist, 0, 15,
5298 $#taglist <= 15 ? undef :
5299 $cgi->a({-href => href(action=>"tags")}, "..."));
5302 if (@headlist) {
5303 git_print_header_div('heads');
5304 git_heads_body(\@headlist, $head, 0, 15,
5305 $#headlist <= 15 ? undef :
5306 $cgi->a({-href => href(action=>"heads")}, "..."));
5309 if (@forklist) {
5310 git_print_header_div('forks');
5311 git_project_list_body(\@forklist, 'age', 0, 15,
5312 $#forklist <= 15 ? undef :
5313 $cgi->a({-href => href(action=>"forks")}, "..."),
5314 'no_header');
5317 git_footer_html();
5320 sub git_tag {
5321 my %tag = parse_tag($hash);
5323 if (! %tag) {
5324 die_error(404, "Unknown tag object");
5327 my $head = git_get_head_hash($project);
5328 git_header_html();
5329 git_print_page_nav('','', $head,undef,$head);
5330 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5331 print "<div class=\"title_text\">\n" .
5332 "<table class=\"object_header\">\n" .
5333 "<tr>\n" .
5334 "<td>object</td>\n" .
5335 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5336 $tag{'object'}) . "</td>\n" .
5337 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5338 $tag{'type'}) . "</td>\n" .
5339 "</tr>\n";
5340 if (defined($tag{'author'})) {
5341 git_print_authorship_rows(\%tag, 'author');
5343 print "</table>\n\n" .
5344 "</div>\n";
5345 print "<div class=\"page_body\">";
5346 my $comment = $tag{'comment'};
5347 foreach my $line (@$comment) {
5348 chomp $line;
5349 print esc_html($line, -nbsp=>1) . "<br/>\n";
5351 print "</div>\n";
5352 git_footer_html();
5355 sub git_blame_common {
5356 my $format = shift || 'porcelain';
5357 if ($format eq 'porcelain' && $cgi->param('js') &&
5358 !$caching_enabled) {
5359 $format = 'incremental';
5360 $action = 'blame_incremental'; # for page title etc
5363 # permissions
5364 gitweb_check_feature('blame')
5365 or die_error(403, "Blame view not allowed");
5367 # error checking
5368 die_error(400, "No file name given") unless $file_name;
5369 $hash_base ||= git_get_head_hash($project);
5370 die_error(404, "Couldn't find base commit") unless $hash_base;
5371 my %co = parse_commit($hash_base)
5372 or die_error(404, "Commit not found");
5373 my $ftype = "blob";
5374 if (!defined $hash) {
5375 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5376 or die_error(404, "Error looking up file");
5377 } else {
5378 $ftype = git_get_type($hash);
5379 if ($ftype !~ "blob") {
5380 die_error(400, "Object is not a blob");
5384 my $fd;
5385 if ($format eq 'incremental') {
5386 # get file contents (as base)
5387 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5388 or die_error(500, "Open git-cat-file failed");
5389 } elsif ($format eq 'data') {
5390 # run git-blame --incremental
5391 open $fd, "-|", git_cmd(), "blame", "--incremental",
5392 $hash_base, "--", $file_name
5393 or die_error(500, "Open git-blame --incremental failed");
5394 } else {
5395 # run git-blame --porcelain
5396 open $fd, "-|", git_cmd(), "blame", '-p',
5397 $hash_base, '--', $file_name
5398 or die_error(500, "Open git-blame --porcelain failed");
5401 # incremental blame data returns early
5402 if ($format eq 'data') {
5403 print $cgi->header(
5404 -type=>"text/plain", -charset => "utf-8",
5405 -status=> "200 OK");
5406 local $| = 1; # output autoflush
5407 print while <$fd>;
5408 close $fd
5409 or print "ERROR $!\n";
5411 print 'END';
5412 if (!$caching_enabled &&
5413 defined $t0 && gitweb_check_feature('timed')) {
5414 print ' '.
5415 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5416 ' '.$number_of_git_cmds;
5418 print "\n";
5420 return;
5423 # page header
5424 git_header_html();
5425 my $formats_nav =
5426 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5427 "blob") .
5428 " | ";
5429 if ($format eq 'incremental') {
5430 $formats_nav .=
5431 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5432 "blame") . " (non-incremental)";
5433 } elsif (!$caching_enabled) {
5434 $formats_nav .=
5435 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5436 "blame") . " (incremental)";
5438 $formats_nav .=
5439 " | " .
5440 $cgi->a({-href => href(action=>"history", -replay=>1)},
5441 "history") .
5442 " | " .
5443 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5444 "HEAD");
5445 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5446 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5447 git_print_page_path($file_name, $ftype, $hash_base);
5449 # page body
5450 if ($format eq 'incremental') {
5451 print "<noscript>\n<div class=\"error\"><center><b>\n".
5452 "This page requires JavaScript to run.\n Use ".
5453 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5454 'this page').
5455 " instead.\n".
5456 "</b></center></div>\n</noscript>\n";
5458 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5461 print qq!<div class="page_body">\n!;
5462 print qq!<div id="progress_info">... / ...</div>\n!
5463 if ($format eq 'incremental');
5464 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5465 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5466 qq!<thead>\n!.
5467 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5468 qq!</thead>\n!.
5469 qq!<tbody>\n!;
5471 my @rev_color = qw(light dark);
5472 my $num_colors = scalar(@rev_color);
5473 my $current_color = 0;
5475 if ($format eq 'incremental') {
5476 my $color_class = $rev_color[$current_color];
5478 #contents of a file
5479 my $linenr = 0;
5480 LINE:
5481 while (my $line = <$fd>) {
5482 chomp $line;
5483 $linenr++;
5485 print qq!<tr id="l$linenr" class="$color_class">!.
5486 qq!<td class="sha1"><a href=""> </a></td>!.
5487 qq!<td class="linenr">!.
5488 qq!<a class="linenr" href="">$linenr</a></td>!;
5489 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5490 print qq!</tr>\n!;
5493 } else { # porcelain, i.e. ordinary blame
5494 my %metainfo = (); # saves information about commits
5496 # blame data
5497 LINE:
5498 while (my $line = <$fd>) {
5499 chomp $line;
5500 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5501 # no <lines in group> for subsequent lines in group of lines
5502 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5503 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5504 if (!exists $metainfo{$full_rev}) {
5505 $metainfo{$full_rev} = { 'nprevious' => 0 };
5507 my $meta = $metainfo{$full_rev};
5508 my $data;
5509 while ($data = <$fd>) {
5510 chomp $data;
5511 last if ($data =~ s/^\t//); # contents of line
5512 if ($data =~ /^(\S+)(?: (.*))?$/) {
5513 $meta->{$1} = $2 unless exists $meta->{$1};
5515 if ($data =~ /^previous /) {
5516 $meta->{'nprevious'}++;
5519 my $short_rev = substr($full_rev, 0, 8);
5520 my $author = $meta->{'author'};
5521 my %date =
5522 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5523 my $date = $date{'iso-tz'};
5524 if ($group_size) {
5525 $current_color = ($current_color + 1) % $num_colors;
5527 my $tr_class = $rev_color[$current_color];
5528 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5529 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5530 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5531 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5532 if ($group_size) {
5533 print "<td class=\"sha1\"";
5534 print " title=\"". esc_html($author) . ", $date\"";
5535 print " rowspan=\"$group_size\"" if ($group_size > 1);
5536 print ">";
5537 print $cgi->a({-href => href(action=>"commit",
5538 hash=>$full_rev,
5539 file_name=>$file_name)},
5540 esc_html($short_rev));
5541 if ($group_size >= 2) {
5542 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5543 if (@author_initials) {
5544 print "<br />" .
5545 esc_html(join('', @author_initials));
5546 # or join('.', ...)
5549 print "</td>\n";
5551 # 'previous' <sha1 of parent commit> <filename at commit>
5552 if (exists $meta->{'previous'} &&
5553 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5554 $meta->{'parent'} = $1;
5555 $meta->{'file_parent'} = unquote($2);
5557 my $linenr_commit =
5558 exists($meta->{'parent'}) ?
5559 $meta->{'parent'} : $full_rev;
5560 my $linenr_filename =
5561 exists($meta->{'file_parent'}) ?
5562 $meta->{'file_parent'} : unquote($meta->{'filename'});
5563 my $blamed = href(action => 'blame',
5564 file_name => $linenr_filename,
5565 hash_base => $linenr_commit);
5566 print "<td class=\"linenr\">";
5567 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5568 -class => "linenr" },
5569 esc_html($lineno));
5570 print "</td>";
5571 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5572 print "</tr>\n";
5573 } # end while
5577 # footer
5578 print "</tbody>\n".
5579 "</table>\n"; # class="blame"
5580 print "</div>\n"; # class="blame_body"
5581 close $fd
5582 or print "Reading blob failed\n";
5584 git_footer_html();
5587 sub git_blame {
5588 git_blame_common();
5591 sub git_blame_incremental {
5592 git_blame_common(!$caching_enabled ? 'incremental' : undef);
5595 sub git_blame_data {
5596 git_blame_common('data');
5599 sub git_tags {
5600 my $head = git_get_head_hash($project);
5601 git_header_html();
5602 git_print_page_nav('','', $head,undef,$head);
5603 git_print_header_div('summary', $project);
5605 my @tagslist = git_get_tags_list();
5606 if (@tagslist) {
5607 git_tags_body(\@tagslist);
5609 git_footer_html();
5612 sub git_heads {
5613 my $head = git_get_head_hash($project);
5614 git_header_html();
5615 git_print_page_nav('','', $head,undef,$head);
5616 git_print_header_div('summary', $project);
5618 my @headslist = git_get_heads_list();
5619 if (@headslist) {
5620 git_heads_body(\@headslist, $head);
5622 git_footer_html();
5625 sub git_blob_plain {
5626 my $type = shift;
5627 my $expires;
5629 if (!defined $hash) {
5630 if (defined $file_name) {
5631 my $base = $hash_base || git_get_head_hash($project);
5632 $hash = git_get_hash_by_path($base, $file_name, "blob")
5633 or die_error(404, "Cannot find file");
5634 } else {
5635 die_error(400, "No file name defined");
5637 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5638 # blobs defined by non-textual hash id's can be cached
5639 $expires = "+1d";
5642 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5643 or die_error(500, "Open git-cat-file blob '$hash' failed");
5645 # content-type (can include charset)
5646 $type = blob_contenttype($fd, $file_name, $type);
5648 # "save as" filename, even when no $file_name is given
5649 my $save_as = "$hash";
5650 if (defined $file_name) {
5651 $save_as = $file_name;
5652 } elsif ($type =~ m/^text\//) {
5653 $save_as .= '.txt';
5656 # With XSS prevention on, blobs of all types except a few known safe
5657 # ones are served with "Content-Disposition: attachment" to make sure
5658 # they don't run in our security domain. For certain image types,
5659 # blob view writes an <img> tag referring to blob_plain view, and we
5660 # want to be sure not to break that by serving the image as an
5661 # attachment (though Firefox 3 doesn't seem to care).
5662 my $sandbox = $prevent_xss &&
5663 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5665 print $cgi->header(
5666 -type => $type,
5667 -expires => $expires,
5668 -content_disposition =>
5669 ($sandbox ? 'attachment' : 'inline')
5670 . '; filename="' . $save_as . '"');
5671 local $/ = undef;
5672 binmode STDOUT, ':raw';
5673 print <$fd>;
5674 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5675 close $fd;
5678 sub git_blob {
5679 my $expires;
5681 if (!defined $hash) {
5682 if (defined $file_name) {
5683 my $base = $hash_base || git_get_head_hash($project);
5684 $hash = git_get_hash_by_path($base, $file_name, "blob")
5685 or die_error(404, "Cannot find file");
5686 } else {
5687 die_error(400, "No file name defined");
5689 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5690 # blobs defined by non-textual hash id's can be cached
5691 $expires = "+1d";
5694 my $have_blame = gitweb_check_feature('blame');
5695 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5696 or die_error(500, "Couldn't cat $file_name, $hash");
5697 my $mimetype = blob_mimetype($fd, $file_name);
5698 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5699 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5700 close $fd;
5701 return git_blob_plain($mimetype);
5703 # we can have blame only for text/* mimetype
5704 $have_blame &&= ($mimetype =~ m!^text/!);
5706 my $highlight = gitweb_check_feature('highlight');
5707 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5708 $fd = run_highlighter($fd, $highlight, $syntax)
5709 if $syntax;
5711 git_header_html(undef, $expires);
5712 my $formats_nav = '';
5713 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5714 if (defined $file_name) {
5715 if ($have_blame) {
5716 $formats_nav .=
5717 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5718 "blame") .
5719 " | ";
5721 $formats_nav .=
5722 $cgi->a({-href => href(action=>"history", -replay=>1)},
5723 "history") .
5724 " | " .
5725 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5726 "raw") .
5727 " | " .
5728 $cgi->a({-href => href(action=>"blob",
5729 hash_base=>"HEAD", file_name=>$file_name)},
5730 "HEAD");
5731 } else {
5732 $formats_nav .=
5733 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5734 "raw");
5736 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5737 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5738 } else {
5739 print "<div class=\"page_nav\">\n" .
5740 "<br/><br/></div>\n" .
5741 "<div class=\"title\">$hash</div>\n";
5743 git_print_page_path($file_name, "blob", $hash_base);
5744 print "<div class=\"page_body\">\n";
5745 if ($mimetype =~ m!^image/!) {
5746 print qq!<img type="$mimetype"!;
5747 if ($file_name) {
5748 print qq! alt="$file_name" title="$file_name"!;
5750 print qq! src="! .
5751 href(action=>"blob_plain", hash=>$hash,
5752 hash_base=>$hash_base, file_name=>$file_name) .
5753 qq!" />\n!;
5754 } else {
5755 my $nr;
5756 while (my $line = <$fd>) {
5757 chomp $line;
5758 $nr++;
5759 $line = untabify($line);
5760 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5761 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5764 close $fd
5765 or print "Reading blob failed.\n";
5766 print "</div>";
5767 git_footer_html();
5770 sub git_tree {
5771 if (!defined $hash_base) {
5772 $hash_base = "HEAD";
5774 if (!defined $hash) {
5775 if (defined $file_name) {
5776 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5777 } else {
5778 $hash = $hash_base;
5781 die_error(404, "No such tree") unless defined($hash);
5783 my $show_sizes = gitweb_check_feature('show-sizes');
5784 my $have_blame = gitweb_check_feature('blame');
5786 my @entries = ();
5788 local $/ = "\0";
5789 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5790 ($show_sizes ? '-l' : ()), @extra_options, $hash
5791 or die_error(500, "Open git-ls-tree failed");
5792 @entries = map { chomp; $_ } <$fd>;
5793 close $fd
5794 or die_error(404, "Reading tree failed");
5797 my $refs = git_get_references();
5798 my $ref = format_ref_marker($refs, $hash_base);
5799 git_header_html();
5800 my $basedir = '';
5801 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5802 my @views_nav = ();
5803 if (defined $file_name) {
5804 push @views_nav,
5805 $cgi->a({-href => href(action=>"history", -replay=>1)},
5806 "history"),
5807 $cgi->a({-href => href(action=>"tree",
5808 hash_base=>"HEAD", file_name=>$file_name)},
5809 "HEAD"),
5811 my $snapshot_links = format_snapshot_links($hash);
5812 if (defined $snapshot_links) {
5813 # FIXME: Should be available when we have no hash base as well.
5814 push @views_nav, $snapshot_links;
5816 git_print_page_nav('tree','', $hash_base, undef, undef,
5817 join(' | ', @views_nav));
5818 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5819 } else {
5820 undef $hash_base;
5821 print "<div class=\"page_nav\">\n";
5822 print "<br/><br/></div>\n";
5823 print "<div class=\"title\">$hash</div>\n";
5825 if (defined $file_name) {
5826 $basedir = $file_name;
5827 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5828 $basedir .= '/';
5830 git_print_page_path($file_name, 'tree', $hash_base);
5832 print "<div class=\"page_body\">\n";
5833 print "<table class=\"tree\">\n";
5834 my $alternate = 1;
5835 # '..' (top directory) link if possible
5836 if (defined $hash_base &&
5837 defined $file_name && $file_name =~ m![^/]+$!) {
5838 if ($alternate) {
5839 print "<tr class=\"dark\">\n";
5840 } else {
5841 print "<tr class=\"light\">\n";
5843 $alternate ^= 1;
5845 my $up = $file_name;
5846 $up =~ s!/?[^/]+$!!;
5847 undef $up unless $up;
5848 # based on git_print_tree_entry
5849 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5850 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5851 print '<td class="list">';
5852 print $cgi->a({-href => href(action=>"tree",
5853 hash_base=>$hash_base,
5854 file_name=>$up)},
5855 "..");
5856 print "</td>\n";
5857 print "<td class=\"link\"></td>\n";
5859 print "</tr>\n";
5861 foreach my $line (@entries) {
5862 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5864 if ($alternate) {
5865 print "<tr class=\"dark\">\n";
5866 } else {
5867 print "<tr class=\"light\">\n";
5869 $alternate ^= 1;
5871 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5873 print "</tr>\n";
5875 print "</table>\n" .
5876 "</div>";
5877 git_footer_html();
5880 sub snapshot_name {
5881 my ($project, $hash) = @_;
5883 # path/to/project.git -> project
5884 # path/to/project/.git -> project
5885 my $name = to_utf8($project);
5886 $name =~ s,([^/])/*\.git$,$1,;
5887 $name = basename($name);
5888 # sanitize name
5889 $name =~ s/[[:cntrl:]]/?/g;
5891 my $ver = $hash;
5892 if ($hash =~ /^[0-9a-fA-F]+$/) {
5893 # shorten SHA-1 hash
5894 my $full_hash = git_get_full_hash($project, $hash);
5895 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5896 $ver = git_get_short_hash($project, $hash);
5898 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5899 # tags don't need shortened SHA-1 hash
5900 $ver = $1;
5901 } else {
5902 # branches and other need shortened SHA-1 hash
5903 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5904 $ver = $1;
5906 $ver .= '-' . git_get_short_hash($project, $hash);
5908 # in case of hierarchical branch names
5909 $ver =~ s!/!.!g;
5911 # name = project-version_string
5912 $name = "$name-$ver";
5914 return wantarray ? ($name, $name) : $name;
5917 sub git_snapshot {
5918 my $format = $input_params{'snapshot_format'};
5919 if (!@snapshot_fmts) {
5920 die_error(403, "Snapshots not allowed");
5922 # default to first supported snapshot format
5923 $format ||= $snapshot_fmts[0];
5924 if ($format !~ m/^[a-z0-9]+$/) {
5925 die_error(400, "Invalid snapshot format parameter");
5926 } elsif (!exists($known_snapshot_formats{$format})) {
5927 die_error(400, "Unknown snapshot format");
5928 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5929 die_error(403, "Snapshot format not allowed");
5930 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5931 die_error(403, "Unsupported snapshot format");
5934 my $type = git_get_type("$hash^{}");
5935 if (!$type) {
5936 die_error(404, 'Object does not exist');
5937 } elsif ($type eq 'blob') {
5938 die_error(400, 'Object is not a tree-ish');
5941 my ($name, $prefix) = snapshot_name($project, $hash);
5942 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
5943 my $cmd = quote_command(
5944 git_cmd(), 'archive',
5945 "--format=$known_snapshot_formats{$format}{'format'}",
5946 "--prefix=$prefix/", $hash);
5947 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5948 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5951 $filename =~ s/(["\\])/\\$1/g;
5952 print $cgi->header(
5953 -type => $known_snapshot_formats{$format}{'type'},
5954 -content_disposition => 'inline; filename="' . $filename . '"',
5955 -status => '200 OK');
5957 open my $fd, "-|", $cmd
5958 or die_error(500, "Execute git-archive failed");
5959 binmode STDOUT, ':raw';
5960 print <$fd>;
5961 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5962 close $fd;
5965 sub git_log_generic {
5966 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
5968 my $head = git_get_head_hash($project);
5969 if (!defined $base) {
5970 $base = $head;
5972 if (!defined $page) {
5973 $page = 0;
5975 my $refs = git_get_references();
5977 my $commit_hash = $base;
5978 if (defined $parent) {
5979 $commit_hash = "$parent..$base";
5981 my @commitlist =
5982 parse_commits($commit_hash, 101, (100 * $page),
5983 defined $file_name ? ($file_name, "--full-history") : ());
5985 my $ftype;
5986 if (!defined $file_hash && defined $file_name) {
5987 # some commits could have deleted file in question,
5988 # and not have it in tree, but one of them has to have it
5989 for (my $i = 0; $i < @commitlist; $i++) {
5990 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5991 last if defined $file_hash;
5994 if (defined $file_hash) {
5995 $ftype = git_get_type($file_hash);
5997 if (defined $file_name && !defined $ftype) {
5998 die_error(500, "Unknown type of object");
6000 my %co;
6001 if (defined $file_name) {
6002 %co = parse_commit($base)
6003 or die_error(404, "Unknown commit object");
6007 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6008 my $next_link = '';
6009 if ($#commitlist >= 100) {
6010 $next_link =
6011 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6012 -accesskey => "n", -title => "Alt-n"}, "next");
6014 my $patch_max = gitweb_get_feature('patches');
6015 if ($patch_max && !defined $file_name) {
6016 if ($patch_max < 0 || @commitlist <= $patch_max) {
6017 $paging_nav .= " &sdot; " .
6018 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6019 "patches");
6023 git_header_html();
6024 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6025 if (defined $file_name) {
6026 git_print_header_div('commit', esc_html($co{'title'}), $base);
6027 } else {
6028 git_print_header_div('summary', $project)
6030 git_print_page_path($file_name, $ftype, $hash_base)
6031 if (defined $file_name);
6033 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6034 $file_name, $file_hash, $ftype);
6036 git_footer_html();
6039 sub git_log {
6040 git_log_generic('log', \&git_log_body,
6041 $hash, $hash_parent);
6044 sub git_commit {
6045 $hash ||= $hash_base || "HEAD";
6046 my %co = parse_commit($hash)
6047 or die_error(404, "Unknown commit object");
6049 my $parent = $co{'parent'};
6050 my $parents = $co{'parents'}; # listref
6052 # we need to prepare $formats_nav before any parameter munging
6053 my $formats_nav;
6054 if (!defined $parent) {
6055 # --root commitdiff
6056 $formats_nav .= '(initial)';
6057 } elsif (@$parents == 1) {
6058 # single parent commit
6059 $formats_nav .=
6060 '(parent: ' .
6061 $cgi->a({-href => href(action=>"commit",
6062 hash=>$parent)},
6063 esc_html(substr($parent, 0, 7))) .
6064 ')';
6065 } else {
6066 # merge commit
6067 $formats_nav .=
6068 '(merge: ' .
6069 join(' ', map {
6070 $cgi->a({-href => href(action=>"commit",
6071 hash=>$_)},
6072 esc_html(substr($_, 0, 7)));
6073 } @$parents ) .
6074 ')';
6076 if (gitweb_check_feature('patches') && @$parents <= 1) {
6077 $formats_nav .= " | " .
6078 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6079 "patch");
6082 if (!defined $parent) {
6083 $parent = "--root";
6085 my @difftree;
6086 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6087 @diff_opts,
6088 (@$parents <= 1 ? $parent : '-c'),
6089 $hash, "--"
6090 or die_error(500, "Open git-diff-tree failed");
6091 @difftree = map { chomp; $_ } <$fd>;
6092 close $fd or die_error(404, "Reading git-diff-tree failed");
6094 # non-textual hash id's can be cached
6095 my $expires;
6096 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6097 $expires = "+1d";
6099 my $refs = git_get_references();
6100 my $ref = format_ref_marker($refs, $co{'id'});
6102 git_header_html(undef, $expires);
6103 git_print_page_nav('commit', '',
6104 $hash, $co{'tree'}, $hash,
6105 $formats_nav);
6107 if (defined $co{'parent'}) {
6108 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6109 } else {
6110 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6112 print "<div class=\"title_text\">\n" .
6113 "<table class=\"object_header\">\n";
6114 git_print_authorship_rows(\%co);
6115 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6116 print "<tr>" .
6117 "<td>tree</td>" .
6118 "<td class=\"sha1\">" .
6119 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6120 class => "list"}, $co{'tree'}) .
6121 "</td>" .
6122 "<td class=\"link\">" .
6123 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6124 "tree");
6125 my $snapshot_links = format_snapshot_links($hash);
6126 if (defined $snapshot_links) {
6127 print " | " . $snapshot_links;
6129 print "</td>" .
6130 "</tr>\n";
6132 foreach my $par (@$parents) {
6133 print "<tr>" .
6134 "<td>parent</td>" .
6135 "<td class=\"sha1\">" .
6136 $cgi->a({-href => href(action=>"commit", hash=>$par),
6137 class => "list"}, $par) .
6138 "</td>" .
6139 "<td class=\"link\">" .
6140 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6141 " | " .
6142 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6143 "</td>" .
6144 "</tr>\n";
6146 print "</table>".
6147 "</div>\n";
6149 print "<div class=\"page_body\">\n";
6150 git_print_log($co{'comment'});
6151 print "</div>\n";
6153 git_difftree_body(\@difftree, $hash, @$parents);
6155 git_footer_html();
6158 sub git_object {
6159 # object is defined by:
6160 # - hash or hash_base alone
6161 # - hash_base and file_name
6162 my $type;
6164 # - hash or hash_base alone
6165 if ($hash || ($hash_base && !defined $file_name)) {
6166 my $object_id = $hash || $hash_base;
6168 open my $fd, "-|", quote_command(
6169 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6170 or die_error(404, "Object does not exist");
6171 $type = <$fd>;
6172 chomp $type;
6173 close $fd
6174 or die_error(404, "Object does not exist");
6176 # - hash_base and file_name
6177 } elsif ($hash_base && defined $file_name) {
6178 $file_name =~ s,/+$,,;
6180 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6181 or die_error(404, "Base object does not exist");
6183 # here errors should not hapen
6184 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6185 or die_error(500, "Open git-ls-tree failed");
6186 my $line = <$fd>;
6187 close $fd;
6189 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6190 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6191 die_error(404, "File or directory for given base does not exist");
6193 $type = $2;
6194 $hash = $3;
6195 } else {
6196 die_error(400, "Not enough information to find object");
6199 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6200 hash=>$hash, hash_base=>$hash_base,
6201 file_name=>$file_name),
6202 -status => '302 Found');
6205 sub git_blobdiff {
6206 my $format = shift || 'html';
6208 my $fd;
6209 my @difftree;
6210 my %diffinfo;
6211 my $expires;
6213 # preparing $fd and %diffinfo for git_patchset_body
6214 # new style URI
6215 if (defined $hash_base && defined $hash_parent_base) {
6216 if (defined $file_name) {
6217 # read raw output
6218 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6219 $hash_parent_base, $hash_base,
6220 "--", (defined $file_parent ? $file_parent : ()), $file_name
6221 or die_error(500, "Open git-diff-tree failed");
6222 @difftree = map { chomp; $_ } <$fd>;
6223 close $fd
6224 or die_error(404, "Reading git-diff-tree failed");
6225 @difftree
6226 or die_error(404, "Blob diff not found");
6228 } elsif (defined $hash &&
6229 $hash =~ /[0-9a-fA-F]{40}/) {
6230 # try to find filename from $hash
6232 # read filtered raw output
6233 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6234 $hash_parent_base, $hash_base, "--"
6235 or die_error(500, "Open git-diff-tree failed");
6236 @difftree =
6237 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6238 # $hash == to_id
6239 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6240 map { chomp; $_ } <$fd>;
6241 close $fd
6242 or die_error(404, "Reading git-diff-tree failed");
6243 @difftree
6244 or die_error(404, "Blob diff not found");
6246 } else {
6247 die_error(400, "Missing one of the blob diff parameters");
6250 if (@difftree > 1) {
6251 die_error(400, "Ambiguous blob diff specification");
6254 %diffinfo = parse_difftree_raw_line($difftree[0]);
6255 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6256 $file_name ||= $diffinfo{'to_file'};
6258 $hash_parent ||= $diffinfo{'from_id'};
6259 $hash ||= $diffinfo{'to_id'};
6261 # non-textual hash id's can be cached
6262 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6263 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6264 $expires = '+1d';
6267 # open patch output
6268 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6269 '-p', ($format eq 'html' ? "--full-index" : ()),
6270 $hash_parent_base, $hash_base,
6271 "--", (defined $file_parent ? $file_parent : ()), $file_name
6272 or die_error(500, "Open git-diff-tree failed");
6275 # old/legacy style URI -- not generated anymore since 1.4.3.
6276 if (!%diffinfo) {
6277 die_error('404 Not Found', "Missing one of the blob diff parameters")
6280 # header
6281 if ($format eq 'html') {
6282 my $formats_nav =
6283 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6284 "raw");
6285 git_header_html(undef, $expires);
6286 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6287 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6288 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6289 } else {
6290 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6291 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6293 if (defined $file_name) {
6294 git_print_page_path($file_name, "blob", $hash_base);
6295 } else {
6296 print "<div class=\"page_path\"></div>\n";
6299 } elsif ($format eq 'plain') {
6300 print $cgi->header(
6301 -type => 'text/plain',
6302 -charset => 'utf-8',
6303 -expires => $expires,
6304 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6306 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6308 } else {
6309 die_error(400, "Unknown blobdiff format");
6312 # patch
6313 if ($format eq 'html') {
6314 print "<div class=\"page_body\">\n";
6316 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6317 close $fd;
6319 print "</div>\n"; # class="page_body"
6320 git_footer_html();
6322 } else {
6323 while (my $line = <$fd>) {
6324 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6325 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6327 print $line;
6329 last if $line =~ m!^\+\+\+!;
6331 local $/ = undef;
6332 print <$fd>;
6333 close $fd;
6337 sub git_blobdiff_plain {
6338 git_blobdiff('plain');
6341 sub git_commitdiff {
6342 my %params = @_;
6343 my $format = $params{-format} || 'html';
6345 my ($patch_max) = gitweb_get_feature('patches');
6346 if ($format eq 'patch') {
6347 die_error(403, "Patch view not allowed") unless $patch_max;
6350 $hash ||= $hash_base || "HEAD";
6351 my %co = parse_commit($hash)
6352 or die_error(404, "Unknown commit object");
6354 # choose format for commitdiff for merge
6355 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6356 $hash_parent = '--cc';
6358 # we need to prepare $formats_nav before almost any parameter munging
6359 my $formats_nav;
6360 if ($format eq 'html') {
6361 $formats_nav =
6362 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6363 "raw");
6364 if ($patch_max && @{$co{'parents'}} <= 1) {
6365 $formats_nav .= " | " .
6366 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6367 "patch");
6370 if (defined $hash_parent &&
6371 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6372 # commitdiff with two commits given
6373 my $hash_parent_short = $hash_parent;
6374 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6375 $hash_parent_short = substr($hash_parent, 0, 7);
6377 $formats_nav .=
6378 ' (from';
6379 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6380 if ($co{'parents'}[$i] eq $hash_parent) {
6381 $formats_nav .= ' parent ' . ($i+1);
6382 last;
6385 $formats_nav .= ': ' .
6386 $cgi->a({-href => href(action=>"commitdiff",
6387 hash=>$hash_parent)},
6388 esc_html($hash_parent_short)) .
6389 ')';
6390 } elsif (!$co{'parent'}) {
6391 # --root commitdiff
6392 $formats_nav .= ' (initial)';
6393 } elsif (scalar @{$co{'parents'}} == 1) {
6394 # single parent commit
6395 $formats_nav .=
6396 ' (parent: ' .
6397 $cgi->a({-href => href(action=>"commitdiff",
6398 hash=>$co{'parent'})},
6399 esc_html(substr($co{'parent'}, 0, 7))) .
6400 ')';
6401 } else {
6402 # merge commit
6403 if ($hash_parent eq '--cc') {
6404 $formats_nav .= ' | ' .
6405 $cgi->a({-href => href(action=>"commitdiff",
6406 hash=>$hash, hash_parent=>'-c')},
6407 'combined');
6408 } else { # $hash_parent eq '-c'
6409 $formats_nav .= ' | ' .
6410 $cgi->a({-href => href(action=>"commitdiff",
6411 hash=>$hash, hash_parent=>'--cc')},
6412 'compact');
6414 $formats_nav .=
6415 ' (merge: ' .
6416 join(' ', map {
6417 $cgi->a({-href => href(action=>"commitdiff",
6418 hash=>$_)},
6419 esc_html(substr($_, 0, 7)));
6420 } @{$co{'parents'}} ) .
6421 ')';
6425 my $hash_parent_param = $hash_parent;
6426 if (!defined $hash_parent_param) {
6427 # --cc for multiple parents, --root for parentless
6428 $hash_parent_param =
6429 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6432 # read commitdiff
6433 my $fd;
6434 my @difftree;
6435 if ($format eq 'html') {
6436 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6437 "--no-commit-id", "--patch-with-raw", "--full-index",
6438 $hash_parent_param, $hash, "--"
6439 or die_error(500, "Open git-diff-tree failed");
6441 while (my $line = <$fd>) {
6442 chomp $line;
6443 # empty line ends raw part of diff-tree output
6444 last unless $line;
6445 push @difftree, scalar parse_difftree_raw_line($line);
6448 } elsif ($format eq 'plain') {
6449 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6450 '-p', $hash_parent_param, $hash, "--"
6451 or die_error(500, "Open git-diff-tree failed");
6452 } elsif ($format eq 'patch') {
6453 # For commit ranges, we limit the output to the number of
6454 # patches specified in the 'patches' feature.
6455 # For single commits, we limit the output to a single patch,
6456 # diverging from the git-format-patch default.
6457 my @commit_spec = ();
6458 if ($hash_parent) {
6459 if ($patch_max > 0) {
6460 push @commit_spec, "-$patch_max";
6462 push @commit_spec, '-n', "$hash_parent..$hash";
6463 } else {
6464 if ($params{-single}) {
6465 push @commit_spec, '-1';
6466 } else {
6467 if ($patch_max > 0) {
6468 push @commit_spec, "-$patch_max";
6470 push @commit_spec, "-n";
6472 push @commit_spec, '--root', $hash;
6474 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6475 '--encoding=utf8', '--stdout', @commit_spec
6476 or die_error(500, "Open git-format-patch failed");
6477 } else {
6478 die_error(400, "Unknown commitdiff format");
6481 # non-textual hash id's can be cached
6482 my $expires;
6483 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6484 $expires = "+1d";
6487 # write commit message
6488 if ($format eq 'html') {
6489 my $refs = git_get_references();
6490 my $ref = format_ref_marker($refs, $co{'id'});
6492 git_header_html(undef, $expires);
6493 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6494 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6495 print "<div class=\"title_text\">\n" .
6496 "<table class=\"object_header\">\n";
6497 git_print_authorship_rows(\%co);
6498 print "</table>".
6499 "</div>\n";
6500 print "<div class=\"page_body\">\n";
6501 if (@{$co{'comment'}} > 1) {
6502 print "<div class=\"log\">\n";
6503 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6504 print "</div>\n"; # class="log"
6507 } elsif ($format eq 'plain') {
6508 my $refs = git_get_references("tags");
6509 my $tagname = git_get_rev_name_tags($hash);
6510 my $filename = basename($project) . "-$hash.patch";
6512 print $cgi->header(
6513 -type => 'text/plain',
6514 -charset => 'utf-8',
6515 -expires => $expires,
6516 -content_disposition => 'inline; filename="' . "$filename" . '"');
6517 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6518 print "From: " . to_utf8($co{'author'}) . "\n";
6519 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6520 print "Subject: " . to_utf8($co{'title'}) . "\n";
6522 print "X-Git-Tag: $tagname\n" if $tagname;
6523 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6525 foreach my $line (@{$co{'comment'}}) {
6526 print to_utf8($line) . "\n";
6528 print "---\n\n";
6529 } elsif ($format eq 'patch') {
6530 my $filename = basename($project) . "-$hash.patch";
6532 print $cgi->header(
6533 -type => 'text/plain',
6534 -charset => 'utf-8',
6535 -expires => $expires,
6536 -content_disposition => 'inline; filename="' . "$filename" . '"');
6539 # write patch
6540 if ($format eq 'html') {
6541 my $use_parents = !defined $hash_parent ||
6542 $hash_parent eq '-c' || $hash_parent eq '--cc';
6543 git_difftree_body(\@difftree, $hash,
6544 $use_parents ? @{$co{'parents'}} : $hash_parent);
6545 print "<br/>\n";
6547 git_patchset_body($fd, \@difftree, $hash,
6548 $use_parents ? @{$co{'parents'}} : $hash_parent);
6549 close $fd;
6550 print "</div>\n"; # class="page_body"
6551 git_footer_html();
6553 } elsif ($format eq 'plain') {
6554 local $/ = undef;
6555 print <$fd>;
6556 close $fd
6557 or print "Reading git-diff-tree failed\n";
6558 } elsif ($format eq 'patch') {
6559 local $/ = undef;
6560 print <$fd>;
6561 close $fd
6562 or print "Reading git-format-patch failed\n";
6566 sub git_commitdiff_plain {
6567 git_commitdiff(-format => 'plain');
6570 # format-patch-style patches
6571 sub git_patch {
6572 git_commitdiff(-format => 'patch', -single => 1);
6575 sub git_patches {
6576 git_commitdiff(-format => 'patch');
6579 sub git_history {
6580 git_log_generic('history', \&git_history_body,
6581 $hash_base, $hash_parent_base,
6582 $file_name, $hash);
6585 sub git_search {
6586 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6587 if (!defined $searchtext) {
6588 die_error(400, "Text field is empty");
6590 if (!defined $hash) {
6591 $hash = git_get_head_hash($project);
6593 my %co = parse_commit($hash);
6594 if (!%co) {
6595 die_error(404, "Unknown commit object");
6597 if (!defined $page) {
6598 $page = 0;
6601 $searchtype ||= 'commit';
6602 if ($searchtype eq 'pickaxe') {
6603 # pickaxe may take all resources of your box and run for several minutes
6604 # with every query - so decide by yourself how public you make this feature
6605 gitweb_check_feature('pickaxe')
6606 or die_error(403, "Pickaxe is disabled");
6608 if ($searchtype eq 'grep') {
6609 gitweb_check_feature('grep')
6610 or die_error(403, "Grep is disabled");
6613 git_header_html();
6615 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6616 my $greptype;
6617 if ($searchtype eq 'commit') {
6618 $greptype = "--grep=";
6619 } elsif ($searchtype eq 'author') {
6620 $greptype = "--author=";
6621 } elsif ($searchtype eq 'committer') {
6622 $greptype = "--committer=";
6624 $greptype .= $searchtext;
6625 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6626 $greptype, '--regexp-ignore-case',
6627 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6629 my $paging_nav = '';
6630 if ($page > 0) {
6631 $paging_nav .=
6632 $cgi->a({-href => href(action=>"search", hash=>$hash,
6633 searchtext=>$searchtext,
6634 searchtype=>$searchtype)},
6635 "first");
6636 $paging_nav .= " &sdot; " .
6637 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6638 -accesskey => "p", -title => "Alt-p"}, "prev");
6639 } else {
6640 $paging_nav .= "first";
6641 $paging_nav .= " &sdot; prev";
6643 my $next_link = '';
6644 if ($#commitlist >= 100) {
6645 $next_link =
6646 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6647 -accesskey => "n", -title => "Alt-n"}, "next");
6648 $paging_nav .= " &sdot; $next_link";
6649 } else {
6650 $paging_nav .= " &sdot; next";
6653 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6654 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6655 if ($page == 0 && !@commitlist) {
6656 print "<p>No match.</p>\n";
6657 } else {
6658 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6662 if ($searchtype eq 'pickaxe') {
6663 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6664 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6666 print "<table class=\"pickaxe search\">\n";
6667 my $alternate = 1;
6668 local $/ = "\n";
6669 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6670 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6671 ($search_use_regexp ? '--pickaxe-regex' : ());
6672 undef %co;
6673 my @files;
6674 while (my $line = <$fd>) {
6675 chomp $line;
6676 next unless $line;
6678 my %set = parse_difftree_raw_line($line);
6679 if (defined $set{'commit'}) {
6680 # finish previous commit
6681 if (%co) {
6682 print "</td>\n" .
6683 "<td class=\"link\">" .
6684 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6685 " | " .
6686 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6687 print "</td>\n" .
6688 "</tr>\n";
6691 if ($alternate) {
6692 print "<tr class=\"dark\">\n";
6693 } else {
6694 print "<tr class=\"light\">\n";
6696 $alternate ^= 1;
6697 %co = parse_commit($set{'commit'});
6698 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6699 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6700 "<td><i>$author</i></td>\n" .
6701 "<td>" .
6702 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6703 -class => "list subject"},
6704 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6705 } elsif (defined $set{'to_id'}) {
6706 next if ($set{'to_id'} =~ m/^0{40}$/);
6708 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6709 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6710 -class => "list"},
6711 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6712 "<br/>\n";
6715 close $fd;
6717 # finish last commit (warning: repetition!)
6718 if (%co) {
6719 print "</td>\n" .
6720 "<td class=\"link\">" .
6721 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6722 " | " .
6723 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6724 print "</td>\n" .
6725 "</tr>\n";
6728 print "</table>\n";
6731 if ($searchtype eq 'grep') {
6732 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6733 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6735 print "<table class=\"grep_search\">\n";
6736 my $alternate = 1;
6737 my $matches = 0;
6738 local $/ = "\n";
6739 open my $fd, "-|", git_cmd(), 'grep', '-n',
6740 $search_use_regexp ? ('-E', '-i') : '-F',
6741 $searchtext, $co{'tree'};
6742 my $lastfile = '';
6743 while (my $line = <$fd>) {
6744 chomp $line;
6745 my ($file, $lno, $ltext, $binary);
6746 last if ($matches++ > 1000);
6747 if ($line =~ /^Binary file (.+) matches$/) {
6748 $file = $1;
6749 $binary = 1;
6750 } else {
6751 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6753 if ($file ne $lastfile) {
6754 $lastfile and print "</td></tr>\n";
6755 if ($alternate++) {
6756 print "<tr class=\"dark\">\n";
6757 } else {
6758 print "<tr class=\"light\">\n";
6760 print "<td class=\"list\">".
6761 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6762 file_name=>"$file"),
6763 -class => "list"}, esc_path($file));
6764 print "</td><td>\n";
6765 $lastfile = $file;
6767 if ($binary) {
6768 print "<div class=\"binary\">Binary file</div>\n";
6769 } else {
6770 $ltext = untabify($ltext);
6771 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6772 $ltext = esc_html($1, -nbsp=>1);
6773 $ltext .= '<span class="match">';
6774 $ltext .= esc_html($2, -nbsp=>1);
6775 $ltext .= '</span>';
6776 $ltext .= esc_html($3, -nbsp=>1);
6777 } else {
6778 $ltext = esc_html($ltext, -nbsp=>1);
6780 print "<div class=\"pre\">" .
6781 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6782 file_name=>"$file").'#l'.$lno,
6783 -class => "linenr"}, sprintf('%4i', $lno))
6784 . ' ' . $ltext . "</div>\n";
6787 if ($lastfile) {
6788 print "</td></tr>\n";
6789 if ($matches > 1000) {
6790 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6792 } else {
6793 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6795 close $fd;
6797 print "</table>\n";
6799 git_footer_html();
6802 sub git_search_help {
6803 git_header_html();
6804 git_print_page_nav('','', $hash,$hash,$hash);
6805 print <<EOT;
6806 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6807 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6808 the pattern entered is recognized as the POSIX extended
6809 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6810 insensitive).</p>
6811 <dl>
6812 <dt><b>commit</b></dt>
6813 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6815 my $have_grep = gitweb_check_feature('grep');
6816 if ($have_grep) {
6817 print <<EOT;
6818 <dt><b>grep</b></dt>
6819 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6820 a different one) are searched for the given pattern. On large trees, this search can take
6821 a while and put some strain on the server, so please use it with some consideration. Note that
6822 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6823 case-sensitive.</dd>
6826 print <<EOT;
6827 <dt><b>author</b></dt>
6828 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6829 <dt><b>committer</b></dt>
6830 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6832 my $have_pickaxe = gitweb_check_feature('pickaxe');
6833 if ($have_pickaxe) {
6834 print <<EOT;
6835 <dt><b>pickaxe</b></dt>
6836 <dd>All commits that caused the string to appear or disappear from any file (changes that
6837 added, removed or "modified" the string) will be listed. This search can take a while and
6838 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6839 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6842 print "</dl>\n";
6843 git_footer_html();
6846 sub git_shortlog {
6847 git_log_generic('shortlog', \&git_shortlog_body,
6848 $hash, $hash_parent);
6851 ## ......................................................................
6852 ## feeds (RSS, Atom; OPML)
6854 sub git_feed {
6855 my $format = shift || 'atom';
6856 my $have_blame = gitweb_check_feature('blame');
6858 # Atom: http://www.atomenabled.org/developers/syndication/
6859 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6860 if ($format ne 'rss' && $format ne 'atom') {
6861 die_error(400, "Unknown web feed format");
6864 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6865 my $head = $hash || 'HEAD';
6866 my @commitlist = parse_commits($head, 150, 0, $file_name);
6868 my %latest_commit;
6869 my %latest_date;
6870 my $content_type = "application/$format+xml";
6871 if (defined $cgi->http('HTTP_ACCEPT') &&
6872 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6873 # browser (feed reader) prefers text/xml
6874 $content_type = 'text/xml';
6876 if (defined($commitlist[0])) {
6877 %latest_commit = %{$commitlist[0]};
6878 my $latest_epoch = $latest_commit{'committer_epoch'};
6879 %latest_date = parse_date($latest_epoch);
6880 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6881 if (defined $if_modified) {
6882 my $since;
6883 if (eval { require HTTP::Date; 1; }) {
6884 $since = HTTP::Date::str2time($if_modified);
6885 } elsif (eval { require Time::ParseDate; 1; }) {
6886 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6888 if (defined $since && $latest_epoch <= $since) {
6889 print $cgi->header(
6890 -type => $content_type,
6891 -charset => 'utf-8',
6892 -last_modified => $latest_date{'rfc2822'},
6893 -status => '304 Not Modified');
6894 return;
6897 print $cgi->header(
6898 -type => $content_type,
6899 -charset => 'utf-8',
6900 -last_modified => $latest_date{'rfc2822'});
6901 } else {
6902 print $cgi->header(
6903 -type => $content_type,
6904 -charset => 'utf-8');
6907 # Optimization: skip generating the body if client asks only
6908 # for Last-Modified date.
6909 return if ($cgi->request_method() eq 'HEAD');
6911 # header variables
6912 my $title = "$site_name - $project/$action";
6913 my $feed_type = 'log';
6914 if (defined $hash) {
6915 $title .= " - '$hash'";
6916 $feed_type = 'branch log';
6917 if (defined $file_name) {
6918 $title .= " :: $file_name";
6919 $feed_type = 'history';
6921 } elsif (defined $file_name) {
6922 $title .= " - $file_name";
6923 $feed_type = 'history';
6925 $title .= " $feed_type";
6926 my $descr = git_get_project_description($project);
6927 if (defined $descr) {
6928 $descr = esc_html($descr);
6929 } else {
6930 $descr = "$project " .
6931 ($format eq 'rss' ? 'RSS' : 'Atom') .
6932 " feed";
6934 my $owner = git_get_project_owner($project);
6935 $owner = esc_html($owner);
6937 #header
6938 my $alt_url;
6939 if (defined $file_name) {
6940 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6941 } elsif (defined $hash) {
6942 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6943 } else {
6944 $alt_url = href(-full=>1, action=>"summary");
6946 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6947 if ($format eq 'rss') {
6948 print <<XML;
6949 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6950 <channel>
6952 print "<title>$title</title>\n" .
6953 "<link>$alt_url</link>\n" .
6954 "<description>$descr</description>\n" .
6955 "<language>en</language>\n" .
6956 # project owner is responsible for 'editorial' content
6957 "<managingEditor>$owner</managingEditor>\n";
6958 if (defined $logo || defined $favicon) {
6959 # prefer the logo to the favicon, since RSS
6960 # doesn't allow both
6961 my $img = esc_url($logo || $favicon);
6962 print "<image>\n" .
6963 "<url>$img</url>\n" .
6964 "<title>$title</title>\n" .
6965 "<link>$alt_url</link>\n" .
6966 "</image>\n";
6968 if (%latest_date) {
6969 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6970 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6972 print "<generator>gitweb v.$version/$git_version</generator>\n";
6973 } elsif ($format eq 'atom') {
6974 print <<XML;
6975 <feed xmlns="http://www.w3.org/2005/Atom">
6977 print "<title>$title</title>\n" .
6978 "<subtitle>$descr</subtitle>\n" .
6979 '<link rel="alternate" type="text/html" href="' .
6980 $alt_url . '" />' . "\n" .
6981 '<link rel="self" type="' . $content_type . '" href="' .
6982 $cgi->self_url() . '" />' . "\n" .
6983 "<id>" . href(-full=>1) . "</id>\n" .
6984 # use project owner for feed author
6985 "<author><name>$owner</name></author>\n";
6986 if (defined $favicon) {
6987 print "<icon>" . esc_url($favicon) . "</icon>\n";
6989 if (defined $logo_url) {
6990 # not twice as wide as tall: 72 x 27 pixels
6991 print "<logo>" . esc_url($logo) . "</logo>\n";
6993 if (! %latest_date) {
6994 # dummy date to keep the feed valid until commits trickle in:
6995 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6996 } else {
6997 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6999 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7002 # contents
7003 for (my $i = 0; $i <= $#commitlist; $i++) {
7004 my %co = %{$commitlist[$i]};
7005 my $commit = $co{'id'};
7006 # we read 150, we always show 30 and the ones more recent than 48 hours
7007 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7008 last;
7010 my %cd = parse_date($co{'author_epoch'});
7012 # get list of changed files
7013 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7014 $co{'parent'} || "--root",
7015 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7016 or next;
7017 my @difftree = map { chomp; $_ } <$fd>;
7018 close $fd
7019 or next;
7021 # print element (entry, item)
7022 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7023 if ($format eq 'rss') {
7024 print "<item>\n" .
7025 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7026 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7027 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7028 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7029 "<link>$co_url</link>\n" .
7030 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7031 "<content:encoded>" .
7032 "<![CDATA[\n";
7033 } elsif ($format eq 'atom') {
7034 print "<entry>\n" .
7035 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7036 "<updated>$cd{'iso-8601'}</updated>\n" .
7037 "<author>\n" .
7038 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7039 if ($co{'author_email'}) {
7040 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7042 print "</author>\n" .
7043 # use committer for contributor
7044 "<contributor>\n" .
7045 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7046 if ($co{'committer_email'}) {
7047 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7049 print "</contributor>\n" .
7050 "<published>$cd{'iso-8601'}</published>\n" .
7051 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7052 "<id>$co_url</id>\n" .
7053 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7054 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7056 my $comment = $co{'comment'};
7057 print "<pre>\n";
7058 foreach my $line (@$comment) {
7059 $line = esc_html($line);
7060 print "$line\n";
7062 print "</pre><ul>\n";
7063 foreach my $difftree_line (@difftree) {
7064 my %difftree = parse_difftree_raw_line($difftree_line);
7065 next if !$difftree{'from_id'};
7067 my $file = $difftree{'file'} || $difftree{'to_file'};
7069 print "<li>" .
7070 "[" .
7071 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7072 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7073 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7074 file_name=>$file, file_parent=>$difftree{'from_file'}),
7075 -title => "diff"}, 'D');
7076 if ($have_blame) {
7077 print $cgi->a({-href => href(-full=>1, action=>"blame",
7078 file_name=>$file, hash_base=>$commit),
7079 -title => "blame"}, 'B');
7081 # if this is not a feed of a file history
7082 if (!defined $file_name || $file_name ne $file) {
7083 print $cgi->a({-href => href(-full=>1, action=>"history",
7084 file_name=>$file, hash=>$commit),
7085 -title => "history"}, 'H');
7087 $file = esc_path($file);
7088 print "] ".
7089 "$file</li>\n";
7091 if ($format eq 'rss') {
7092 print "</ul>]]>\n" .
7093 "</content:encoded>\n" .
7094 "</item>\n";
7095 } elsif ($format eq 'atom') {
7096 print "</ul>\n</div>\n" .
7097 "</content>\n" .
7098 "</entry>\n";
7102 # end of feed
7103 if ($format eq 'rss') {
7104 print "</channel>\n</rss>\n";
7105 } elsif ($format eq 'atom') {
7106 print "</feed>\n";
7110 sub git_rss {
7111 git_feed('rss');
7114 sub git_atom {
7115 git_feed('atom');
7118 sub git_opml {
7119 my @list = git_get_projects_list();
7121 print $cgi->header(
7122 -type => 'text/xml',
7123 -charset => 'utf-8',
7124 -content_disposition => 'inline; filename="opml.xml"');
7126 print <<XML;
7127 <?xml version="1.0" encoding="utf-8"?>
7128 <opml version="1.0">
7129 <head>
7130 <title>$site_name OPML Export</title>
7131 </head>
7132 <body>
7133 <outline text="git RSS feeds">
7136 foreach my $pr (@list) {
7137 my %proj = %$pr;
7138 my $head = git_get_head_hash($proj{'path'});
7139 if (!defined $head) {
7140 next;
7142 $git_dir = "$projectroot/$proj{'path'}";
7143 my %co = parse_commit($head);
7144 if (!%co) {
7145 next;
7148 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7149 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7150 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7151 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7153 print <<XML;
7154 </outline>
7155 </body>
7156 </opml>