submodule: Use cat instead of echo to avoid DOS line-endings
[git/dscho.git] / gitweb / gitweb.perl
blob6e02f179c01d82ce778ac07cedc00eb13780b902
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;
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
19 use File::Basename qw(basename);
20 use Time::HiRes qw(gettimeofday tv_interval);
21 binmode STDOUT, ':utf8';
23 our $t0 = [ gettimeofday() ];
24 our $number_of_git_cmds = 0;
26 BEGIN {
27 CGI->compile() if $ENV{'MOD_PERL'};
30 our $version = "++GIT_VERSION++";
32 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
33 sub evaluate_uri {
34 our $cgi;
36 our $my_url = $cgi->url();
37 our $my_uri = $cgi->url(-absolute => 1);
39 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
40 # needed and used only for URLs with nonempty PATH_INFO
41 our $base_url = $my_url;
43 # When the script is used as DirectoryIndex, the URL does not contain the name
44 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
45 # have to do it ourselves. We make $path_info global because it's also used
46 # later on.
48 # Another issue with the script being the DirectoryIndex is that the resulting
49 # $my_url data is not the full script URL: this is good, because we want
50 # generated links to keep implying the script name if it wasn't explicitly
51 # indicated in the URL we're handling, but it means that $my_url cannot be used
52 # as base URL.
53 # Therefore, if we needed to strip PATH_INFO, then we know that we have
54 # to build the base URL ourselves:
55 our $path_info = $ENV{"PATH_INFO"};
56 if ($path_info) {
57 if ($my_url =~ s,\Q$path_info\E$,, &&
58 $my_uri =~ s,\Q$path_info\E$,, &&
59 defined $ENV{'SCRIPT_NAME'}) {
60 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
64 # target of the home link on top of all pages
65 our $home_link = $my_uri || "/";
68 # core git executable to use
69 # this can just be "git" if your webserver has a sensible PATH
70 our $GIT = "++GIT_BINDIR++/git";
72 # absolute fs-path which will be prepended to the project path
73 #our $projectroot = "/pub/scm";
74 our $projectroot = "++GITWEB_PROJECTROOT++";
76 # fs traversing limit for getting project list
77 # the number is relative to the projectroot
78 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
80 # string of the home link on top of all pages
81 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
83 # name of your site or organization to appear in page titles
84 # replace this with something more descriptive for clearer bookmarks
85 our $site_name = "++GITWEB_SITENAME++"
86 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
88 # filename of html text to include at top of each page
89 our $site_header = "++GITWEB_SITE_HEADER++";
90 # html text to include at home page
91 our $home_text = "++GITWEB_HOMETEXT++";
92 # filename of html text to include at bottom of each page
93 our $site_footer = "++GITWEB_SITE_FOOTER++";
95 # URI of stylesheets
96 our @stylesheets = ("++GITWEB_CSS++");
97 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
98 our $stylesheet = undef;
99 # URI of GIT logo (72x27 size)
100 our $logo = "++GITWEB_LOGO++";
101 # URI of GIT favicon, assumed to be image/png type
102 our $favicon = "++GITWEB_FAVICON++";
103 # URI of gitweb.js (JavaScript code for gitweb)
104 our $javascript = "++GITWEB_JS++";
106 # URI and label (title) of GIT logo link
107 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
108 #our $logo_label = "git documentation";
109 our $logo_url = "http://git-scm.com/";
110 our $logo_label = "git homepage";
112 # source of projects list
113 our $projects_list = "++GITWEB_LIST++";
115 # the width (in characters) of the projects list "Description" column
116 our $projects_list_description_width = 25;
118 # group projects by category on the projects list
119 # (enabled if this variable evaluates to true)
120 our $projects_list_group_categories = 0;
122 # default category if none specified
123 # (leave the empty string for no category)
124 our $project_list_default_category = "";
126 # default order of projects list
127 # valid values are none, project, descr, owner, and age
128 our $default_projects_order = "project";
130 # show repository only if this file exists
131 # (only effective if this variable evaluates to true)
132 our $export_ok = "++GITWEB_EXPORT_OK++";
134 # show repository only if this subroutine returns true
135 # when given the path to the project, for example:
136 # sub { return -e "$_[0]/git-daemon-export-ok"; }
137 our $export_auth_hook = undef;
139 # only allow viewing of repositories also shown on the overview page
140 our $strict_export = "++GITWEB_STRICT_EXPORT++";
142 # list of git base URLs used for URL to where fetch project from,
143 # i.e. full URL is "$git_base_url/$project"
144 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
146 # default blob_plain mimetype and default charset for text/plain blob
147 our $default_blob_plain_mimetype = 'text/plain';
148 our $default_text_plain_charset = undef;
150 # file to use for guessing MIME types before trying /etc/mime.types
151 # (relative to the current git repository)
152 our $mimetypes_file = undef;
154 # assume this charset if line contains non-UTF-8 characters;
155 # it should be valid encoding (see Encoding::Supported(3pm) for list),
156 # for which encoding all byte sequences are valid, for example
157 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
158 # could be even 'utf-8' for the old behavior)
159 our $fallback_encoding = 'latin1';
161 # rename detection options for git-diff and git-diff-tree
162 # - default is '-M', with the cost proportional to
163 # (number of removed files) * (number of new files).
164 # - more costly is '-C' (which implies '-M'), with the cost proportional to
165 # (number of changed files + number of removed files) * (number of new files)
166 # - even more costly is '-C', '--find-copies-harder' with cost
167 # (number of files in the original tree) * (number of new files)
168 # - one might want to include '-B' option, e.g. '-B', '-M'
169 our @diff_opts = ('-M'); # taken from git_commit
171 # Disables features that would allow repository owners to inject script into
172 # the gitweb domain.
173 our $prevent_xss = 0;
175 # Path to the highlight executable to use (must be the one from
176 # http://www.andre-simon.de due to assumptions about parameters and output).
177 # Useful if highlight is not installed on your webserver's PATH.
178 # [Default: highlight]
179 our $highlight_bin = "++HIGHLIGHT_BIN++";
181 # information about snapshot formats that gitweb is capable of serving
182 our %known_snapshot_formats = (
183 # name => {
184 # 'display' => display name,
185 # 'type' => mime type,
186 # 'suffix' => filename suffix,
187 # 'format' => --format for git-archive,
188 # 'compressor' => [compressor command and arguments]
189 # (array reference, optional)
190 # 'disabled' => boolean (optional)}
192 'tgz' => {
193 'display' => 'tar.gz',
194 'type' => 'application/x-gzip',
195 'suffix' => '.tar.gz',
196 'format' => 'tar',
197 'compressor' => ['gzip', '-n']},
199 'tbz2' => {
200 'display' => 'tar.bz2',
201 'type' => 'application/x-bzip2',
202 'suffix' => '.tar.bz2',
203 'format' => 'tar',
204 'compressor' => ['bzip2']},
206 'txz' => {
207 'display' => 'tar.xz',
208 'type' => 'application/x-xz',
209 'suffix' => '.tar.xz',
210 'format' => 'tar',
211 'compressor' => ['xz'],
212 'disabled' => 1},
214 'zip' => {
215 'display' => 'zip',
216 'type' => 'application/x-zip',
217 'suffix' => '.zip',
218 'format' => 'zip'},
221 # Aliases so we understand old gitweb.snapshot values in repository
222 # configuration.
223 our %known_snapshot_format_aliases = (
224 'gzip' => 'tgz',
225 'bzip2' => 'tbz2',
226 'xz' => 'txz',
228 # backward compatibility: legacy gitweb config support
229 'x-gzip' => undef, 'gz' => undef,
230 'x-bzip2' => undef, 'bz2' => undef,
231 'x-zip' => undef, '' => undef,
234 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
235 # are changed, it may be appropriate to change these values too via
236 # $GITWEB_CONFIG.
237 our %avatar_size = (
238 'default' => 16,
239 'double' => 32
242 # Used to set the maximum load that we will still respond to gitweb queries.
243 # If server load exceed this value then return "503 server busy" error.
244 # If gitweb cannot determined server load, it is taken to be 0.
245 # Leave it undefined (or set to 'undef') to turn off load checking.
246 our $maxload = 300;
248 # configuration for 'highlight' (http://www.andre-simon.de/)
249 # match by basename
250 our %highlight_basename = (
251 #'Program' => 'py',
252 #'Library' => 'py',
253 'SConstruct' => 'py', # SCons equivalent of Makefile
254 'Makefile' => 'make',
256 # match by extension
257 our %highlight_ext = (
258 # main extensions, defining name of syntax;
259 # see files in /usr/share/highlight/langDefs/ directory
260 map { $_ => $_ }
261 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make),
262 # alternate extensions, see /etc/highlight/filetypes.conf
263 'h' => 'c',
264 map { $_ => 'sh' } qw(bash zsh ksh),
265 map { $_ => 'cpp' } qw(cxx c++ cc),
266 map { $_ => 'php' } qw(php3 php4 php5 phps),
267 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
268 map { $_ => 'make'} qw(mak mk),
269 map { $_ => 'xml' } qw(xhtml html htm),
272 # You define site-wide feature defaults here; override them with
273 # $GITWEB_CONFIG as necessary.
274 our %feature = (
275 # feature => {
276 # 'sub' => feature-sub (subroutine),
277 # 'override' => allow-override (boolean),
278 # 'default' => [ default options...] (array reference)}
280 # if feature is overridable (it means that allow-override has true value),
281 # then feature-sub will be called with default options as parameters;
282 # return value of feature-sub indicates if to enable specified feature
284 # if there is no 'sub' key (no feature-sub), then feature cannot be
285 # overridden
287 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
288 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
289 # is enabled
291 # Enable the 'blame' blob view, showing the last commit that modified
292 # each line in the file. This can be very CPU-intensive.
294 # To enable system wide have in $GITWEB_CONFIG
295 # $feature{'blame'}{'default'} = [1];
296 # To have project specific config enable override in $GITWEB_CONFIG
297 # $feature{'blame'}{'override'} = 1;
298 # and in project config gitweb.blame = 0|1;
299 'blame' => {
300 'sub' => sub { feature_bool('blame', @_) },
301 'override' => 0,
302 'default' => [0]},
304 # Enable the 'snapshot' link, providing a compressed archive of any
305 # tree. This can potentially generate high traffic if you have large
306 # project.
308 # Value is a list of formats defined in %known_snapshot_formats that
309 # you wish to offer.
310 # To disable system wide have in $GITWEB_CONFIG
311 # $feature{'snapshot'}{'default'} = [];
312 # To have project specific config enable override in $GITWEB_CONFIG
313 # $feature{'snapshot'}{'override'} = 1;
314 # and in project config, a comma-separated list of formats or "none"
315 # to disable. Example: gitweb.snapshot = tbz2,zip;
316 'snapshot' => {
317 'sub' => \&feature_snapshot,
318 'override' => 0,
319 'default' => ['tgz']},
321 # Enable text search, which will list the commits which match author,
322 # committer or commit text to a given string. Enabled by default.
323 # Project specific override is not supported.
325 # Note that this controls all search features, which means that if
326 # it is disabled, then 'grep' and 'pickaxe' search would also be
327 # disabled.
328 'search' => {
329 'override' => 0,
330 'default' => [1]},
332 # Enable grep search, which will list the files in currently selected
333 # tree containing the given string. Enabled by default. This can be
334 # potentially CPU-intensive, of course.
335 # Note that you need to have 'search' feature enabled too.
337 # To enable system wide have in $GITWEB_CONFIG
338 # $feature{'grep'}{'default'} = [1];
339 # To have project specific config enable override in $GITWEB_CONFIG
340 # $feature{'grep'}{'override'} = 1;
341 # and in project config gitweb.grep = 0|1;
342 'grep' => {
343 'sub' => sub { feature_bool('grep', @_) },
344 'override' => 0,
345 'default' => [1]},
347 # Enable the pickaxe search, which will list the commits that modified
348 # a given string in a file. This can be practical and quite faster
349 # alternative to 'blame', but still potentially CPU-intensive.
350 # Note that you need to have 'search' feature enabled too.
352 # To enable system wide have in $GITWEB_CONFIG
353 # $feature{'pickaxe'}{'default'} = [1];
354 # To have project specific config enable override in $GITWEB_CONFIG
355 # $feature{'pickaxe'}{'override'} = 1;
356 # and in project config gitweb.pickaxe = 0|1;
357 'pickaxe' => {
358 'sub' => sub { feature_bool('pickaxe', @_) },
359 'override' => 0,
360 'default' => [1]},
362 # Enable showing size of blobs in a 'tree' view, in a separate
363 # column, similar to what 'ls -l' does. This cost a bit of IO.
365 # To disable system wide have in $GITWEB_CONFIG
366 # $feature{'show-sizes'}{'default'} = [0];
367 # To have project specific config enable override in $GITWEB_CONFIG
368 # $feature{'show-sizes'}{'override'} = 1;
369 # and in project config gitweb.showsizes = 0|1;
370 'show-sizes' => {
371 'sub' => sub { feature_bool('showsizes', @_) },
372 'override' => 0,
373 'default' => [1]},
375 # Make gitweb use an alternative format of the URLs which can be
376 # more readable and natural-looking: project name is embedded
377 # directly in the path and the query string contains other
378 # auxiliary information. All gitweb installations recognize
379 # URL in either format; this configures in which formats gitweb
380 # generates links.
382 # To enable system wide have in $GITWEB_CONFIG
383 # $feature{'pathinfo'}{'default'} = [1];
384 # Project specific override is not supported.
386 # Note that you will need to change the default location of CSS,
387 # favicon, logo and possibly other files to an absolute URL. Also,
388 # if gitweb.cgi serves as your indexfile, you will need to force
389 # $my_uri to contain the script name in your $GITWEB_CONFIG.
390 'pathinfo' => {
391 'override' => 0,
392 'default' => [0]},
394 # Make gitweb consider projects in project root subdirectories
395 # to be forks of existing projects. Given project $projname.git,
396 # projects matching $projname/*.git will not be shown in the main
397 # projects list, instead a '+' mark will be added to $projname
398 # there and a 'forks' view will be enabled for the project, listing
399 # all the forks. If project list is taken from a file, forks have
400 # to be listed after the main project.
402 # To enable system wide have in $GITWEB_CONFIG
403 # $feature{'forks'}{'default'} = [1];
404 # Project specific override is not supported.
405 'forks' => {
406 'override' => 0,
407 'default' => [0]},
409 # Insert custom links to the action bar of all project pages.
410 # This enables you mainly to link to third-party scripts integrating
411 # into gitweb; e.g. git-browser for graphical history representation
412 # or custom web-based repository administration interface.
414 # The 'default' value consists of a list of triplets in the form
415 # (label, link, position) where position is the label after which
416 # to insert the link and link is a format string where %n expands
417 # to the project name, %f to the project path within the filesystem,
418 # %h to the current hash (h gitweb parameter) and %b to the current
419 # hash base (hb gitweb parameter); %% expands to %.
421 # To enable system wide have in $GITWEB_CONFIG e.g.
422 # $feature{'actions'}{'default'} = [('graphiclog',
423 # '/git-browser/by-commit.html?r=%n', 'summary')];
424 # Project specific override is not supported.
425 'actions' => {
426 'override' => 0,
427 'default' => []},
429 # Allow gitweb scan project content tags of project repository,
430 # and display the popular Web 2.0-ish "tag cloud" near the projects
431 # list. Note that this is something COMPLETELY different from the
432 # normal Git tags.
434 # gitweb by itself can show existing tags, but it does not handle
435 # tagging itself; you need to do it externally, outside gitweb.
436 # The format is described in git_get_project_ctags() subroutine.
437 # You may want to install the HTML::TagCloud Perl module to get
438 # a pretty tag cloud instead of just a list of tags.
440 # To enable system wide have in $GITWEB_CONFIG
441 # $feature{'ctags'}{'default'} = [1];
442 # Project specific override is not supported.
444 # In the future whether ctags editing is enabled might depend
445 # on the value, but using 1 should always mean no editing of ctags.
446 'ctags' => {
447 'override' => 0,
448 'default' => [0]},
450 # The maximum number of patches in a patchset generated in patch
451 # view. Set this to 0 or undef to disable patch view, or to a
452 # negative number to remove any limit.
454 # To disable system wide have in $GITWEB_CONFIG
455 # $feature{'patches'}{'default'} = [0];
456 # To have project specific config enable override in $GITWEB_CONFIG
457 # $feature{'patches'}{'override'} = 1;
458 # and in project config gitweb.patches = 0|n;
459 # where n is the maximum number of patches allowed in a patchset.
460 'patches' => {
461 'sub' => \&feature_patches,
462 'override' => 0,
463 'default' => [16]},
465 # Avatar support. When this feature is enabled, views such as
466 # shortlog or commit will display an avatar associated with
467 # the email of the committer(s) and/or author(s).
469 # Currently available providers are gravatar and picon.
470 # If an unknown provider is specified, the feature is disabled.
472 # Gravatar depends on Digest::MD5.
473 # Picon currently relies on the indiana.edu database.
475 # To enable system wide have in $GITWEB_CONFIG
476 # $feature{'avatar'}{'default'} = ['<provider>'];
477 # where <provider> is either gravatar or picon.
478 # To have project specific config enable override in $GITWEB_CONFIG
479 # $feature{'avatar'}{'override'} = 1;
480 # and in project config gitweb.avatar = <provider>;
481 'avatar' => {
482 'sub' => \&feature_avatar,
483 'override' => 0,
484 'default' => ['']},
486 # Enable displaying how much time and how many git commands
487 # it took to generate and display page. Disabled by default.
488 # Project specific override is not supported.
489 'timed' => {
490 'override' => 0,
491 'default' => [0]},
493 # Enable turning some links into links to actions which require
494 # JavaScript to run (like 'blame_incremental'). Not enabled by
495 # default. Project specific override is currently not supported.
496 'javascript-actions' => {
497 'override' => 0,
498 'default' => [0]},
500 # Enable and configure ability to change common timezone for dates
501 # in gitweb output via JavaScript. Enabled by default.
502 # Project specific override is not supported.
503 'javascript-timezone' => {
504 'override' => 0,
505 'default' => [
506 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
507 # or undef to turn off this feature
508 'gitweb_tz', # name of cookie where to store selected timezone
509 'datetime', # CSS class used to mark up dates for manipulation
512 # Syntax highlighting support. This is based on Daniel Svensson's
513 # and Sham Chukoury's work in gitweb-xmms2.git.
514 # It requires the 'highlight' program present in $PATH,
515 # and therefore is disabled by default.
517 # To enable system wide have in $GITWEB_CONFIG
518 # $feature{'highlight'}{'default'} = [1];
520 'highlight' => {
521 'sub' => sub { feature_bool('highlight', @_) },
522 'override' => 0,
523 'default' => [0]},
525 # Enable displaying of remote heads in the heads list
527 # To enable system wide have in $GITWEB_CONFIG
528 # $feature{'remote_heads'}{'default'} = [1];
529 # To have project specific config enable override in $GITWEB_CONFIG
530 # $feature{'remote_heads'}{'override'} = 1;
531 # and in project config gitweb.remote_heads = 0|1;
532 'remote_heads' => {
533 'sub' => sub { feature_bool('remote_heads', @_) },
534 'override' => 0,
535 'default' => [0]},
538 sub gitweb_get_feature {
539 my ($name) = @_;
540 return unless exists $feature{$name};
541 my ($sub, $override, @defaults) = (
542 $feature{$name}{'sub'},
543 $feature{$name}{'override'},
544 @{$feature{$name}{'default'}});
545 # project specific override is possible only if we have project
546 our $git_dir; # global variable, declared later
547 if (!$override || !defined $git_dir) {
548 return @defaults;
550 if (!defined $sub) {
551 warn "feature $name is not overridable";
552 return @defaults;
554 return $sub->(@defaults);
557 # A wrapper to check if a given feature is enabled.
558 # With this, you can say
560 # my $bool_feat = gitweb_check_feature('bool_feat');
561 # gitweb_check_feature('bool_feat') or somecode;
563 # instead of
565 # my ($bool_feat) = gitweb_get_feature('bool_feat');
566 # (gitweb_get_feature('bool_feat'))[0] or somecode;
568 sub gitweb_check_feature {
569 return (gitweb_get_feature(@_))[0];
573 sub feature_bool {
574 my $key = shift;
575 my ($val) = git_get_project_config($key, '--bool');
577 if (!defined $val) {
578 return ($_[0]);
579 } elsif ($val eq 'true') {
580 return (1);
581 } elsif ($val eq 'false') {
582 return (0);
586 sub feature_snapshot {
587 my (@fmts) = @_;
589 my ($val) = git_get_project_config('snapshot');
591 if ($val) {
592 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
595 return @fmts;
598 sub feature_patches {
599 my @val = (git_get_project_config('patches', '--int'));
601 if (@val) {
602 return @val;
605 return ($_[0]);
608 sub feature_avatar {
609 my @val = (git_get_project_config('avatar'));
611 return @val ? @val : @_;
614 # checking HEAD file with -e is fragile if the repository was
615 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
616 # and then pruned.
617 sub check_head_link {
618 my ($dir) = @_;
619 my $headfile = "$dir/HEAD";
620 return ((-e $headfile) ||
621 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
624 sub check_export_ok {
625 my ($dir) = @_;
626 return (check_head_link($dir) &&
627 (!$export_ok || -e "$dir/$export_ok") &&
628 (!$export_auth_hook || $export_auth_hook->($dir)));
631 # process alternate names for backward compatibility
632 # filter out unsupported (unknown) snapshot formats
633 sub filter_snapshot_fmts {
634 my @fmts = @_;
636 @fmts = map {
637 exists $known_snapshot_format_aliases{$_} ?
638 $known_snapshot_format_aliases{$_} : $_} @fmts;
639 @fmts = grep {
640 exists $known_snapshot_formats{$_} &&
641 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
644 # If it is set to code reference, it is code that it is to be run once per
645 # request, allowing updating configurations that change with each request,
646 # while running other code in config file only once.
648 # Otherwise, if it is false then gitweb would process config file only once;
649 # if it is true then gitweb config would be run for each request.
650 our $per_request_config = 1;
652 # read and parse gitweb config file given by its parameter.
653 # returns true on success, false on recoverable error, allowing
654 # to chain this subroutine, using first file that exists.
655 # dies on errors during parsing config file, as it is unrecoverable.
656 sub read_config_file {
657 my $filename = shift;
658 return unless defined $filename;
659 # die if there are errors parsing config file
660 if (-e $filename) {
661 do $filename;
662 die $@ if $@;
663 return 1;
665 return;
668 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
669 sub evaluate_gitweb_config {
670 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
671 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
672 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
674 # Protect agains duplications of file names, to not read config twice.
675 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
676 # there possibility of duplication of filename there doesn't matter.
677 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
678 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
680 # Common system-wide settings for convenience.
681 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
682 read_config_file($GITWEB_CONFIG_COMMON);
684 # Use first config file that exists. This means use the per-instance
685 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
686 read_config_file($GITWEB_CONFIG) and return;
687 read_config_file($GITWEB_CONFIG_SYSTEM);
690 # Get loadavg of system, to compare against $maxload.
691 # Currently it requires '/proc/loadavg' present to get loadavg;
692 # if it is not present it returns 0, which means no load checking.
693 sub get_loadavg {
694 if( -e '/proc/loadavg' ){
695 open my $fd, '<', '/proc/loadavg'
696 or return 0;
697 my @load = split(/\s+/, scalar <$fd>);
698 close $fd;
700 # The first three columns measure CPU and IO utilization of the last one,
701 # five, and 10 minute periods. The fourth column shows the number of
702 # currently running processes and the total number of processes in the m/n
703 # format. The last column displays the last process ID used.
704 return $load[0] || 0;
706 # additional checks for load average should go here for things that don't export
707 # /proc/loadavg
709 return 0;
712 # version of the core git binary
713 our $git_version;
714 sub evaluate_git_version {
715 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
716 $number_of_git_cmds++;
719 sub check_loadavg {
720 if (defined $maxload && get_loadavg() > $maxload) {
721 die_error(503, "The load average on the server is too high");
725 # ======================================================================
726 # input validation and dispatch
728 # input parameters can be collected from a variety of sources (presently, CGI
729 # and PATH_INFO), so we define an %input_params hash that collects them all
730 # together during validation: this allows subsequent uses (e.g. href()) to be
731 # agnostic of the parameter origin
733 our %input_params = ();
735 # input parameters are stored with the long parameter name as key. This will
736 # also be used in the href subroutine to convert parameters to their CGI
737 # equivalent, and since the href() usage is the most frequent one, we store
738 # the name -> CGI key mapping here, instead of the reverse.
740 # XXX: Warning: If you touch this, check the search form for updating,
741 # too.
743 our @cgi_param_mapping = (
744 project => "p",
745 action => "a",
746 file_name => "f",
747 file_parent => "fp",
748 hash => "h",
749 hash_parent => "hp",
750 hash_base => "hb",
751 hash_parent_base => "hpb",
752 page => "pg",
753 order => "o",
754 searchtext => "s",
755 searchtype => "st",
756 snapshot_format => "sf",
757 extra_options => "opt",
758 search_use_regexp => "sr",
759 ctag => "by_tag",
760 # this must be last entry (for manipulation from JavaScript)
761 javascript => "js"
763 our %cgi_param_mapping = @cgi_param_mapping;
765 # we will also need to know the possible actions, for validation
766 our %actions = (
767 "blame" => \&git_blame,
768 "blame_incremental" => \&git_blame_incremental,
769 "blame_data" => \&git_blame_data,
770 "blobdiff" => \&git_blobdiff,
771 "blobdiff_plain" => \&git_blobdiff_plain,
772 "blob" => \&git_blob,
773 "blob_plain" => \&git_blob_plain,
774 "commitdiff" => \&git_commitdiff,
775 "commitdiff_plain" => \&git_commitdiff_plain,
776 "commit" => \&git_commit,
777 "forks" => \&git_forks,
778 "heads" => \&git_heads,
779 "history" => \&git_history,
780 "log" => \&git_log,
781 "patch" => \&git_patch,
782 "patches" => \&git_patches,
783 "remotes" => \&git_remotes,
784 "rss" => \&git_rss,
785 "atom" => \&git_atom,
786 "search" => \&git_search,
787 "search_help" => \&git_search_help,
788 "shortlog" => \&git_shortlog,
789 "summary" => \&git_summary,
790 "tag" => \&git_tag,
791 "tags" => \&git_tags,
792 "tree" => \&git_tree,
793 "snapshot" => \&git_snapshot,
794 "object" => \&git_object,
795 # those below don't need $project
796 "opml" => \&git_opml,
797 "project_list" => \&git_project_list,
798 "project_index" => \&git_project_index,
801 # finally, we have the hash of allowed extra_options for the commands that
802 # allow them
803 our %allowed_options = (
804 "--no-merges" => [ qw(rss atom log shortlog history) ],
807 # fill %input_params with the CGI parameters. All values except for 'opt'
808 # should be single values, but opt can be an array. We should probably
809 # build an array of parameters that can be multi-valued, but since for the time
810 # being it's only this one, we just single it out
811 sub evaluate_query_params {
812 our $cgi;
814 while (my ($name, $symbol) = each %cgi_param_mapping) {
815 if ($symbol eq 'opt') {
816 $input_params{$name} = [ $cgi->param($symbol) ];
817 } else {
818 $input_params{$name} = $cgi->param($symbol);
823 # now read PATH_INFO and update the parameter list for missing parameters
824 sub evaluate_path_info {
825 return if defined $input_params{'project'};
826 return if !$path_info;
827 $path_info =~ s,^/+,,;
828 return if !$path_info;
830 # find which part of PATH_INFO is project
831 my $project = $path_info;
832 $project =~ s,/+$,,;
833 while ($project && !check_head_link("$projectroot/$project")) {
834 $project =~ s,/*[^/]*$,,;
836 return unless $project;
837 $input_params{'project'} = $project;
839 # do not change any parameters if an action is given using the query string
840 return if $input_params{'action'};
841 $path_info =~ s,^\Q$project\E/*,,;
843 # next, check if we have an action
844 my $action = $path_info;
845 $action =~ s,/.*$,,;
846 if (exists $actions{$action}) {
847 $path_info =~ s,^$action/*,,;
848 $input_params{'action'} = $action;
851 # list of actions that want hash_base instead of hash, but can have no
852 # pathname (f) parameter
853 my @wants_base = (
854 'tree',
855 'history',
858 # we want to catch, among others
859 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
860 my ($parentrefname, $parentpathname, $refname, $pathname) =
861 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
863 # first, analyze the 'current' part
864 if (defined $pathname) {
865 # we got "branch:filename" or "branch:dir/"
866 # we could use git_get_type(branch:pathname), but:
867 # - it needs $git_dir
868 # - it does a git() call
869 # - the convention of terminating directories with a slash
870 # makes it superfluous
871 # - embedding the action in the PATH_INFO would make it even
872 # more superfluous
873 $pathname =~ s,^/+,,;
874 if (!$pathname || substr($pathname, -1) eq "/") {
875 $input_params{'action'} ||= "tree";
876 $pathname =~ s,/$,,;
877 } else {
878 # the default action depends on whether we had parent info
879 # or not
880 if ($parentrefname) {
881 $input_params{'action'} ||= "blobdiff_plain";
882 } else {
883 $input_params{'action'} ||= "blob_plain";
886 $input_params{'hash_base'} ||= $refname;
887 $input_params{'file_name'} ||= $pathname;
888 } elsif (defined $refname) {
889 # we got "branch". In this case we have to choose if we have to
890 # set hash or hash_base.
892 # Most of the actions without a pathname only want hash to be
893 # set, except for the ones specified in @wants_base that want
894 # hash_base instead. It should also be noted that hand-crafted
895 # links having 'history' as an action and no pathname or hash
896 # set will fail, but that happens regardless of PATH_INFO.
897 if (defined $parentrefname) {
898 # if there is parent let the default be 'shortlog' action
899 # (for http://git.example.com/repo.git/A..B links); if there
900 # is no parent, dispatch will detect type of object and set
901 # action appropriately if required (if action is not set)
902 $input_params{'action'} ||= "shortlog";
904 if ($input_params{'action'} &&
905 grep { $_ eq $input_params{'action'} } @wants_base) {
906 $input_params{'hash_base'} ||= $refname;
907 } else {
908 $input_params{'hash'} ||= $refname;
912 # next, handle the 'parent' part, if present
913 if (defined $parentrefname) {
914 # a missing pathspec defaults to the 'current' filename, allowing e.g.
915 # someproject/blobdiff/oldrev..newrev:/filename
916 if ($parentpathname) {
917 $parentpathname =~ s,^/+,,;
918 $parentpathname =~ s,/$,,;
919 $input_params{'file_parent'} ||= $parentpathname;
920 } else {
921 $input_params{'file_parent'} ||= $input_params{'file_name'};
923 # we assume that hash_parent_base is wanted if a path was specified,
924 # or if the action wants hash_base instead of hash
925 if (defined $input_params{'file_parent'} ||
926 grep { $_ eq $input_params{'action'} } @wants_base) {
927 $input_params{'hash_parent_base'} ||= $parentrefname;
928 } else {
929 $input_params{'hash_parent'} ||= $parentrefname;
933 # for the snapshot action, we allow URLs in the form
934 # $project/snapshot/$hash.ext
935 # where .ext determines the snapshot and gets removed from the
936 # passed $refname to provide the $hash.
938 # To be able to tell that $refname includes the format extension, we
939 # require the following two conditions to be satisfied:
940 # - the hash input parameter MUST have been set from the $refname part
941 # of the URL (i.e. they must be equal)
942 # - the snapshot format MUST NOT have been defined already (e.g. from
943 # CGI parameter sf)
944 # It's also useless to try any matching unless $refname has a dot,
945 # so we check for that too
946 if (defined $input_params{'action'} &&
947 $input_params{'action'} eq 'snapshot' &&
948 defined $refname && index($refname, '.') != -1 &&
949 $refname eq $input_params{'hash'} &&
950 !defined $input_params{'snapshot_format'}) {
951 # We loop over the known snapshot formats, checking for
952 # extensions. Allowed extensions are both the defined suffix
953 # (which includes the initial dot already) and the snapshot
954 # format key itself, with a prepended dot
955 while (my ($fmt, $opt) = each %known_snapshot_formats) {
956 my $hash = $refname;
957 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
958 next;
960 my $sfx = $1;
961 # a valid suffix was found, so set the snapshot format
962 # and reset the hash parameter
963 $input_params{'snapshot_format'} = $fmt;
964 $input_params{'hash'} = $hash;
965 # we also set the format suffix to the one requested
966 # in the URL: this way a request for e.g. .tgz returns
967 # a .tgz instead of a .tar.gz
968 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
969 last;
974 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
975 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
976 $searchtext, $search_regexp);
977 sub evaluate_and_validate_params {
978 our $action = $input_params{'action'};
979 if (defined $action) {
980 if (!validate_action($action)) {
981 die_error(400, "Invalid action parameter");
985 # parameters which are pathnames
986 our $project = $input_params{'project'};
987 if (defined $project) {
988 if (!validate_project($project)) {
989 undef $project;
990 die_error(404, "No such project");
994 our $file_name = $input_params{'file_name'};
995 if (defined $file_name) {
996 if (!validate_pathname($file_name)) {
997 die_error(400, "Invalid file parameter");
1001 our $file_parent = $input_params{'file_parent'};
1002 if (defined $file_parent) {
1003 if (!validate_pathname($file_parent)) {
1004 die_error(400, "Invalid file parent parameter");
1008 # parameters which are refnames
1009 our $hash = $input_params{'hash'};
1010 if (defined $hash) {
1011 if (!validate_refname($hash)) {
1012 die_error(400, "Invalid hash parameter");
1016 our $hash_parent = $input_params{'hash_parent'};
1017 if (defined $hash_parent) {
1018 if (!validate_refname($hash_parent)) {
1019 die_error(400, "Invalid hash parent parameter");
1023 our $hash_base = $input_params{'hash_base'};
1024 if (defined $hash_base) {
1025 if (!validate_refname($hash_base)) {
1026 die_error(400, "Invalid hash base parameter");
1030 our @extra_options = @{$input_params{'extra_options'}};
1031 # @extra_options is always defined, since it can only be (currently) set from
1032 # CGI, and $cgi->param() returns the empty array in array context if the param
1033 # is not set
1034 foreach my $opt (@extra_options) {
1035 if (not exists $allowed_options{$opt}) {
1036 die_error(400, "Invalid option parameter");
1038 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1039 die_error(400, "Invalid option parameter for this action");
1043 our $hash_parent_base = $input_params{'hash_parent_base'};
1044 if (defined $hash_parent_base) {
1045 if (!validate_refname($hash_parent_base)) {
1046 die_error(400, "Invalid hash parent base parameter");
1050 # other parameters
1051 our $page = $input_params{'page'};
1052 if (defined $page) {
1053 if ($page =~ m/[^0-9]/) {
1054 die_error(400, "Invalid page parameter");
1058 our $searchtype = $input_params{'searchtype'};
1059 if (defined $searchtype) {
1060 if ($searchtype =~ m/[^a-z]/) {
1061 die_error(400, "Invalid searchtype parameter");
1065 our $search_use_regexp = $input_params{'search_use_regexp'};
1067 our $searchtext = $input_params{'searchtext'};
1068 our $search_regexp;
1069 if (defined $searchtext) {
1070 if (length($searchtext) < 2) {
1071 die_error(403, "At least two characters are required for search parameter");
1073 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1077 # path to the current git repository
1078 our $git_dir;
1079 sub evaluate_git_dir {
1080 our $git_dir = "$projectroot/$project" if $project;
1083 our (@snapshot_fmts, $git_avatar);
1084 sub configure_gitweb_features {
1085 # list of supported snapshot formats
1086 our @snapshot_fmts = gitweb_get_feature('snapshot');
1087 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1089 # check that the avatar feature is set to a known provider name,
1090 # and for each provider check if the dependencies are satisfied.
1091 # if the provider name is invalid or the dependencies are not met,
1092 # reset $git_avatar to the empty string.
1093 our ($git_avatar) = gitweb_get_feature('avatar');
1094 if ($git_avatar eq 'gravatar') {
1095 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1096 } elsif ($git_avatar eq 'picon') {
1097 # no dependencies
1098 } else {
1099 $git_avatar = '';
1103 # custom error handler: 'die <message>' is Internal Server Error
1104 sub handle_errors_html {
1105 my $msg = shift; # it is already HTML escaped
1107 # to avoid infinite loop where error occurs in die_error,
1108 # change handler to default handler, disabling handle_errors_html
1109 set_message("Error occured when inside die_error:\n$msg");
1111 # you cannot jump out of die_error when called as error handler;
1112 # the subroutine set via CGI::Carp::set_message is called _after_
1113 # HTTP headers are already written, so it cannot write them itself
1114 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1116 set_message(\&handle_errors_html);
1118 # dispatch
1119 sub dispatch {
1120 if (!defined $action) {
1121 if (defined $hash) {
1122 $action = git_get_type($hash);
1123 } elsif (defined $hash_base && defined $file_name) {
1124 $action = git_get_type("$hash_base:$file_name");
1125 } elsif (defined $project) {
1126 $action = 'summary';
1127 } else {
1128 $action = 'project_list';
1131 if (!defined($actions{$action})) {
1132 die_error(400, "Unknown action");
1134 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1135 !$project) {
1136 die_error(400, "Project needed");
1138 $actions{$action}->();
1141 sub reset_timer {
1142 our $t0 = [ gettimeofday() ]
1143 if defined $t0;
1144 our $number_of_git_cmds = 0;
1147 our $first_request = 1;
1148 sub run_request {
1149 reset_timer();
1151 evaluate_uri();
1152 if ($first_request) {
1153 evaluate_gitweb_config();
1154 evaluate_git_version();
1156 if ($per_request_config) {
1157 if (ref($per_request_config) eq 'CODE') {
1158 $per_request_config->();
1159 } elsif (!$first_request) {
1160 evaluate_gitweb_config();
1163 check_loadavg();
1165 # $projectroot and $projects_list might be set in gitweb config file
1166 $projects_list ||= $projectroot;
1168 evaluate_query_params();
1169 evaluate_path_info();
1170 evaluate_and_validate_params();
1171 evaluate_git_dir();
1173 configure_gitweb_features();
1175 dispatch();
1178 our $is_last_request = sub { 1 };
1179 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1180 our $CGI = 'CGI';
1181 our $cgi;
1182 sub configure_as_fcgi {
1183 require CGI::Fast;
1184 our $CGI = 'CGI::Fast';
1186 my $request_number = 0;
1187 # let each child service 100 requests
1188 our $is_last_request = sub { ++$request_number > 100 };
1190 sub evaluate_argv {
1191 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1192 configure_as_fcgi()
1193 if $script_name =~ /\.fcgi$/;
1195 return unless (@ARGV);
1197 require Getopt::Long;
1198 Getopt::Long::GetOptions(
1199 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1200 'nproc|n=i' => sub {
1201 my ($arg, $val) = @_;
1202 return unless eval { require FCGI::ProcManager; 1; };
1203 my $proc_manager = FCGI::ProcManager->new({
1204 n_processes => $val,
1206 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1207 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1208 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1213 sub run {
1214 evaluate_argv();
1216 $first_request = 1;
1217 $pre_listen_hook->()
1218 if $pre_listen_hook;
1220 REQUEST:
1221 while ($cgi = $CGI->new()) {
1222 $pre_dispatch_hook->()
1223 if $pre_dispatch_hook;
1225 run_request();
1227 $post_dispatch_hook->()
1228 if $post_dispatch_hook;
1229 $first_request = 0;
1231 last REQUEST if ($is_last_request->());
1234 DONE_GITWEB:
1238 run();
1240 if (defined caller) {
1241 # wrapped in a subroutine processing requests,
1242 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1243 return;
1244 } else {
1245 # pure CGI script, serving single request
1246 exit;
1249 ## ======================================================================
1250 ## action links
1252 # possible values of extra options
1253 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1254 # -replay => 1 - start from a current view (replay with modifications)
1255 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1256 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1257 sub href {
1258 my %params = @_;
1259 # default is to use -absolute url() i.e. $my_uri
1260 my $href = $params{-full} ? $my_url : $my_uri;
1262 # implicit -replay, must be first of implicit params
1263 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1265 $params{'project'} = $project unless exists $params{'project'};
1267 if ($params{-replay}) {
1268 while (my ($name, $symbol) = each %cgi_param_mapping) {
1269 if (!exists $params{$name}) {
1270 $params{$name} = $input_params{$name};
1275 my $use_pathinfo = gitweb_check_feature('pathinfo');
1276 if (defined $params{'project'} &&
1277 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1278 # try to put as many parameters as possible in PATH_INFO:
1279 # - project name
1280 # - action
1281 # - hash_parent or hash_parent_base:/file_parent
1282 # - hash or hash_base:/filename
1283 # - the snapshot_format as an appropriate suffix
1285 # When the script is the root DirectoryIndex for the domain,
1286 # $href here would be something like http://gitweb.example.com/
1287 # Thus, we strip any trailing / from $href, to spare us double
1288 # slashes in the final URL
1289 $href =~ s,/$,,;
1291 # Then add the project name, if present
1292 $href .= "/".esc_path_info($params{'project'});
1293 delete $params{'project'};
1295 # since we destructively absorb parameters, we keep this
1296 # boolean that remembers if we're handling a snapshot
1297 my $is_snapshot = $params{'action'} eq 'snapshot';
1299 # Summary just uses the project path URL, any other action is
1300 # added to the URL
1301 if (defined $params{'action'}) {
1302 $href .= "/".esc_path_info($params{'action'})
1303 unless $params{'action'} eq 'summary';
1304 delete $params{'action'};
1307 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1308 # stripping nonexistent or useless pieces
1309 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1310 || $params{'hash_parent'} || $params{'hash'});
1311 if (defined $params{'hash_base'}) {
1312 if (defined $params{'hash_parent_base'}) {
1313 $href .= esc_path_info($params{'hash_parent_base'});
1314 # skip the file_parent if it's the same as the file_name
1315 if (defined $params{'file_parent'}) {
1316 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1317 delete $params{'file_parent'};
1318 } elsif ($params{'file_parent'} !~ /\.\./) {
1319 $href .= ":/".esc_path_info($params{'file_parent'});
1320 delete $params{'file_parent'};
1323 $href .= "..";
1324 delete $params{'hash_parent'};
1325 delete $params{'hash_parent_base'};
1326 } elsif (defined $params{'hash_parent'}) {
1327 $href .= esc_path_info($params{'hash_parent'}). "..";
1328 delete $params{'hash_parent'};
1331 $href .= esc_path_info($params{'hash_base'});
1332 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1333 $href .= ":/".esc_path_info($params{'file_name'});
1334 delete $params{'file_name'};
1336 delete $params{'hash'};
1337 delete $params{'hash_base'};
1338 } elsif (defined $params{'hash'}) {
1339 $href .= esc_path_info($params{'hash'});
1340 delete $params{'hash'};
1343 # If the action was a snapshot, we can absorb the
1344 # snapshot_format parameter too
1345 if ($is_snapshot) {
1346 my $fmt = $params{'snapshot_format'};
1347 # snapshot_format should always be defined when href()
1348 # is called, but just in case some code forgets, we
1349 # fall back to the default
1350 $fmt ||= $snapshot_fmts[0];
1351 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1352 delete $params{'snapshot_format'};
1356 # now encode the parameters explicitly
1357 my @result = ();
1358 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1359 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1360 if (defined $params{$name}) {
1361 if (ref($params{$name}) eq "ARRAY") {
1362 foreach my $par (@{$params{$name}}) {
1363 push @result, $symbol . "=" . esc_param($par);
1365 } else {
1366 push @result, $symbol . "=" . esc_param($params{$name});
1370 $href .= "?" . join(';', @result) if scalar @result;
1372 # final transformation: trailing spaces must be escaped (URI-encoded)
1373 $href =~ s/(\s+)$/CGI::escape($1)/e;
1375 if ($params{-anchor}) {
1376 $href .= "#".esc_param($params{-anchor});
1379 return $href;
1383 ## ======================================================================
1384 ## validation, quoting/unquoting and escaping
1386 sub validate_action {
1387 my $input = shift || return undef;
1388 return undef unless exists $actions{$input};
1389 return $input;
1392 sub validate_project {
1393 my $input = shift || return undef;
1394 if (!validate_pathname($input) ||
1395 !(-d "$projectroot/$input") ||
1396 !check_export_ok("$projectroot/$input") ||
1397 ($strict_export && !project_in_list($input))) {
1398 return undef;
1399 } else {
1400 return $input;
1404 sub validate_pathname {
1405 my $input = shift || return undef;
1407 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1408 # at the beginning, at the end, and between slashes.
1409 # also this catches doubled slashes
1410 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1411 return undef;
1413 # no null characters
1414 if ($input =~ m!\0!) {
1415 return undef;
1417 return $input;
1420 sub validate_refname {
1421 my $input = shift || return undef;
1423 # textual hashes are O.K.
1424 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1425 return $input;
1427 # it must be correct pathname
1428 $input = validate_pathname($input)
1429 or return undef;
1430 # restrictions on ref name according to git-check-ref-format
1431 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1432 return undef;
1434 return $input;
1437 # decode sequences of octets in utf8 into Perl's internal form,
1438 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1439 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1440 sub to_utf8 {
1441 my $str = shift;
1442 return undef unless defined $str;
1443 if (utf8::valid($str)) {
1444 utf8::decode($str);
1445 return $str;
1446 } else {
1447 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1451 # quote unsafe chars, but keep the slash, even when it's not
1452 # correct, but quoted slashes look too horrible in bookmarks
1453 sub esc_param {
1454 my $str = shift;
1455 return undef unless defined $str;
1456 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1457 $str =~ s/ /\+/g;
1458 return $str;
1461 # the quoting rules for path_info fragment are slightly different
1462 sub esc_path_info {
1463 my $str = shift;
1464 return undef unless defined $str;
1466 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1467 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1469 return $str;
1472 # quote unsafe chars in whole URL, so some characters cannot be quoted
1473 sub esc_url {
1474 my $str = shift;
1475 return undef unless defined $str;
1476 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1477 $str =~ s/ /\+/g;
1478 return $str;
1481 # quote unsafe characters in HTML attributes
1482 sub esc_attr {
1484 # for XHTML conformance escaping '"' to '&quot;' is not enough
1485 return esc_html(@_);
1488 # replace invalid utf8 character with SUBSTITUTION sequence
1489 sub esc_html {
1490 my $str = shift;
1491 my %opts = @_;
1493 return undef unless defined $str;
1495 $str = to_utf8($str);
1496 $str = $cgi->escapeHTML($str);
1497 if ($opts{'-nbsp'}) {
1498 $str =~ s/ /&nbsp;/g;
1500 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1501 return $str;
1504 # quote control characters and escape filename to HTML
1505 sub esc_path {
1506 my $str = shift;
1507 my %opts = @_;
1509 return undef unless defined $str;
1511 $str = to_utf8($str);
1512 $str = $cgi->escapeHTML($str);
1513 if ($opts{'-nbsp'}) {
1514 $str =~ s/ /&nbsp;/g;
1516 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1517 return $str;
1520 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1521 sub sanitize {
1522 my $str = shift;
1524 return undef unless defined $str;
1526 $str = to_utf8($str);
1527 $str =~ s|([[:cntrl:]])|($1 =~ /[\t\n\r]/ ? $1 : quot_cec($1))|eg;
1528 return $str;
1531 # Make control characters "printable", using character escape codes (CEC)
1532 sub quot_cec {
1533 my $cntrl = shift;
1534 my %opts = @_;
1535 my %es = ( # character escape codes, aka escape sequences
1536 "\t" => '\t', # tab (HT)
1537 "\n" => '\n', # line feed (LF)
1538 "\r" => '\r', # carrige return (CR)
1539 "\f" => '\f', # form feed (FF)
1540 "\b" => '\b', # backspace (BS)
1541 "\a" => '\a', # alarm (bell) (BEL)
1542 "\e" => '\e', # escape (ESC)
1543 "\013" => '\v', # vertical tab (VT)
1544 "\000" => '\0', # nul character (NUL)
1546 my $chr = ( (exists $es{$cntrl})
1547 ? $es{$cntrl}
1548 : sprintf('\%2x', ord($cntrl)) );
1549 if ($opts{-nohtml}) {
1550 return $chr;
1551 } else {
1552 return "<span class=\"cntrl\">$chr</span>";
1556 # Alternatively use unicode control pictures codepoints,
1557 # Unicode "printable representation" (PR)
1558 sub quot_upr {
1559 my $cntrl = shift;
1560 my %opts = @_;
1562 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1563 if ($opts{-nohtml}) {
1564 return $chr;
1565 } else {
1566 return "<span class=\"cntrl\">$chr</span>";
1570 # git may return quoted and escaped filenames
1571 sub unquote {
1572 my $str = shift;
1574 sub unq {
1575 my $seq = shift;
1576 my %es = ( # character escape codes, aka escape sequences
1577 't' => "\t", # tab (HT, TAB)
1578 'n' => "\n", # newline (NL)
1579 'r' => "\r", # return (CR)
1580 'f' => "\f", # form feed (FF)
1581 'b' => "\b", # backspace (BS)
1582 'a' => "\a", # alarm (bell) (BEL)
1583 'e' => "\e", # escape (ESC)
1584 'v' => "\013", # vertical tab (VT)
1587 if ($seq =~ m/^[0-7]{1,3}$/) {
1588 # octal char sequence
1589 return chr(oct($seq));
1590 } elsif (exists $es{$seq}) {
1591 # C escape sequence, aka character escape code
1592 return $es{$seq};
1594 # quoted ordinary character
1595 return $seq;
1598 if ($str =~ m/^"(.*)"$/) {
1599 # needs unquoting
1600 $str = $1;
1601 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1603 return $str;
1606 # escape tabs (convert tabs to spaces)
1607 sub untabify {
1608 my $line = shift;
1610 while ((my $pos = index($line, "\t")) != -1) {
1611 if (my $count = (8 - ($pos % 8))) {
1612 my $spaces = ' ' x $count;
1613 $line =~ s/\t/$spaces/;
1617 return $line;
1620 sub project_in_list {
1621 my $project = shift;
1622 my @list = git_get_projects_list();
1623 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1626 ## ----------------------------------------------------------------------
1627 ## HTML aware string manipulation
1629 # Try to chop given string on a word boundary between position
1630 # $len and $len+$add_len. If there is no word boundary there,
1631 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1632 # (marking chopped part) would be longer than given string.
1633 sub chop_str {
1634 my $str = shift;
1635 my $len = shift;
1636 my $add_len = shift || 10;
1637 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1639 # Make sure perl knows it is utf8 encoded so we don't
1640 # cut in the middle of a utf8 multibyte char.
1641 $str = to_utf8($str);
1643 # allow only $len chars, but don't cut a word if it would fit in $add_len
1644 # if it doesn't fit, cut it if it's still longer than the dots we would add
1645 # remove chopped character entities entirely
1647 # when chopping in the middle, distribute $len into left and right part
1648 # return early if chopping wouldn't make string shorter
1649 if ($where eq 'center') {
1650 return $str if ($len + 5 >= length($str)); # filler is length 5
1651 $len = int($len/2);
1652 } else {
1653 return $str if ($len + 4 >= length($str)); # filler is length 4
1656 # regexps: ending and beginning with word part up to $add_len
1657 my $endre = qr/.{$len}\w{0,$add_len}/;
1658 my $begre = qr/\w{0,$add_len}.{$len}/;
1660 if ($where eq 'left') {
1661 $str =~ m/^(.*?)($begre)$/;
1662 my ($lead, $body) = ($1, $2);
1663 if (length($lead) > 4) {
1664 $lead = " ...";
1666 return "$lead$body";
1668 } elsif ($where eq 'center') {
1669 $str =~ m/^($endre)(.*)$/;
1670 my ($left, $str) = ($1, $2);
1671 $str =~ m/^(.*?)($begre)$/;
1672 my ($mid, $right) = ($1, $2);
1673 if (length($mid) > 5) {
1674 $mid = " ... ";
1676 return "$left$mid$right";
1678 } else {
1679 $str =~ m/^($endre)(.*)$/;
1680 my $body = $1;
1681 my $tail = $2;
1682 if (length($tail) > 4) {
1683 $tail = "... ";
1685 return "$body$tail";
1689 # takes the same arguments as chop_str, but also wraps a <span> around the
1690 # result with a title attribute if it does get chopped. Additionally, the
1691 # string is HTML-escaped.
1692 sub chop_and_escape_str {
1693 my ($str) = @_;
1695 my $chopped = chop_str(@_);
1696 if ($chopped eq $str) {
1697 return esc_html($chopped);
1698 } else {
1699 $str =~ s/[[:cntrl:]]/?/g;
1700 return $cgi->span({-title=>$str}, esc_html($chopped));
1704 ## ----------------------------------------------------------------------
1705 ## functions returning short strings
1707 # CSS class for given age value (in seconds)
1708 sub age_class {
1709 my $age = shift;
1711 if (!defined $age) {
1712 return "noage";
1713 } elsif ($age < 60*60*2) {
1714 return "age0";
1715 } elsif ($age < 60*60*24*2) {
1716 return "age1";
1717 } else {
1718 return "age2";
1722 # convert age in seconds to "nn units ago" string
1723 sub age_string {
1724 my $age = shift;
1725 my $age_str;
1727 if ($age > 60*60*24*365*2) {
1728 $age_str = (int $age/60/60/24/365);
1729 $age_str .= " years ago";
1730 } elsif ($age > 60*60*24*(365/12)*2) {
1731 $age_str = int $age/60/60/24/(365/12);
1732 $age_str .= " months ago";
1733 } elsif ($age > 60*60*24*7*2) {
1734 $age_str = int $age/60/60/24/7;
1735 $age_str .= " weeks ago";
1736 } elsif ($age > 60*60*24*2) {
1737 $age_str = int $age/60/60/24;
1738 $age_str .= " days ago";
1739 } elsif ($age > 60*60*2) {
1740 $age_str = int $age/60/60;
1741 $age_str .= " hours ago";
1742 } elsif ($age > 60*2) {
1743 $age_str = int $age/60;
1744 $age_str .= " min ago";
1745 } elsif ($age > 2) {
1746 $age_str = int $age;
1747 $age_str .= " sec ago";
1748 } else {
1749 $age_str .= " right now";
1751 return $age_str;
1754 use constant {
1755 S_IFINVALID => 0030000,
1756 S_IFGITLINK => 0160000,
1759 # submodule/subproject, a commit object reference
1760 sub S_ISGITLINK {
1761 my $mode = shift;
1763 return (($mode & S_IFMT) == S_IFGITLINK)
1766 # convert file mode in octal to symbolic file mode string
1767 sub mode_str {
1768 my $mode = oct shift;
1770 if (S_ISGITLINK($mode)) {
1771 return 'm---------';
1772 } elsif (S_ISDIR($mode & S_IFMT)) {
1773 return 'drwxr-xr-x';
1774 } elsif (S_ISLNK($mode)) {
1775 return 'lrwxrwxrwx';
1776 } elsif (S_ISREG($mode)) {
1777 # git cares only about the executable bit
1778 if ($mode & S_IXUSR) {
1779 return '-rwxr-xr-x';
1780 } else {
1781 return '-rw-r--r--';
1783 } else {
1784 return '----------';
1788 # convert file mode in octal to file type string
1789 sub file_type {
1790 my $mode = shift;
1792 if ($mode !~ m/^[0-7]+$/) {
1793 return $mode;
1794 } else {
1795 $mode = oct $mode;
1798 if (S_ISGITLINK($mode)) {
1799 return "submodule";
1800 } elsif (S_ISDIR($mode & S_IFMT)) {
1801 return "directory";
1802 } elsif (S_ISLNK($mode)) {
1803 return "symlink";
1804 } elsif (S_ISREG($mode)) {
1805 return "file";
1806 } else {
1807 return "unknown";
1811 # convert file mode in octal to file type description string
1812 sub file_type_long {
1813 my $mode = shift;
1815 if ($mode !~ m/^[0-7]+$/) {
1816 return $mode;
1817 } else {
1818 $mode = oct $mode;
1821 if (S_ISGITLINK($mode)) {
1822 return "submodule";
1823 } elsif (S_ISDIR($mode & S_IFMT)) {
1824 return "directory";
1825 } elsif (S_ISLNK($mode)) {
1826 return "symlink";
1827 } elsif (S_ISREG($mode)) {
1828 if ($mode & S_IXUSR) {
1829 return "executable";
1830 } else {
1831 return "file";
1833 } else {
1834 return "unknown";
1839 ## ----------------------------------------------------------------------
1840 ## functions returning short HTML fragments, or transforming HTML fragments
1841 ## which don't belong to other sections
1843 # format line of commit message.
1844 sub format_log_line_html {
1845 my $line = shift;
1847 $line = esc_html($line, -nbsp=>1);
1848 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1849 $cgi->a({-href => href(action=>"object", hash=>$1),
1850 -class => "text"}, $1);
1851 }eg;
1853 return $line;
1856 # format marker of refs pointing to given object
1858 # the destination action is chosen based on object type and current context:
1859 # - for annotated tags, we choose the tag view unless it's the current view
1860 # already, in which case we go to shortlog view
1861 # - for other refs, we keep the current view if we're in history, shortlog or
1862 # log view, and select shortlog otherwise
1863 sub format_ref_marker {
1864 my ($refs, $id) = @_;
1865 my $markers = '';
1867 if (defined $refs->{$id}) {
1868 foreach my $ref (@{$refs->{$id}}) {
1869 # this code exploits the fact that non-lightweight tags are the
1870 # only indirect objects, and that they are the only objects for which
1871 # we want to use tag instead of shortlog as action
1872 my ($type, $name) = qw();
1873 my $indirect = ($ref =~ s/\^\{\}$//);
1874 # e.g. tags/v2.6.11 or heads/next
1875 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1876 $type = $1;
1877 $name = $2;
1878 } else {
1879 $type = "ref";
1880 $name = $ref;
1883 my $class = $type;
1884 $class .= " indirect" if $indirect;
1886 my $dest_action = "shortlog";
1888 if ($indirect) {
1889 $dest_action = "tag" unless $action eq "tag";
1890 } elsif ($action =~ /^(history|(short)?log)$/) {
1891 $dest_action = $action;
1894 my $dest = "";
1895 $dest .= "refs/" unless $ref =~ m!^refs/!;
1896 $dest .= $ref;
1898 my $link = $cgi->a({
1899 -href => href(
1900 action=>$dest_action,
1901 hash=>$dest
1902 )}, $name);
1904 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
1905 $link . "</span>";
1909 if ($markers) {
1910 return ' <span class="refs">'. $markers . '</span>';
1911 } else {
1912 return "";
1916 # format, perhaps shortened and with markers, title line
1917 sub format_subject_html {
1918 my ($long, $short, $href, $extra) = @_;
1919 $extra = '' unless defined($extra);
1921 if (length($short) < length($long)) {
1922 $long =~ s/[[:cntrl:]]/?/g;
1923 return $cgi->a({-href => $href, -class => "list subject",
1924 -title => to_utf8($long)},
1925 esc_html($short)) . $extra;
1926 } else {
1927 return $cgi->a({-href => $href, -class => "list subject"},
1928 esc_html($long)) . $extra;
1932 # Rather than recomputing the url for an email multiple times, we cache it
1933 # after the first hit. This gives a visible benefit in views where the avatar
1934 # for the same email is used repeatedly (e.g. shortlog).
1935 # The cache is shared by all avatar engines (currently gravatar only), which
1936 # are free to use it as preferred. Since only one avatar engine is used for any
1937 # given page, there's no risk for cache conflicts.
1938 our %avatar_cache = ();
1940 # Compute the picon url for a given email, by using the picon search service over at
1941 # http://www.cs.indiana.edu/picons/search.html
1942 sub picon_url {
1943 my $email = lc shift;
1944 if (!$avatar_cache{$email}) {
1945 my ($user, $domain) = split('@', $email);
1946 $avatar_cache{$email} =
1947 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1948 "$domain/$user/" .
1949 "users+domains+unknown/up/single";
1951 return $avatar_cache{$email};
1954 # Compute the gravatar url for a given email, if it's not in the cache already.
1955 # Gravatar stores only the part of the URL before the size, since that's the
1956 # one computationally more expensive. This also allows reuse of the cache for
1957 # different sizes (for this particular engine).
1958 sub gravatar_url {
1959 my $email = lc shift;
1960 my $size = shift;
1961 $avatar_cache{$email} ||=
1962 "http://www.gravatar.com/avatar/" .
1963 Digest::MD5::md5_hex($email) . "?s=";
1964 return $avatar_cache{$email} . $size;
1967 # Insert an avatar for the given $email at the given $size if the feature
1968 # is enabled.
1969 sub git_get_avatar {
1970 my ($email, %opts) = @_;
1971 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1972 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1973 $opts{-size} ||= 'default';
1974 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1975 my $url = "";
1976 if ($git_avatar eq 'gravatar') {
1977 $url = gravatar_url($email, $size);
1978 } elsif ($git_avatar eq 'picon') {
1979 $url = picon_url($email);
1981 # Other providers can be added by extending the if chain, defining $url
1982 # as needed. If no variant puts something in $url, we assume avatars
1983 # are completely disabled/unavailable.
1984 if ($url) {
1985 return $pre_white .
1986 "<img width=\"$size\" " .
1987 "class=\"avatar\" " .
1988 "src=\"".esc_url($url)."\" " .
1989 "alt=\"\" " .
1990 "/>" . $post_white;
1991 } else {
1992 return "";
1996 sub format_search_author {
1997 my ($author, $searchtype, $displaytext) = @_;
1998 my $have_search = gitweb_check_feature('search');
2000 if ($have_search) {
2001 my $performed = "";
2002 if ($searchtype eq 'author') {
2003 $performed = "authored";
2004 } elsif ($searchtype eq 'committer') {
2005 $performed = "committed";
2008 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2009 searchtext=>$author,
2010 searchtype=>$searchtype), class=>"list",
2011 title=>"Search for commits $performed by $author"},
2012 $displaytext);
2014 } else {
2015 return $displaytext;
2019 # format the author name of the given commit with the given tag
2020 # the author name is chopped and escaped according to the other
2021 # optional parameters (see chop_str).
2022 sub format_author_html {
2023 my $tag = shift;
2024 my $co = shift;
2025 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2026 return "<$tag class=\"author\">" .
2027 format_search_author($co->{'author_name'}, "author",
2028 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2029 $author) .
2030 "</$tag>";
2033 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2034 sub format_git_diff_header_line {
2035 my $line = shift;
2036 my $diffinfo = shift;
2037 my ($from, $to) = @_;
2039 if ($diffinfo->{'nparents'}) {
2040 # combined diff
2041 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2042 if ($to->{'href'}) {
2043 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2044 esc_path($to->{'file'}));
2045 } else { # file was deleted (no href)
2046 $line .= esc_path($to->{'file'});
2048 } else {
2049 # "ordinary" diff
2050 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2051 if ($from->{'href'}) {
2052 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2053 'a/' . esc_path($from->{'file'}));
2054 } else { # file was added (no href)
2055 $line .= 'a/' . esc_path($from->{'file'});
2057 $line .= ' ';
2058 if ($to->{'href'}) {
2059 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2060 'b/' . esc_path($to->{'file'}));
2061 } else { # file was deleted
2062 $line .= 'b/' . esc_path($to->{'file'});
2066 return "<div class=\"diff header\">$line</div>\n";
2069 # format extended diff header line, before patch itself
2070 sub format_extended_diff_header_line {
2071 my $line = shift;
2072 my $diffinfo = shift;
2073 my ($from, $to) = @_;
2075 # match <path>
2076 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2077 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2078 esc_path($from->{'file'}));
2080 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2081 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2082 esc_path($to->{'file'}));
2084 # match single <mode>
2085 if ($line =~ m/\s(\d{6})$/) {
2086 $line .= '<span class="info"> (' .
2087 file_type_long($1) .
2088 ')</span>';
2090 # match <hash>
2091 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2092 # can match only for combined diff
2093 $line = 'index ';
2094 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2095 if ($from->{'href'}[$i]) {
2096 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2097 -class=>"hash"},
2098 substr($diffinfo->{'from_id'}[$i],0,7));
2099 } else {
2100 $line .= '0' x 7;
2102 # separator
2103 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2105 $line .= '..';
2106 if ($to->{'href'}) {
2107 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2108 substr($diffinfo->{'to_id'},0,7));
2109 } else {
2110 $line .= '0' x 7;
2113 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2114 # can match only for ordinary diff
2115 my ($from_link, $to_link);
2116 if ($from->{'href'}) {
2117 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2118 substr($diffinfo->{'from_id'},0,7));
2119 } else {
2120 $from_link = '0' x 7;
2122 if ($to->{'href'}) {
2123 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2124 substr($diffinfo->{'to_id'},0,7));
2125 } else {
2126 $to_link = '0' x 7;
2128 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2129 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2132 return $line . "<br/>\n";
2135 # format from-file/to-file diff header
2136 sub format_diff_from_to_header {
2137 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2138 my $line;
2139 my $result = '';
2141 $line = $from_line;
2142 #assert($line =~ m/^---/) if DEBUG;
2143 # no extra formatting for "^--- /dev/null"
2144 if (! $diffinfo->{'nparents'}) {
2145 # ordinary (single parent) diff
2146 if ($line =~ m!^--- "?a/!) {
2147 if ($from->{'href'}) {
2148 $line = '--- a/' .
2149 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2150 esc_path($from->{'file'}));
2151 } else {
2152 $line = '--- a/' .
2153 esc_path($from->{'file'});
2156 $result .= qq!<div class="diff from_file">$line</div>\n!;
2158 } else {
2159 # combined diff (merge commit)
2160 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2161 if ($from->{'href'}[$i]) {
2162 $line = '--- ' .
2163 $cgi->a({-href=>href(action=>"blobdiff",
2164 hash_parent=>$diffinfo->{'from_id'}[$i],
2165 hash_parent_base=>$parents[$i],
2166 file_parent=>$from->{'file'}[$i],
2167 hash=>$diffinfo->{'to_id'},
2168 hash_base=>$hash,
2169 file_name=>$to->{'file'}),
2170 -class=>"path",
2171 -title=>"diff" . ($i+1)},
2172 $i+1) .
2173 '/' .
2174 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2175 esc_path($from->{'file'}[$i]));
2176 } else {
2177 $line = '--- /dev/null';
2179 $result .= qq!<div class="diff from_file">$line</div>\n!;
2183 $line = $to_line;
2184 #assert($line =~ m/^\+\+\+/) if DEBUG;
2185 # no extra formatting for "^+++ /dev/null"
2186 if ($line =~ m!^\+\+\+ "?b/!) {
2187 if ($to->{'href'}) {
2188 $line = '+++ b/' .
2189 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2190 esc_path($to->{'file'}));
2191 } else {
2192 $line = '+++ b/' .
2193 esc_path($to->{'file'});
2196 $result .= qq!<div class="diff to_file">$line</div>\n!;
2198 return $result;
2201 # create note for patch simplified by combined diff
2202 sub format_diff_cc_simplified {
2203 my ($diffinfo, @parents) = @_;
2204 my $result = '';
2206 $result .= "<div class=\"diff header\">" .
2207 "diff --cc ";
2208 if (!is_deleted($diffinfo)) {
2209 $result .= $cgi->a({-href => href(action=>"blob",
2210 hash_base=>$hash,
2211 hash=>$diffinfo->{'to_id'},
2212 file_name=>$diffinfo->{'to_file'}),
2213 -class => "path"},
2214 esc_path($diffinfo->{'to_file'}));
2215 } else {
2216 $result .= esc_path($diffinfo->{'to_file'});
2218 $result .= "</div>\n" . # class="diff header"
2219 "<div class=\"diff nodifferences\">" .
2220 "Simple merge" .
2221 "</div>\n"; # class="diff nodifferences"
2223 return $result;
2226 # format patch (diff) line (not to be used for diff headers)
2227 sub format_diff_line {
2228 my $line = shift;
2229 my ($from, $to) = @_;
2230 my $diff_class = "";
2232 chomp $line;
2234 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2235 # combined diff
2236 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2237 if ($line =~ m/^\@{3}/) {
2238 $diff_class = " chunk_header";
2239 } elsif ($line =~ m/^\\/) {
2240 $diff_class = " incomplete";
2241 } elsif ($prefix =~ tr/+/+/) {
2242 $diff_class = " add";
2243 } elsif ($prefix =~ tr/-/-/) {
2244 $diff_class = " rem";
2246 } else {
2247 # assume ordinary diff
2248 my $char = substr($line, 0, 1);
2249 if ($char eq '+') {
2250 $diff_class = " add";
2251 } elsif ($char eq '-') {
2252 $diff_class = " rem";
2253 } elsif ($char eq '@') {
2254 $diff_class = " chunk_header";
2255 } elsif ($char eq "\\") {
2256 $diff_class = " incomplete";
2259 $line = untabify($line);
2260 if ($from && $to && $line =~ m/^\@{2} /) {
2261 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2262 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2264 $from_lines = 0 unless defined $from_lines;
2265 $to_lines = 0 unless defined $to_lines;
2267 if ($from->{'href'}) {
2268 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2269 -class=>"list"}, $from_text);
2271 if ($to->{'href'}) {
2272 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2273 -class=>"list"}, $to_text);
2275 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2276 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2277 return "<div class=\"diff$diff_class\">$line</div>\n";
2278 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2279 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2280 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2282 @from_text = split(' ', $ranges);
2283 for (my $i = 0; $i < @from_text; ++$i) {
2284 ($from_start[$i], $from_nlines[$i]) =
2285 (split(',', substr($from_text[$i], 1)), 0);
2288 $to_text = pop @from_text;
2289 $to_start = pop @from_start;
2290 $to_nlines = pop @from_nlines;
2292 $line = "<span class=\"chunk_info\">$prefix ";
2293 for (my $i = 0; $i < @from_text; ++$i) {
2294 if ($from->{'href'}[$i]) {
2295 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2296 -class=>"list"}, $from_text[$i]);
2297 } else {
2298 $line .= $from_text[$i];
2300 $line .= " ";
2302 if ($to->{'href'}) {
2303 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2304 -class=>"list"}, $to_text);
2305 } else {
2306 $line .= $to_text;
2308 $line .= " $prefix</span>" .
2309 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2310 return "<div class=\"diff$diff_class\">$line</div>\n";
2312 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2315 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2316 # linked. Pass the hash of the tree/commit to snapshot.
2317 sub format_snapshot_links {
2318 my ($hash) = @_;
2319 my $num_fmts = @snapshot_fmts;
2320 if ($num_fmts > 1) {
2321 # A parenthesized list of links bearing format names.
2322 # e.g. "snapshot (_tar.gz_ _zip_)"
2323 return "snapshot (" . join(' ', map
2324 $cgi->a({
2325 -href => href(
2326 action=>"snapshot",
2327 hash=>$hash,
2328 snapshot_format=>$_
2330 }, $known_snapshot_formats{$_}{'display'})
2331 , @snapshot_fmts) . ")";
2332 } elsif ($num_fmts == 1) {
2333 # A single "snapshot" link whose tooltip bears the format name.
2334 # i.e. "_snapshot_"
2335 my ($fmt) = @snapshot_fmts;
2336 return
2337 $cgi->a({
2338 -href => href(
2339 action=>"snapshot",
2340 hash=>$hash,
2341 snapshot_format=>$fmt
2343 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2344 }, "snapshot");
2345 } else { # $num_fmts == 0
2346 return undef;
2350 ## ......................................................................
2351 ## functions returning values to be passed, perhaps after some
2352 ## transformation, to other functions; e.g. returning arguments to href()
2354 # returns hash to be passed to href to generate gitweb URL
2355 # in -title key it returns description of link
2356 sub get_feed_info {
2357 my $format = shift || 'Atom';
2358 my %res = (action => lc($format));
2360 # feed links are possible only for project views
2361 return unless (defined $project);
2362 # some views should link to OPML, or to generic project feed,
2363 # or don't have specific feed yet (so they should use generic)
2364 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2366 my $branch;
2367 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2368 # from tag links; this also makes possible to detect branch links
2369 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2370 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2371 $branch = $1;
2373 # find log type for feed description (title)
2374 my $type = 'log';
2375 if (defined $file_name) {
2376 $type = "history of $file_name";
2377 $type .= "/" if ($action eq 'tree');
2378 $type .= " on '$branch'" if (defined $branch);
2379 } else {
2380 $type = "log of $branch" if (defined $branch);
2383 $res{-title} = $type;
2384 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2385 $res{'file_name'} = $file_name;
2387 return %res;
2390 ## ----------------------------------------------------------------------
2391 ## git utility subroutines, invoking git commands
2393 # returns path to the core git executable and the --git-dir parameter as list
2394 sub git_cmd {
2395 $number_of_git_cmds++;
2396 return $GIT, '--git-dir='.$git_dir;
2399 # quote the given arguments for passing them to the shell
2400 # quote_command("command", "arg 1", "arg with ' and ! characters")
2401 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2402 # Try to avoid using this function wherever possible.
2403 sub quote_command {
2404 return join(' ',
2405 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2408 # get HEAD ref of given project as hash
2409 sub git_get_head_hash {
2410 return git_get_full_hash(shift, 'HEAD');
2413 sub git_get_full_hash {
2414 return git_get_hash(@_);
2417 sub git_get_short_hash {
2418 return git_get_hash(@_, '--short=7');
2421 sub git_get_hash {
2422 my ($project, $hash, @options) = @_;
2423 my $o_git_dir = $git_dir;
2424 my $retval = undef;
2425 $git_dir = "$projectroot/$project";
2426 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2427 '--verify', '-q', @options, $hash) {
2428 $retval = <$fd>;
2429 chomp $retval if defined $retval;
2430 close $fd;
2432 if (defined $o_git_dir) {
2433 $git_dir = $o_git_dir;
2435 return $retval;
2438 # get type of given object
2439 sub git_get_type {
2440 my $hash = shift;
2442 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2443 my $type = <$fd>;
2444 close $fd or return;
2445 chomp $type;
2446 return $type;
2449 # repository configuration
2450 our $config_file = '';
2451 our %config;
2453 # store multiple values for single key as anonymous array reference
2454 # single values stored directly in the hash, not as [ <value> ]
2455 sub hash_set_multi {
2456 my ($hash, $key, $value) = @_;
2458 if (!exists $hash->{$key}) {
2459 $hash->{$key} = $value;
2460 } elsif (!ref $hash->{$key}) {
2461 $hash->{$key} = [ $hash->{$key}, $value ];
2462 } else {
2463 push @{$hash->{$key}}, $value;
2467 # return hash of git project configuration
2468 # optionally limited to some section, e.g. 'gitweb'
2469 sub git_parse_project_config {
2470 my $section_regexp = shift;
2471 my %config;
2473 local $/ = "\0";
2475 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2476 or return;
2478 while (my $keyval = <$fh>) {
2479 chomp $keyval;
2480 my ($key, $value) = split(/\n/, $keyval, 2);
2482 hash_set_multi(\%config, $key, $value)
2483 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2485 close $fh;
2487 return %config;
2490 # convert config value to boolean: 'true' or 'false'
2491 # no value, number > 0, 'true' and 'yes' values are true
2492 # rest of values are treated as false (never as error)
2493 sub config_to_bool {
2494 my $val = shift;
2496 return 1 if !defined $val; # section.key
2498 # strip leading and trailing whitespace
2499 $val =~ s/^\s+//;
2500 $val =~ s/\s+$//;
2502 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2503 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2506 # convert config value to simple decimal number
2507 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2508 # to be multiplied by 1024, 1048576, or 1073741824
2509 sub config_to_int {
2510 my $val = shift;
2512 # strip leading and trailing whitespace
2513 $val =~ s/^\s+//;
2514 $val =~ s/\s+$//;
2516 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2517 $unit = lc($unit);
2518 # unknown unit is treated as 1
2519 return $num * ($unit eq 'g' ? 1073741824 :
2520 $unit eq 'm' ? 1048576 :
2521 $unit eq 'k' ? 1024 : 1);
2523 return $val;
2526 # convert config value to array reference, if needed
2527 sub config_to_multi {
2528 my $val = shift;
2530 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2533 sub git_get_project_config {
2534 my ($key, $type) = @_;
2536 return unless defined $git_dir;
2538 # key sanity check
2539 return unless ($key);
2540 # only subsection, if exists, is case sensitive,
2541 # and not lowercased by 'git config -z -l'
2542 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2543 $key = join(".", lc($hi), $mi, lc($lo));
2544 } else {
2545 $key = lc($key);
2547 $key =~ s/^gitweb\.//;
2548 return if ($key =~ m/\W/);
2550 # type sanity check
2551 if (defined $type) {
2552 $type =~ s/^--//;
2553 $type = undef
2554 unless ($type eq 'bool' || $type eq 'int');
2557 # get config
2558 if (!defined $config_file ||
2559 $config_file ne "$git_dir/config") {
2560 %config = git_parse_project_config('gitweb');
2561 $config_file = "$git_dir/config";
2564 # check if config variable (key) exists
2565 return unless exists $config{"gitweb.$key"};
2567 # ensure given type
2568 if (!defined $type) {
2569 return $config{"gitweb.$key"};
2570 } elsif ($type eq 'bool') {
2571 # backward compatibility: 'git config --bool' returns true/false
2572 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2573 } elsif ($type eq 'int') {
2574 return config_to_int($config{"gitweb.$key"});
2576 return $config{"gitweb.$key"};
2579 # get hash of given path at given ref
2580 sub git_get_hash_by_path {
2581 my $base = shift;
2582 my $path = shift || return undef;
2583 my $type = shift;
2585 $path =~ s,/+$,,;
2587 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2588 or die_error(500, "Open git-ls-tree failed");
2589 my $line = <$fd>;
2590 close $fd or return undef;
2592 if (!defined $line) {
2593 # there is no tree or hash given by $path at $base
2594 return undef;
2597 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2598 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2599 if (defined $type && $type ne $2) {
2600 # type doesn't match
2601 return undef;
2603 return $3;
2606 # get path of entry with given hash at given tree-ish (ref)
2607 # used to get 'from' filename for combined diff (merge commit) for renames
2608 sub git_get_path_by_hash {
2609 my $base = shift || return;
2610 my $hash = shift || return;
2612 local $/ = "\0";
2614 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2615 or return undef;
2616 while (my $line = <$fd>) {
2617 chomp $line;
2619 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2620 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2621 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2622 close $fd;
2623 return $1;
2626 close $fd;
2627 return undef;
2630 ## ......................................................................
2631 ## git utility functions, directly accessing git repository
2633 # get the value of config variable either from file named as the variable
2634 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2635 # configuration variable in the repository config file.
2636 sub git_get_file_or_project_config {
2637 my ($path, $name) = @_;
2639 $git_dir = "$projectroot/$path";
2640 open my $fd, '<', "$git_dir/$name"
2641 or return git_get_project_config($name);
2642 my $conf = <$fd>;
2643 close $fd;
2644 if (defined $conf) {
2645 chomp $conf;
2647 return $conf;
2650 sub git_get_project_description {
2651 my $path = shift;
2652 return git_get_file_or_project_config($path, 'description');
2655 sub git_get_project_category {
2656 my $path = shift;
2657 return git_get_file_or_project_config($path, 'category');
2661 # supported formats:
2662 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2663 # - if its contents is a number, use it as tag weight,
2664 # - otherwise add a tag with weight 1
2665 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2666 # the same value multiple times increases tag weight
2667 # * `gitweb.ctag' multi-valued repo config variable
2668 sub git_get_project_ctags {
2669 my $project = shift;
2670 my $ctags = {};
2672 $git_dir = "$projectroot/$project";
2673 if (opendir my $dh, "$git_dir/ctags") {
2674 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2675 foreach my $tagfile (@files) {
2676 open my $ct, '<', $tagfile
2677 or next;
2678 my $val = <$ct>;
2679 chomp $val if $val;
2680 close $ct;
2682 (my $ctag = $tagfile) =~ s#.*/##;
2683 if ($val =~ /^\d+$/) {
2684 $ctags->{$ctag} = $val;
2685 } else {
2686 $ctags->{$ctag} = 1;
2689 closedir $dh;
2691 } elsif (open my $fh, '<', "$git_dir/ctags") {
2692 while (my $line = <$fh>) {
2693 chomp $line;
2694 $ctags->{$line}++ if $line;
2696 close $fh;
2698 } else {
2699 my $taglist = config_to_multi(git_get_project_config('ctag'));
2700 foreach my $tag (@$taglist) {
2701 $ctags->{$tag}++;
2705 return $ctags;
2708 # return hash, where keys are content tags ('ctags'),
2709 # and values are sum of weights of given tag in every project
2710 sub git_gather_all_ctags {
2711 my $projects = shift;
2712 my $ctags = {};
2714 foreach my $p (@$projects) {
2715 foreach my $ct (keys %{$p->{'ctags'}}) {
2716 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2720 return $ctags;
2723 sub git_populate_project_tagcloud {
2724 my $ctags = shift;
2726 # First, merge different-cased tags; tags vote on casing
2727 my %ctags_lc;
2728 foreach (keys %$ctags) {
2729 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2730 if (not $ctags_lc{lc $_}->{topcount}
2731 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2732 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2733 $ctags_lc{lc $_}->{topname} = $_;
2737 my $cloud;
2738 my $matched = $cgi->param('by_tag');
2739 if (eval { require HTML::TagCloud; 1; }) {
2740 $cloud = HTML::TagCloud->new;
2741 foreach my $ctag (sort keys %ctags_lc) {
2742 # Pad the title with spaces so that the cloud looks
2743 # less crammed.
2744 my $title = esc_html($ctags_lc{$ctag}->{topname});
2745 $title =~ s/ /&nbsp;/g;
2746 $title =~ s/^/&nbsp;/g;
2747 $title =~ s/$/&nbsp;/g;
2748 if (defined $matched && $matched eq $ctag) {
2749 $title = qq(<span class="match">$title</span>);
2751 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2752 $ctags_lc{$ctag}->{count});
2754 } else {
2755 $cloud = {};
2756 foreach my $ctag (keys %ctags_lc) {
2757 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
2758 if (defined $matched && $matched eq $ctag) {
2759 $title = qq(<span class="match">$title</span>);
2761 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
2762 $cloud->{$ctag}{ctag} =
2763 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
2766 return $cloud;
2769 sub git_show_project_tagcloud {
2770 my ($cloud, $count) = @_;
2771 if (ref $cloud eq 'HTML::TagCloud') {
2772 return $cloud->html_and_css($count);
2773 } else {
2774 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
2775 return
2776 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
2777 join (', ', map {
2778 $cloud->{$_}->{'ctag'}
2779 } splice(@tags, 0, $count)) .
2780 '</div>';
2784 sub git_get_project_url_list {
2785 my $path = shift;
2787 $git_dir = "$projectroot/$path";
2788 open my $fd, '<', "$git_dir/cloneurl"
2789 or return wantarray ?
2790 @{ config_to_multi(git_get_project_config('url')) } :
2791 config_to_multi(git_get_project_config('url'));
2792 my @git_project_url_list = map { chomp; $_ } <$fd>;
2793 close $fd;
2795 return wantarray ? @git_project_url_list : \@git_project_url_list;
2798 sub git_get_projects_list {
2799 my $filter = shift || '';
2800 my @list;
2802 $filter =~ s/\.git$//;
2804 if (-d $projects_list) {
2805 # search in directory
2806 my $dir = $projects_list;
2807 # remove the trailing "/"
2808 $dir =~ s!/+$!!;
2809 my $pfxlen = length("$projects_list");
2810 my $pfxdepth = ($projects_list =~ tr!/!!);
2811 # when filtering, search only given subdirectory
2812 if ($filter) {
2813 $dir .= "/$filter";
2814 $dir =~ s!/+$!!;
2817 File::Find::find({
2818 follow_fast => 1, # follow symbolic links
2819 follow_skip => 2, # ignore duplicates
2820 dangling_symlinks => 0, # ignore dangling symlinks, silently
2821 wanted => sub {
2822 # global variables
2823 our $project_maxdepth;
2824 our $projectroot;
2825 # skip project-list toplevel, if we get it.
2826 return if (m!^[/.]$!);
2827 # only directories can be git repositories
2828 return unless (-d $_);
2829 # don't traverse too deep (Find is super slow on os x)
2830 # $project_maxdepth excludes depth of $projectroot
2831 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2832 $File::Find::prune = 1;
2833 return;
2836 my $path = substr($File::Find::name, $pfxlen + 1);
2837 # we check related file in $projectroot
2838 if (check_export_ok("$projectroot/$path")) {
2839 push @list, { path => $path };
2840 $File::Find::prune = 1;
2843 }, "$dir");
2845 } elsif (-f $projects_list) {
2846 # read from file(url-encoded):
2847 # 'git%2Fgit.git Linus+Torvalds'
2848 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2849 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2850 open my $fd, '<', $projects_list or return;
2851 PROJECT:
2852 while (my $line = <$fd>) {
2853 chomp $line;
2854 my ($path, $owner) = split ' ', $line;
2855 $path = unescape($path);
2856 $owner = unescape($owner);
2857 if (!defined $path) {
2858 next;
2860 # if $filter is rpovided, check if $path begins with $filter
2861 if ($filter && $path !~ m!^\Q$filter\E/!) {
2862 next;
2864 if (check_export_ok("$projectroot/$path")) {
2865 my $pr = {
2866 path => $path,
2867 owner => to_utf8($owner),
2869 push @list, $pr;
2872 close $fd;
2874 return @list;
2877 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
2878 # as side effects it sets 'forks' field to list of forks for forked projects
2879 sub filter_forks_from_projects_list {
2880 my $projects = shift;
2882 my %trie; # prefix tree of directories (path components)
2883 # generate trie out of those directories that might contain forks
2884 foreach my $pr (@$projects) {
2885 my $path = $pr->{'path'};
2886 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
2887 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
2888 next unless ($path); # skip '.git' repository: tests, git-instaweb
2889 next unless (-d $path); # containing directory exists
2890 $pr->{'forks'} = []; # there can be 0 or more forks of project
2892 # add to trie
2893 my @dirs = split('/', $path);
2894 # walk the trie, until either runs out of components or out of trie
2895 my $ref = \%trie;
2896 while (scalar @dirs &&
2897 exists($ref->{$dirs[0]})) {
2898 $ref = $ref->{shift @dirs};
2900 # create rest of trie structure from rest of components
2901 foreach my $dir (@dirs) {
2902 $ref = $ref->{$dir} = {};
2904 # create end marker, store $pr as a data
2905 $ref->{''} = $pr if (!exists $ref->{''});
2908 # filter out forks, by finding shortest prefix match for paths
2909 my @filtered;
2910 PROJECT:
2911 foreach my $pr (@$projects) {
2912 # trie lookup
2913 my $ref = \%trie;
2914 DIR:
2915 foreach my $dir (split('/', $pr->{'path'})) {
2916 if (exists $ref->{''}) {
2917 # found [shortest] prefix, is a fork - skip it
2918 push @{$ref->{''}{'forks'}}, $pr;
2919 next PROJECT;
2921 if (!exists $ref->{$dir}) {
2922 # not in trie, cannot have prefix, not a fork
2923 push @filtered, $pr;
2924 next PROJECT;
2926 # If the dir is there, we just walk one step down the trie.
2927 $ref = $ref->{$dir};
2929 # we ran out of trie
2930 # (shouldn't happen: it's either no match, or end marker)
2931 push @filtered, $pr;
2934 return @filtered;
2937 # note: fill_project_list_info must be run first,
2938 # for 'descr_long' and 'ctags' to be filled
2939 sub search_projects_list {
2940 my ($projlist, %opts) = @_;
2941 my $tagfilter = $opts{'tagfilter'};
2942 my $searchtext = $opts{'searchtext'};
2944 return @$projlist
2945 unless ($tagfilter || $searchtext);
2947 my @projects;
2948 PROJECT:
2949 foreach my $pr (@$projlist) {
2951 if ($tagfilter) {
2952 next unless ref($pr->{'ctags'}) eq 'HASH';
2953 next unless
2954 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
2957 if ($searchtext) {
2958 next unless
2959 $pr->{'path'} =~ /$searchtext/ ||
2960 $pr->{'descr_long'} =~ /$searchtext/;
2963 push @projects, $pr;
2966 return @projects;
2969 our $gitweb_project_owner = undef;
2970 sub git_get_project_list_from_file {
2972 return if (defined $gitweb_project_owner);
2974 $gitweb_project_owner = {};
2975 # read from file (url-encoded):
2976 # 'git%2Fgit.git Linus+Torvalds'
2977 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2978 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2979 if (-f $projects_list) {
2980 open(my $fd, '<', $projects_list);
2981 while (my $line = <$fd>) {
2982 chomp $line;
2983 my ($pr, $ow) = split ' ', $line;
2984 $pr = unescape($pr);
2985 $ow = unescape($ow);
2986 $gitweb_project_owner->{$pr} = to_utf8($ow);
2988 close $fd;
2992 sub git_get_project_owner {
2993 my $project = shift;
2994 my $owner;
2996 return undef unless $project;
2997 $git_dir = "$projectroot/$project";
2999 if (!defined $gitweb_project_owner) {
3000 git_get_project_list_from_file();
3003 if (exists $gitweb_project_owner->{$project}) {
3004 $owner = $gitweb_project_owner->{$project};
3006 if (!defined $owner){
3007 $owner = git_get_project_config('owner');
3009 if (!defined $owner) {
3010 $owner = get_file_owner("$git_dir");
3013 return $owner;
3016 sub git_get_last_activity {
3017 my ($path) = @_;
3018 my $fd;
3020 $git_dir = "$projectroot/$path";
3021 open($fd, "-|", git_cmd(), 'for-each-ref',
3022 '--format=%(committer)',
3023 '--sort=-committerdate',
3024 '--count=1',
3025 'refs/heads') or return;
3026 my $most_recent = <$fd>;
3027 close $fd or return;
3028 if (defined $most_recent &&
3029 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3030 my $timestamp = $1;
3031 my $age = time - $timestamp;
3032 return ($age, age_string($age));
3034 return (undef, undef);
3037 # Implementation note: when a single remote is wanted, we cannot use 'git
3038 # remote show -n' because that command always work (assuming it's a remote URL
3039 # if it's not defined), and we cannot use 'git remote show' because that would
3040 # try to make a network roundtrip. So the only way to find if that particular
3041 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3042 # and when we find what we want.
3043 sub git_get_remotes_list {
3044 my $wanted = shift;
3045 my %remotes = ();
3047 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3048 return unless $fd;
3049 while (my $remote = <$fd>) {
3050 chomp $remote;
3051 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3052 next if $wanted and not $remote eq $wanted;
3053 my ($url, $key) = ($1, $2);
3055 $remotes{$remote} ||= { 'heads' => () };
3056 $remotes{$remote}{$key} = $url;
3058 close $fd or return;
3059 return wantarray ? %remotes : \%remotes;
3062 # Takes a hash of remotes as first parameter and fills it by adding the
3063 # available remote heads for each of the indicated remotes.
3064 sub fill_remote_heads {
3065 my $remotes = shift;
3066 my @heads = map { "remotes/$_" } keys %$remotes;
3067 my @remoteheads = git_get_heads_list(undef, @heads);
3068 foreach my $remote (keys %$remotes) {
3069 $remotes->{$remote}{'heads'} = [ grep {
3070 $_->{'name'} =~ s!^$remote/!!
3071 } @remoteheads ];
3075 sub git_get_references {
3076 my $type = shift || "";
3077 my %refs;
3078 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3079 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3080 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3081 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3082 or return;
3084 while (my $line = <$fd>) {
3085 chomp $line;
3086 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3087 if (defined $refs{$1}) {
3088 push @{$refs{$1}}, $2;
3089 } else {
3090 $refs{$1} = [ $2 ];
3094 close $fd or return;
3095 return \%refs;
3098 sub git_get_rev_name_tags {
3099 my $hash = shift || return undef;
3101 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3102 or return;
3103 my $name_rev = <$fd>;
3104 close $fd;
3106 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3107 return $1;
3108 } else {
3109 # catches also '$hash undefined' output
3110 return undef;
3114 ## ----------------------------------------------------------------------
3115 ## parse to hash functions
3117 sub parse_date {
3118 my $epoch = shift;
3119 my $tz = shift || "-0000";
3121 my %date;
3122 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3123 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3124 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3125 $date{'hour'} = $hour;
3126 $date{'minute'} = $min;
3127 $date{'mday'} = $mday;
3128 $date{'day'} = $days[$wday];
3129 $date{'month'} = $months[$mon];
3130 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3131 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3132 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3133 $mday, $months[$mon], $hour ,$min;
3134 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3135 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3137 my ($tz_sign, $tz_hour, $tz_min) =
3138 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3139 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3140 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3141 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3142 $date{'hour_local'} = $hour;
3143 $date{'minute_local'} = $min;
3144 $date{'tz_local'} = $tz;
3145 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3146 1900+$year, $mon+1, $mday,
3147 $hour, $min, $sec, $tz);
3148 return %date;
3151 sub parse_tag {
3152 my $tag_id = shift;
3153 my %tag;
3154 my @comment;
3156 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3157 $tag{'id'} = $tag_id;
3158 while (my $line = <$fd>) {
3159 chomp $line;
3160 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3161 $tag{'object'} = $1;
3162 } elsif ($line =~ m/^type (.+)$/) {
3163 $tag{'type'} = $1;
3164 } elsif ($line =~ m/^tag (.+)$/) {
3165 $tag{'name'} = $1;
3166 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3167 $tag{'author'} = $1;
3168 $tag{'author_epoch'} = $2;
3169 $tag{'author_tz'} = $3;
3170 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3171 $tag{'author_name'} = $1;
3172 $tag{'author_email'} = $2;
3173 } else {
3174 $tag{'author_name'} = $tag{'author'};
3176 } elsif ($line =~ m/--BEGIN/) {
3177 push @comment, $line;
3178 last;
3179 } elsif ($line eq "") {
3180 last;
3183 push @comment, <$fd>;
3184 $tag{'comment'} = \@comment;
3185 close $fd or return;
3186 if (!defined $tag{'name'}) {
3187 return
3189 return %tag
3192 sub parse_commit_text {
3193 my ($commit_text, $withparents) = @_;
3194 my @commit_lines = split '\n', $commit_text;
3195 my %co;
3197 pop @commit_lines; # Remove '\0'
3199 if (! @commit_lines) {
3200 return;
3203 my $header = shift @commit_lines;
3204 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3205 return;
3207 ($co{'id'}, my @parents) = split ' ', $header;
3208 while (my $line = shift @commit_lines) {
3209 last if $line eq "\n";
3210 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3211 $co{'tree'} = $1;
3212 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3213 push @parents, $1;
3214 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3215 $co{'author'} = to_utf8($1);
3216 $co{'author_epoch'} = $2;
3217 $co{'author_tz'} = $3;
3218 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3219 $co{'author_name'} = $1;
3220 $co{'author_email'} = $2;
3221 } else {
3222 $co{'author_name'} = $co{'author'};
3224 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3225 $co{'committer'} = to_utf8($1);
3226 $co{'committer_epoch'} = $2;
3227 $co{'committer_tz'} = $3;
3228 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3229 $co{'committer_name'} = $1;
3230 $co{'committer_email'} = $2;
3231 } else {
3232 $co{'committer_name'} = $co{'committer'};
3236 if (!defined $co{'tree'}) {
3237 return;
3239 $co{'parents'} = \@parents;
3240 $co{'parent'} = $parents[0];
3242 foreach my $title (@commit_lines) {
3243 $title =~ s/^ //;
3244 if ($title ne "") {
3245 $co{'title'} = chop_str($title, 80, 5);
3246 # remove leading stuff of merges to make the interesting part visible
3247 if (length($title) > 50) {
3248 $title =~ s/^Automatic //;
3249 $title =~ s/^merge (of|with) /Merge ... /i;
3250 if (length($title) > 50) {
3251 $title =~ s/(http|rsync):\/\///;
3253 if (length($title) > 50) {
3254 $title =~ s/(master|www|rsync)\.//;
3256 if (length($title) > 50) {
3257 $title =~ s/kernel.org:?//;
3259 if (length($title) > 50) {
3260 $title =~ s/\/pub\/scm//;
3263 $co{'title_short'} = chop_str($title, 50, 5);
3264 last;
3267 if (! defined $co{'title'} || $co{'title'} eq "") {
3268 $co{'title'} = $co{'title_short'} = '(no commit message)';
3270 # remove added spaces
3271 foreach my $line (@commit_lines) {
3272 $line =~ s/^ //;
3274 $co{'comment'} = \@commit_lines;
3276 my $age = time - $co{'committer_epoch'};
3277 $co{'age'} = $age;
3278 $co{'age_string'} = age_string($age);
3279 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3280 if ($age > 60*60*24*7*2) {
3281 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3282 $co{'age_string_age'} = $co{'age_string'};
3283 } else {
3284 $co{'age_string_date'} = $co{'age_string'};
3285 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3287 return %co;
3290 sub parse_commit {
3291 my ($commit_id) = @_;
3292 my %co;
3294 local $/ = "\0";
3296 open my $fd, "-|", git_cmd(), "rev-list",
3297 "--parents",
3298 "--header",
3299 "--max-count=1",
3300 $commit_id,
3301 "--",
3302 or die_error(500, "Open git-rev-list failed");
3303 %co = parse_commit_text(<$fd>, 1);
3304 close $fd;
3306 return %co;
3309 sub parse_commits {
3310 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3311 my @cos;
3313 $maxcount ||= 1;
3314 $skip ||= 0;
3316 local $/ = "\0";
3318 open my $fd, "-|", git_cmd(), "rev-list",
3319 "--header",
3320 @args,
3321 ("--max-count=" . $maxcount),
3322 ("--skip=" . $skip),
3323 @extra_options,
3324 $commit_id,
3325 "--",
3326 ($filename ? ($filename) : ())
3327 or die_error(500, "Open git-rev-list failed");
3328 while (my $line = <$fd>) {
3329 my %co = parse_commit_text($line);
3330 push @cos, \%co;
3332 close $fd;
3334 return wantarray ? @cos : \@cos;
3337 # parse line of git-diff-tree "raw" output
3338 sub parse_difftree_raw_line {
3339 my $line = shift;
3340 my %res;
3342 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3343 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3344 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3345 $res{'from_mode'} = $1;
3346 $res{'to_mode'} = $2;
3347 $res{'from_id'} = $3;
3348 $res{'to_id'} = $4;
3349 $res{'status'} = $5;
3350 $res{'similarity'} = $6;
3351 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3352 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3353 } else {
3354 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3357 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3358 # combined diff (for merge commit)
3359 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3360 $res{'nparents'} = length($1);
3361 $res{'from_mode'} = [ split(' ', $2) ];
3362 $res{'to_mode'} = pop @{$res{'from_mode'}};
3363 $res{'from_id'} = [ split(' ', $3) ];
3364 $res{'to_id'} = pop @{$res{'from_id'}};
3365 $res{'status'} = [ split('', $4) ];
3366 $res{'to_file'} = unquote($5);
3368 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3369 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3370 $res{'commit'} = $1;
3373 return wantarray ? %res : \%res;
3376 # wrapper: return parsed line of git-diff-tree "raw" output
3377 # (the argument might be raw line, or parsed info)
3378 sub parsed_difftree_line {
3379 my $line_or_ref = shift;
3381 if (ref($line_or_ref) eq "HASH") {
3382 # pre-parsed (or generated by hand)
3383 return $line_or_ref;
3384 } else {
3385 return parse_difftree_raw_line($line_or_ref);
3389 # parse line of git-ls-tree output
3390 sub parse_ls_tree_line {
3391 my $line = shift;
3392 my %opts = @_;
3393 my %res;
3395 if ($opts{'-l'}) {
3396 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3397 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3399 $res{'mode'} = $1;
3400 $res{'type'} = $2;
3401 $res{'hash'} = $3;
3402 $res{'size'} = $4;
3403 if ($opts{'-z'}) {
3404 $res{'name'} = $5;
3405 } else {
3406 $res{'name'} = unquote($5);
3408 } else {
3409 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3410 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3412 $res{'mode'} = $1;
3413 $res{'type'} = $2;
3414 $res{'hash'} = $3;
3415 if ($opts{'-z'}) {
3416 $res{'name'} = $4;
3417 } else {
3418 $res{'name'} = unquote($4);
3422 return wantarray ? %res : \%res;
3425 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3426 sub parse_from_to_diffinfo {
3427 my ($diffinfo, $from, $to, @parents) = @_;
3429 if ($diffinfo->{'nparents'}) {
3430 # combined diff
3431 $from->{'file'} = [];
3432 $from->{'href'} = [];
3433 fill_from_file_info($diffinfo, @parents)
3434 unless exists $diffinfo->{'from_file'};
3435 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3436 $from->{'file'}[$i] =
3437 defined $diffinfo->{'from_file'}[$i] ?
3438 $diffinfo->{'from_file'}[$i] :
3439 $diffinfo->{'to_file'};
3440 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3441 $from->{'href'}[$i] = href(action=>"blob",
3442 hash_base=>$parents[$i],
3443 hash=>$diffinfo->{'from_id'}[$i],
3444 file_name=>$from->{'file'}[$i]);
3445 } else {
3446 $from->{'href'}[$i] = undef;
3449 } else {
3450 # ordinary (not combined) diff
3451 $from->{'file'} = $diffinfo->{'from_file'};
3452 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3453 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3454 hash=>$diffinfo->{'from_id'},
3455 file_name=>$from->{'file'});
3456 } else {
3457 delete $from->{'href'};
3461 $to->{'file'} = $diffinfo->{'to_file'};
3462 if (!is_deleted($diffinfo)) { # file exists in result
3463 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3464 hash=>$diffinfo->{'to_id'},
3465 file_name=>$to->{'file'});
3466 } else {
3467 delete $to->{'href'};
3471 ## ......................................................................
3472 ## parse to array of hashes functions
3474 sub git_get_heads_list {
3475 my ($limit, @classes) = @_;
3476 @classes = ('heads') unless @classes;
3477 my @patterns = map { "refs/$_" } @classes;
3478 my @headslist;
3480 open my $fd, '-|', git_cmd(), 'for-each-ref',
3481 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3482 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3483 @patterns
3484 or return;
3485 while (my $line = <$fd>) {
3486 my %ref_item;
3488 chomp $line;
3489 my ($refinfo, $committerinfo) = split(/\0/, $line);
3490 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3491 my ($committer, $epoch, $tz) =
3492 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3493 $ref_item{'fullname'} = $name;
3494 $name =~ s!^refs/(?:head|remote)s/!!;
3496 $ref_item{'name'} = $name;
3497 $ref_item{'id'} = $hash;
3498 $ref_item{'title'} = $title || '(no commit message)';
3499 $ref_item{'epoch'} = $epoch;
3500 if ($epoch) {
3501 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3502 } else {
3503 $ref_item{'age'} = "unknown";
3506 push @headslist, \%ref_item;
3508 close $fd;
3510 return wantarray ? @headslist : \@headslist;
3513 sub git_get_tags_list {
3514 my $limit = shift;
3515 my @tagslist;
3517 open my $fd, '-|', git_cmd(), 'for-each-ref',
3518 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3519 '--format=%(objectname) %(objecttype) %(refname) '.
3520 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3521 'refs/tags'
3522 or return;
3523 while (my $line = <$fd>) {
3524 my %ref_item;
3526 chomp $line;
3527 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3528 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3529 my ($creator, $epoch, $tz) =
3530 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3531 $ref_item{'fullname'} = $name;
3532 $name =~ s!^refs/tags/!!;
3534 $ref_item{'type'} = $type;
3535 $ref_item{'id'} = $id;
3536 $ref_item{'name'} = $name;
3537 if ($type eq "tag") {
3538 $ref_item{'subject'} = $title;
3539 $ref_item{'reftype'} = $reftype;
3540 $ref_item{'refid'} = $refid;
3541 } else {
3542 $ref_item{'reftype'} = $type;
3543 $ref_item{'refid'} = $id;
3546 if ($type eq "tag" || $type eq "commit") {
3547 $ref_item{'epoch'} = $epoch;
3548 if ($epoch) {
3549 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3550 } else {
3551 $ref_item{'age'} = "unknown";
3555 push @tagslist, \%ref_item;
3557 close $fd;
3559 return wantarray ? @tagslist : \@tagslist;
3562 ## ----------------------------------------------------------------------
3563 ## filesystem-related functions
3565 sub get_file_owner {
3566 my $path = shift;
3568 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3569 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3570 if (!defined $gcos) {
3571 return undef;
3573 my $owner = $gcos;
3574 $owner =~ s/[,;].*$//;
3575 return to_utf8($owner);
3578 # assume that file exists
3579 sub insert_file {
3580 my $filename = shift;
3582 open my $fd, '<', $filename;
3583 print map { to_utf8($_) } <$fd>;
3584 close $fd;
3587 ## ......................................................................
3588 ## mimetype related functions
3590 sub mimetype_guess_file {
3591 my $filename = shift;
3592 my $mimemap = shift;
3593 -r $mimemap or return undef;
3595 my %mimemap;
3596 open(my $mh, '<', $mimemap) or return undef;
3597 while (<$mh>) {
3598 next if m/^#/; # skip comments
3599 my ($mimetype, @exts) = split(/\s+/);
3600 foreach my $ext (@exts) {
3601 $mimemap{$ext} = $mimetype;
3604 close($mh);
3606 $filename =~ /\.([^.]*)$/;
3607 return $mimemap{$1};
3610 sub mimetype_guess {
3611 my $filename = shift;
3612 my $mime;
3613 $filename =~ /\./ or return undef;
3615 if ($mimetypes_file) {
3616 my $file = $mimetypes_file;
3617 if ($file !~ m!^/!) { # if it is relative path
3618 # it is relative to project
3619 $file = "$projectroot/$project/$file";
3621 $mime = mimetype_guess_file($filename, $file);
3623 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3624 return $mime;
3627 sub blob_mimetype {
3628 my $fd = shift;
3629 my $filename = shift;
3631 if ($filename) {
3632 my $mime = mimetype_guess($filename);
3633 $mime and return $mime;
3636 # just in case
3637 return $default_blob_plain_mimetype unless $fd;
3639 if (-T $fd) {
3640 return 'text/plain';
3641 } elsif (! $filename) {
3642 return 'application/octet-stream';
3643 } elsif ($filename =~ m/\.png$/i) {
3644 return 'image/png';
3645 } elsif ($filename =~ m/\.gif$/i) {
3646 return 'image/gif';
3647 } elsif ($filename =~ m/\.jpe?g$/i) {
3648 return 'image/jpeg';
3649 } else {
3650 return 'application/octet-stream';
3654 sub blob_contenttype {
3655 my ($fd, $file_name, $type) = @_;
3657 $type ||= blob_mimetype($fd, $file_name);
3658 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3659 $type .= "; charset=$default_text_plain_charset";
3662 return $type;
3665 # guess file syntax for syntax highlighting; return undef if no highlighting
3666 # the name of syntax can (in the future) depend on syntax highlighter used
3667 sub guess_file_syntax {
3668 my ($highlight, $mimetype, $file_name) = @_;
3669 return undef unless ($highlight && defined $file_name);
3670 my $basename = basename($file_name, '.in');
3671 return $highlight_basename{$basename}
3672 if exists $highlight_basename{$basename};
3674 $basename =~ /\.([^.]*)$/;
3675 my $ext = $1 or return undef;
3676 return $highlight_ext{$ext}
3677 if exists $highlight_ext{$ext};
3679 return undef;
3682 # run highlighter and return FD of its output,
3683 # or return original FD if no highlighting
3684 sub run_highlighter {
3685 my ($fd, $highlight, $syntax) = @_;
3686 return $fd unless ($highlight && defined $syntax);
3688 close $fd;
3689 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3690 quote_command($highlight_bin).
3691 " --replace-tabs=8 --fragment --syntax $syntax |"
3692 or die_error(500, "Couldn't open file or run syntax highlighter");
3693 return $fd;
3696 ## ======================================================================
3697 ## functions printing HTML: header, footer, error page
3699 sub get_page_title {
3700 my $title = to_utf8($site_name);
3702 return $title unless (defined $project);
3703 $title .= " - " . to_utf8($project);
3705 return $title unless (defined $action);
3706 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3708 return $title unless (defined $file_name);
3709 $title .= " - " . esc_path($file_name);
3710 if ($action eq "tree" && $file_name !~ m|/$|) {
3711 $title .= "/";
3714 return $title;
3717 sub get_content_type_html {
3718 # require explicit support from the UA if we are to send the page as
3719 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3720 # we have to do this because MSIE sometimes globs '*/*', pretending to
3721 # support xhtml+xml but choking when it gets what it asked for.
3722 if (defined $cgi->http('HTTP_ACCEPT') &&
3723 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3724 $cgi->Accept('application/xhtml+xml') != 0) {
3725 return 'application/xhtml+xml';
3726 } else {
3727 return 'text/html';
3731 sub print_feed_meta {
3732 if (defined $project) {
3733 my %href_params = get_feed_info();
3734 if (!exists $href_params{'-title'}) {
3735 $href_params{'-title'} = 'log';
3738 foreach my $format (qw(RSS Atom)) {
3739 my $type = lc($format);
3740 my %link_attr = (
3741 '-rel' => 'alternate',
3742 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3743 '-type' => "application/$type+xml"
3746 $href_params{'action'} = $type;
3747 $link_attr{'-href'} = href(%href_params);
3748 print "<link ".
3749 "rel=\"$link_attr{'-rel'}\" ".
3750 "title=\"$link_attr{'-title'}\" ".
3751 "href=\"$link_attr{'-href'}\" ".
3752 "type=\"$link_attr{'-type'}\" ".
3753 "/>\n";
3755 $href_params{'extra_options'} = '--no-merges';
3756 $link_attr{'-href'} = href(%href_params);
3757 $link_attr{'-title'} .= ' (no merges)';
3758 print "<link ".
3759 "rel=\"$link_attr{'-rel'}\" ".
3760 "title=\"$link_attr{'-title'}\" ".
3761 "href=\"$link_attr{'-href'}\" ".
3762 "type=\"$link_attr{'-type'}\" ".
3763 "/>\n";
3766 } else {
3767 printf('<link rel="alternate" title="%s projects list" '.
3768 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3769 esc_attr($site_name), href(project=>undef, action=>"project_index"));
3770 printf('<link rel="alternate" title="%s projects feeds" '.
3771 'href="%s" type="text/x-opml" />'."\n",
3772 esc_attr($site_name), href(project=>undef, action=>"opml"));
3776 sub print_header_links {
3777 my $status = shift;
3779 # print out each stylesheet that exist, providing backwards capability
3780 # for those people who defined $stylesheet in a config file
3781 if (defined $stylesheet) {
3782 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3783 } else {
3784 foreach my $stylesheet (@stylesheets) {
3785 next unless $stylesheet;
3786 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3789 print_feed_meta()
3790 if ($status eq '200 OK');
3791 if (defined $favicon) {
3792 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
3796 sub print_nav_breadcrumbs {
3797 my %opts = @_;
3799 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3800 if (defined $project) {
3801 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3802 if (defined $action) {
3803 my $action_print = $action ;
3804 if (defined $opts{-action_extra}) {
3805 $action_print = $cgi->a({-href => href(action=>$action)},
3806 $action);
3808 print " / $action_print";
3810 if (defined $opts{-action_extra}) {
3811 print " / $opts{-action_extra}";
3813 print "\n";
3817 sub print_search_form {
3818 if (!defined $searchtext) {
3819 $searchtext = "";
3821 my $search_hash;
3822 if (defined $hash_base) {
3823 $search_hash = $hash_base;
3824 } elsif (defined $hash) {
3825 $search_hash = $hash;
3826 } else {
3827 $search_hash = "HEAD";
3829 my $action = $my_uri;
3830 my $use_pathinfo = gitweb_check_feature('pathinfo');
3831 if ($use_pathinfo) {
3832 $action .= "/".esc_url($project);
3834 print $cgi->startform(-method => "get", -action => $action) .
3835 "<div class=\"search\">\n" .
3836 (!$use_pathinfo &&
3837 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3838 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3839 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3840 $cgi->popup_menu(-name => 'st', -default => 'commit',
3841 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3842 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3843 " search:\n",
3844 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3845 "<span title=\"Extended regular expression\">" .
3846 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3847 -checked => $search_use_regexp) .
3848 "</span>" .
3849 "</div>" .
3850 $cgi->end_form() . "\n";
3853 sub git_header_html {
3854 my $status = shift || "200 OK";
3855 my $expires = shift;
3856 my %opts = @_;
3858 my $title = get_page_title();
3859 my $content_type = get_content_type_html();
3860 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3861 -status=> $status, -expires => $expires)
3862 unless ($opts{'-no_http_header'});
3863 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3864 print <<EOF;
3865 <?xml version="1.0" encoding="utf-8"?>
3866 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3867 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3868 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3869 <!-- git core binaries version $git_version -->
3870 <head>
3871 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3872 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3873 <meta name="robots" content="index, nofollow"/>
3874 <title>$title</title>
3876 # the stylesheet, favicon etc urls won't work correctly with path_info
3877 # unless we set the appropriate base URL
3878 if ($ENV{'PATH_INFO'}) {
3879 print "<base href=\"".esc_url($base_url)."\" />\n";
3881 print_header_links($status);
3882 print "</head>\n" .
3883 "<body>\n";
3885 if (defined $site_header && -f $site_header) {
3886 insert_file($site_header);
3889 print "<div class=\"page_header\">\n";
3890 if (defined $logo) {
3891 print $cgi->a({-href => esc_url($logo_url),
3892 -title => $logo_label},
3893 $cgi->img({-src => esc_url($logo),
3894 -width => 72, -height => 27,
3895 -alt => "git",
3896 -class => "logo"}));
3898 print_nav_breadcrumbs(%opts);
3899 print "</div>\n";
3901 my $have_search = gitweb_check_feature('search');
3902 if (defined $project && $have_search) {
3903 print_search_form();
3907 sub git_footer_html {
3908 my $feed_class = 'rss_logo';
3910 print "<div class=\"page_footer\">\n";
3911 if (defined $project) {
3912 my $descr = git_get_project_description($project);
3913 if (defined $descr) {
3914 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3917 my %href_params = get_feed_info();
3918 if (!%href_params) {
3919 $feed_class .= ' generic';
3921 $href_params{'-title'} ||= 'log';
3923 foreach my $format (qw(RSS Atom)) {
3924 $href_params{'action'} = lc($format);
3925 print $cgi->a({-href => href(%href_params),
3926 -title => "$href_params{'-title'} $format feed",
3927 -class => $feed_class}, $format)."\n";
3930 } else {
3931 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3932 -class => $feed_class}, "OPML") . " ";
3933 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3934 -class => $feed_class}, "TXT") . "\n";
3936 print "</div>\n"; # class="page_footer"
3938 if (defined $t0 && gitweb_check_feature('timed')) {
3939 print "<div id=\"generating_info\">\n";
3940 print 'This page took '.
3941 '<span id="generating_time" class="time_span">'.
3942 tv_interval($t0, [ gettimeofday() ]).
3943 ' seconds </span>'.
3944 ' and '.
3945 '<span id="generating_cmd">'.
3946 $number_of_git_cmds.
3947 '</span> git commands '.
3948 " to generate.\n";
3949 print "</div>\n"; # class="page_footer"
3952 if (defined $site_footer && -f $site_footer) {
3953 insert_file($site_footer);
3956 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
3957 if (defined $action &&
3958 $action eq 'blame_incremental') {
3959 print qq!<script type="text/javascript">\n!.
3960 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3961 qq! "!. href() .qq!");\n!.
3962 qq!</script>\n!;
3963 } else {
3964 my ($jstimezone, $tz_cookie, $datetime_class) =
3965 gitweb_get_feature('javascript-timezone');
3967 print qq!<script type="text/javascript">\n!.
3968 qq!window.onload = function () {\n!;
3969 if (gitweb_check_feature('javascript-actions')) {
3970 print qq! fixLinks();\n!;
3972 if ($jstimezone && $tz_cookie && $datetime_class) {
3973 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
3974 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
3976 print qq!};\n!.
3977 qq!</script>\n!;
3980 print "</body>\n" .
3981 "</html>";
3984 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3985 # Example: die_error(404, 'Hash not found')
3986 # By convention, use the following status codes (as defined in RFC 2616):
3987 # 400: Invalid or missing CGI parameters, or
3988 # requested object exists but has wrong type.
3989 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3990 # this server or project.
3991 # 404: Requested object/revision/project doesn't exist.
3992 # 500: The server isn't configured properly, or
3993 # an internal error occurred (e.g. failed assertions caused by bugs), or
3994 # an unknown error occurred (e.g. the git binary died unexpectedly).
3995 # 503: The server is currently unavailable (because it is overloaded,
3996 # or down for maintenance). Generally, this is a temporary state.
3997 sub die_error {
3998 my $status = shift || 500;
3999 my $error = esc_html(shift) || "Internal Server Error";
4000 my $extra = shift;
4001 my %opts = @_;
4003 my %http_responses = (
4004 400 => '400 Bad Request',
4005 403 => '403 Forbidden',
4006 404 => '404 Not Found',
4007 500 => '500 Internal Server Error',
4008 503 => '503 Service Unavailable',
4010 git_header_html($http_responses{$status}, undef, %opts);
4011 print <<EOF;
4012 <div class="page_body">
4013 <br /><br />
4014 $status - $error
4015 <br />
4017 if (defined $extra) {
4018 print "<hr />\n" .
4019 "$extra\n";
4021 print "</div>\n";
4023 git_footer_html();
4024 goto DONE_GITWEB
4025 unless ($opts{'-error_handler'});
4028 ## ----------------------------------------------------------------------
4029 ## functions printing or outputting HTML: navigation
4031 sub git_print_page_nav {
4032 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4033 $extra = '' if !defined $extra; # pager or formats
4035 my @navs = qw(summary shortlog log commit commitdiff tree);
4036 if ($suppress) {
4037 @navs = grep { $_ ne $suppress } @navs;
4040 my %arg = map { $_ => {action=>$_} } @navs;
4041 if (defined $head) {
4042 for (qw(commit commitdiff)) {
4043 $arg{$_}{'hash'} = $head;
4045 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4046 for (qw(shortlog log)) {
4047 $arg{$_}{'hash'} = $head;
4052 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4053 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4055 my @actions = gitweb_get_feature('actions');
4056 my %repl = (
4057 '%' => '%',
4058 'n' => $project, # project name
4059 'f' => $git_dir, # project path within filesystem
4060 'h' => $treehead || '', # current hash ('h' parameter)
4061 'b' => $treebase || '', # hash base ('hb' parameter)
4063 while (@actions) {
4064 my ($label, $link, $pos) = splice(@actions,0,3);
4065 # insert
4066 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4067 # munch munch
4068 $link =~ s/%([%nfhb])/$repl{$1}/g;
4069 $arg{$label}{'_href'} = $link;
4072 print "<div class=\"page_nav\">\n" .
4073 (join " | ",
4074 map { $_ eq $current ?
4075 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4076 } @navs);
4077 print "<br/>\n$extra<br/>\n" .
4078 "</div>\n";
4081 # returns a submenu for the nagivation of the refs views (tags, heads,
4082 # remotes) with the current view disabled and the remotes view only
4083 # available if the feature is enabled
4084 sub format_ref_views {
4085 my ($current) = @_;
4086 my @ref_views = qw{tags heads};
4087 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4088 return join " | ", map {
4089 $_ eq $current ? $_ :
4090 $cgi->a({-href => href(action=>$_)}, $_)
4091 } @ref_views
4094 sub format_paging_nav {
4095 my ($action, $page, $has_next_link) = @_;
4096 my $paging_nav;
4099 if ($page > 0) {
4100 $paging_nav .=
4101 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4102 " &sdot; " .
4103 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4104 -accesskey => "p", -title => "Alt-p"}, "prev");
4105 } else {
4106 $paging_nav .= "first &sdot; prev";
4109 if ($has_next_link) {
4110 $paging_nav .= " &sdot; " .
4111 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4112 -accesskey => "n", -title => "Alt-n"}, "next");
4113 } else {
4114 $paging_nav .= " &sdot; next";
4117 return $paging_nav;
4120 ## ......................................................................
4121 ## functions printing or outputting HTML: div
4123 sub git_print_header_div {
4124 my ($action, $title, $hash, $hash_base) = @_;
4125 my %args = ();
4127 $args{'action'} = $action;
4128 $args{'hash'} = $hash if $hash;
4129 $args{'hash_base'} = $hash_base if $hash_base;
4131 print "<div class=\"header\">\n" .
4132 $cgi->a({-href => href(%args), -class => "title"},
4133 $title ? $title : $action) .
4134 "\n</div>\n";
4137 sub format_repo_url {
4138 my ($name, $url) = @_;
4139 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4142 # Group output by placing it in a DIV element and adding a header.
4143 # Options for start_div() can be provided by passing a hash reference as the
4144 # first parameter to the function.
4145 # Options to git_print_header_div() can be provided by passing an array
4146 # reference. This must follow the options to start_div if they are present.
4147 # The content can be a scalar, which is output as-is, a scalar reference, which
4148 # is output after html escaping, an IO handle passed either as *handle or
4149 # *handle{IO}, or a function reference. In the latter case all following
4150 # parameters will be taken as argument to the content function call.
4151 sub git_print_section {
4152 my ($div_args, $header_args, $content);
4153 my $arg = shift;
4154 if (ref($arg) eq 'HASH') {
4155 $div_args = $arg;
4156 $arg = shift;
4158 if (ref($arg) eq 'ARRAY') {
4159 $header_args = $arg;
4160 $arg = shift;
4162 $content = $arg;
4164 print $cgi->start_div($div_args);
4165 git_print_header_div(@$header_args);
4167 if (ref($content) eq 'CODE') {
4168 $content->(@_);
4169 } elsif (ref($content) eq 'SCALAR') {
4170 print esc_html($$content);
4171 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4172 print <$content>;
4173 } elsif (!ref($content) && defined($content)) {
4174 print $content;
4177 print $cgi->end_div;
4180 sub format_timestamp_html {
4181 my $date = shift;
4182 my $strtime = $date->{'rfc2822'};
4184 my (undef, undef, $datetime_class) =
4185 gitweb_get_feature('javascript-timezone');
4186 if ($datetime_class) {
4187 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4190 my $localtime_format = '(%02d:%02d %s)';
4191 if ($date->{'hour_local'} < 6) {
4192 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4194 $strtime .= ' ' .
4195 sprintf($localtime_format,
4196 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4198 return $strtime;
4201 # Outputs the author name and date in long form
4202 sub git_print_authorship {
4203 my $co = shift;
4204 my %opts = @_;
4205 my $tag = $opts{-tag} || 'div';
4206 my $author = $co->{'author_name'};
4208 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4209 print "<$tag class=\"author_date\">" .
4210 format_search_author($author, "author", esc_html($author)) .
4211 " [".format_timestamp_html(\%ad)."]".
4212 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4213 "</$tag>\n";
4216 # Outputs table rows containing the full author or committer information,
4217 # in the format expected for 'commit' view (& similar).
4218 # Parameters are a commit hash reference, followed by the list of people
4219 # to output information for. If the list is empty it defaults to both
4220 # author and committer.
4221 sub git_print_authorship_rows {
4222 my $co = shift;
4223 # too bad we can't use @people = @_ || ('author', 'committer')
4224 my @people = @_;
4225 @people = ('author', 'committer') unless @people;
4226 foreach my $who (@people) {
4227 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4228 print "<tr><td>$who</td><td>" .
4229 format_search_author($co->{"${who}_name"}, $who,
4230 esc_html($co->{"${who}_name"})) . " " .
4231 format_search_author($co->{"${who}_email"}, $who,
4232 esc_html("<" . $co->{"${who}_email"} . ">")) .
4233 "</td><td rowspan=\"2\">" .
4234 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4235 "</td></tr>\n" .
4236 "<tr>" .
4237 "<td></td><td>" .
4238 format_timestamp_html(\%wd) .
4239 "</td>" .
4240 "</tr>\n";
4244 sub git_print_page_path {
4245 my $name = shift;
4246 my $type = shift;
4247 my $hb = shift;
4250 print "<div class=\"page_path\">";
4251 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4252 -title => 'tree root'}, to_utf8("[$project]"));
4253 print " / ";
4254 if (defined $name) {
4255 my @dirname = split '/', $name;
4256 my $basename = pop @dirname;
4257 my $fullname = '';
4259 foreach my $dir (@dirname) {
4260 $fullname .= ($fullname ? '/' : '') . $dir;
4261 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4262 hash_base=>$hb),
4263 -title => $fullname}, esc_path($dir));
4264 print " / ";
4266 if (defined $type && $type eq 'blob') {
4267 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4268 hash_base=>$hb),
4269 -title => $name}, esc_path($basename));
4270 print '&nbsp;&nbsp;&nbsp;&nbsp;
4271 <a id="lineNoToggle" href="#" onclick="toggleLineNumbers();"></a>
4272 <script>
4273 function toggleLineNumbers() {
4274 e = document.getElementById("lineNoStyle");
4275 e2 = document.getElementById("lineNoToggle");
4276 if (e2.innerHTML == "[Hide line numbers]") {
4277 e.innerHTML = ".linenr { display:none; }";
4278 e2.innerHTML = "[Show line numbers]";
4280 else {
4281 e.innerHTML = "";
4282 e2.innerHTML = "[Hide line numbers]";
4285 var style = document.createElement("style");
4286 style.setAttribute("id", "lineNoStyle");
4287 document.getElementsByTagName("head")[0].appendChild(style);
4288 toggleLineNumbers();
4289 </script>
4291 } elsif (defined $type && $type eq 'tree') {
4292 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4293 hash_base=>$hb),
4294 -title => $name}, esc_path($basename));
4295 print " / ";
4296 } else {
4297 print esc_path($basename);
4300 print "<br/></div>\n";
4303 sub git_print_log {
4304 my $log = shift;
4305 my %opts = @_;
4307 if ($opts{'-remove_title'}) {
4308 # remove title, i.e. first line of log
4309 shift @$log;
4311 # remove leading empty lines
4312 while (defined $log->[0] && $log->[0] eq "") {
4313 shift @$log;
4316 # print log
4317 my $signoff = 0;
4318 my $empty = 0;
4319 foreach my $line (@$log) {
4320 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4321 $signoff = 1;
4322 $empty = 0;
4323 if (! $opts{'-remove_signoff'}) {
4324 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4325 next;
4326 } else {
4327 # remove signoff lines
4328 next;
4330 } else {
4331 $signoff = 0;
4334 # print only one empty line
4335 # do not print empty line after signoff
4336 if ($line eq "") {
4337 next if ($empty || $signoff);
4338 $empty = 1;
4339 } else {
4340 $empty = 0;
4343 print format_log_line_html($line) . "<br/>\n";
4346 if ($opts{'-final_empty_line'}) {
4347 # end with single empty line
4348 print "<br/>\n" unless $empty;
4352 # return link target (what link points to)
4353 sub git_get_link_target {
4354 my $hash = shift;
4355 my $link_target;
4357 # read link
4358 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4359 or return;
4361 local $/ = undef;
4362 $link_target = <$fd>;
4364 close $fd
4365 or return;
4367 return $link_target;
4370 # given link target, and the directory (basedir) the link is in,
4371 # return target of link relative to top directory (top tree);
4372 # return undef if it is not possible (including absolute links).
4373 sub normalize_link_target {
4374 my ($link_target, $basedir) = @_;
4376 # absolute symlinks (beginning with '/') cannot be normalized
4377 return if (substr($link_target, 0, 1) eq '/');
4379 # normalize link target to path from top (root) tree (dir)
4380 my $path;
4381 if ($basedir) {
4382 $path = $basedir . '/' . $link_target;
4383 } else {
4384 # we are in top (root) tree (dir)
4385 $path = $link_target;
4388 # remove //, /./, and /../
4389 my @path_parts;
4390 foreach my $part (split('/', $path)) {
4391 # discard '.' and ''
4392 next if (!$part || $part eq '.');
4393 # handle '..'
4394 if ($part eq '..') {
4395 if (@path_parts) {
4396 pop @path_parts;
4397 } else {
4398 # link leads outside repository (outside top dir)
4399 return;
4401 } else {
4402 push @path_parts, $part;
4405 $path = join('/', @path_parts);
4407 return $path;
4410 # print tree entry (row of git_tree), but without encompassing <tr> element
4411 sub git_print_tree_entry {
4412 my ($t, $basedir, $hash_base, $have_blame) = @_;
4414 my %base_key = ();
4415 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4417 # The format of a table row is: mode list link. Where mode is
4418 # the mode of the entry, list is the name of the entry, an href,
4419 # and link is the action links of the entry.
4421 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4422 if (exists $t->{'size'}) {
4423 print "<td class=\"size\">$t->{'size'}</td>\n";
4425 if ($t->{'type'} eq "blob") {
4426 print "<td class=\"list\">" .
4427 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4428 file_name=>"$basedir$t->{'name'}", %base_key),
4429 -class => "list"}, esc_path($t->{'name'}));
4430 if (S_ISLNK(oct $t->{'mode'})) {
4431 my $link_target = git_get_link_target($t->{'hash'});
4432 if ($link_target) {
4433 my $norm_target = normalize_link_target($link_target, $basedir);
4434 if (defined $norm_target) {
4435 print " -> " .
4436 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4437 file_name=>$norm_target),
4438 -title => $norm_target}, esc_path($link_target));
4439 } else {
4440 print " -> " . esc_path($link_target);
4444 print "</td>\n";
4445 print "<td class=\"link\">";
4446 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4447 file_name=>"$basedir$t->{'name'}", %base_key)},
4448 "blob");
4449 if ($have_blame) {
4450 print " | " .
4451 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4452 file_name=>"$basedir$t->{'name'}", %base_key)},
4453 "blame");
4455 if (defined $hash_base) {
4456 print " | " .
4457 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4458 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4459 "history");
4461 print " | " .
4462 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4463 file_name=>"$basedir$t->{'name'}")},
4464 "raw");
4465 print "</td>\n";
4467 } elsif ($t->{'type'} eq "tree") {
4468 print "<td class=\"list\">";
4469 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4470 file_name=>"$basedir$t->{'name'}",
4471 %base_key)},
4472 esc_path($t->{'name'}));
4473 print "</td>\n";
4474 print "<td class=\"link\">";
4475 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4476 file_name=>"$basedir$t->{'name'}",
4477 %base_key)},
4478 "tree");
4479 if (defined $hash_base) {
4480 print " | " .
4481 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4482 file_name=>"$basedir$t->{'name'}")},
4483 "history");
4485 print "</td>\n";
4486 } else {
4487 # unknown object: we can only present history for it
4488 # (this includes 'commit' object, i.e. submodule support)
4489 print "<td class=\"list\">" .
4490 esc_path($t->{'name'}) .
4491 "</td>\n";
4492 print "<td class=\"link\">";
4493 if (defined $hash_base) {
4494 print $cgi->a({-href => href(action=>"history",
4495 hash_base=>$hash_base,
4496 file_name=>"$basedir$t->{'name'}")},
4497 "history");
4499 print "</td>\n";
4503 ## ......................................................................
4504 ## functions printing large fragments of HTML
4506 # get pre-image filenames for merge (combined) diff
4507 sub fill_from_file_info {
4508 my ($diff, @parents) = @_;
4510 $diff->{'from_file'} = [ ];
4511 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4512 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4513 if ($diff->{'status'}[$i] eq 'R' ||
4514 $diff->{'status'}[$i] eq 'C') {
4515 $diff->{'from_file'}[$i] =
4516 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4520 return $diff;
4523 # is current raw difftree line of file deletion
4524 sub is_deleted {
4525 my $diffinfo = shift;
4527 return $diffinfo->{'to_id'} eq ('0' x 40);
4530 # does patch correspond to [previous] difftree raw line
4531 # $diffinfo - hashref of parsed raw diff format
4532 # $patchinfo - hashref of parsed patch diff format
4533 # (the same keys as in $diffinfo)
4534 sub is_patch_split {
4535 my ($diffinfo, $patchinfo) = @_;
4537 return defined $diffinfo && defined $patchinfo
4538 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4542 sub git_difftree_body {
4543 my ($difftree, $hash, @parents) = @_;
4544 my ($parent) = $parents[0];
4545 my $have_blame = gitweb_check_feature('blame');
4546 print "<div class=\"list_head\">\n";
4547 if ($#{$difftree} > 10) {
4548 print(($#{$difftree} + 1) . " files changed:\n");
4550 print "</div>\n";
4552 print "<table class=\"" .
4553 (@parents > 1 ? "combined " : "") .
4554 "diff_tree\">\n";
4556 # header only for combined diff in 'commitdiff' view
4557 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4558 if ($has_header) {
4559 # table header
4560 print "<thead><tr>\n" .
4561 "<th></th><th></th>\n"; # filename, patchN link
4562 for (my $i = 0; $i < @parents; $i++) {
4563 my $par = $parents[$i];
4564 print "<th>" .
4565 $cgi->a({-href => href(action=>"commitdiff",
4566 hash=>$hash, hash_parent=>$par),
4567 -title => 'commitdiff to parent number ' .
4568 ($i+1) . ': ' . substr($par,0,7)},
4569 $i+1) .
4570 "&nbsp;</th>\n";
4572 print "</tr></thead>\n<tbody>\n";
4575 my $alternate = 1;
4576 my $patchno = 0;
4577 foreach my $line (@{$difftree}) {
4578 my $diff = parsed_difftree_line($line);
4580 if ($alternate) {
4581 print "<tr class=\"dark\">\n";
4582 } else {
4583 print "<tr class=\"light\">\n";
4585 $alternate ^= 1;
4587 if (exists $diff->{'nparents'}) { # combined diff
4589 fill_from_file_info($diff, @parents)
4590 unless exists $diff->{'from_file'};
4592 if (!is_deleted($diff)) {
4593 # file exists in the result (child) commit
4594 print "<td>" .
4595 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4596 file_name=>$diff->{'to_file'},
4597 hash_base=>$hash),
4598 -class => "list"}, esc_path($diff->{'to_file'})) .
4599 "</td>\n";
4600 } else {
4601 print "<td>" .
4602 esc_path($diff->{'to_file'}) .
4603 "</td>\n";
4606 if ($action eq 'commitdiff') {
4607 # link to patch
4608 $patchno++;
4609 print "<td class=\"link\">" .
4610 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4611 "patch") .
4612 " | " .
4613 "</td>\n";
4616 my $has_history = 0;
4617 my $not_deleted = 0;
4618 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4619 my $hash_parent = $parents[$i];
4620 my $from_hash = $diff->{'from_id'}[$i];
4621 my $from_path = $diff->{'from_file'}[$i];
4622 my $status = $diff->{'status'}[$i];
4624 $has_history ||= ($status ne 'A');
4625 $not_deleted ||= ($status ne 'D');
4627 if ($status eq 'A') {
4628 print "<td class=\"link\" align=\"right\"> | </td>\n";
4629 } elsif ($status eq 'D') {
4630 print "<td class=\"link\">" .
4631 $cgi->a({-href => href(action=>"blob",
4632 hash_base=>$hash,
4633 hash=>$from_hash,
4634 file_name=>$from_path)},
4635 "blob" . ($i+1)) .
4636 " | </td>\n";
4637 } else {
4638 if ($diff->{'to_id'} eq $from_hash) {
4639 print "<td class=\"link nochange\">";
4640 } else {
4641 print "<td class=\"link\">";
4643 print $cgi->a({-href => href(action=>"blobdiff",
4644 hash=>$diff->{'to_id'},
4645 hash_parent=>$from_hash,
4646 hash_base=>$hash,
4647 hash_parent_base=>$hash_parent,
4648 file_name=>$diff->{'to_file'},
4649 file_parent=>$from_path)},
4650 "diff" . ($i+1)) .
4651 " | </td>\n";
4655 print "<td class=\"link\">";
4656 if ($not_deleted) {
4657 print $cgi->a({-href => href(action=>"blob",
4658 hash=>$diff->{'to_id'},
4659 file_name=>$diff->{'to_file'},
4660 hash_base=>$hash)},
4661 "blob");
4662 print " | " if ($has_history);
4664 if ($has_history) {
4665 print $cgi->a({-href => href(action=>"history",
4666 file_name=>$diff->{'to_file'},
4667 hash_base=>$hash)},
4668 "history");
4670 print "</td>\n";
4672 print "</tr>\n";
4673 next; # instead of 'else' clause, to avoid extra indent
4675 # else ordinary diff
4677 my ($to_mode_oct, $to_mode_str, $to_file_type);
4678 my ($from_mode_oct, $from_mode_str, $from_file_type);
4679 if ($diff->{'to_mode'} ne ('0' x 6)) {
4680 $to_mode_oct = oct $diff->{'to_mode'};
4681 if (S_ISREG($to_mode_oct)) { # only for regular file
4682 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4684 $to_file_type = file_type($diff->{'to_mode'});
4686 if ($diff->{'from_mode'} ne ('0' x 6)) {
4687 $from_mode_oct = oct $diff->{'from_mode'};
4688 if (S_ISREG($from_mode_oct)) { # only for regular file
4689 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4691 $from_file_type = file_type($diff->{'from_mode'});
4694 if ($diff->{'status'} eq "A") { # created
4695 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4696 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4697 $mode_chng .= "]</span>";
4698 print "<td>";
4699 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4700 hash_base=>$hash, file_name=>$diff->{'file'}),
4701 -class => "list"}, esc_path($diff->{'file'}));
4702 print "</td>\n";
4703 print "<td>$mode_chng</td>\n";
4704 print "<td class=\"link\">";
4705 if ($action eq 'commitdiff') {
4706 # link to patch
4707 $patchno++;
4708 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4709 "patch") .
4710 " | ";
4712 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4713 hash_base=>$hash, file_name=>$diff->{'file'})},
4714 "blob");
4715 print "</td>\n";
4717 } elsif ($diff->{'status'} eq "D") { # deleted
4718 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4719 print "<td>";
4720 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4721 hash_base=>$parent, file_name=>$diff->{'file'}),
4722 -class => "list"}, esc_path($diff->{'file'}));
4723 print "</td>\n";
4724 print "<td>$mode_chng</td>\n";
4725 print "<td class=\"link\">";
4726 if ($action eq 'commitdiff') {
4727 # link to patch
4728 $patchno++;
4729 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4730 "patch") .
4731 " | ";
4733 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4734 hash_base=>$parent, file_name=>$diff->{'file'})},
4735 "blob") . " | ";
4736 if ($have_blame) {
4737 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4738 file_name=>$diff->{'file'})},
4739 "blame") . " | ";
4741 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4742 file_name=>$diff->{'file'})},
4743 "history");
4744 print "</td>\n";
4746 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4747 my $mode_chnge = "";
4748 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4749 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4750 if ($from_file_type ne $to_file_type) {
4751 $mode_chnge .= " from $from_file_type to $to_file_type";
4753 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4754 if ($from_mode_str && $to_mode_str) {
4755 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4756 } elsif ($to_mode_str) {
4757 $mode_chnge .= " mode: $to_mode_str";
4760 $mode_chnge .= "]</span>\n";
4762 print "<td>";
4763 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4764 hash_base=>$hash, file_name=>$diff->{'file'}),
4765 -class => "list"}, esc_path($diff->{'file'}));
4766 print "</td>\n";
4767 print "<td>$mode_chnge</td>\n";
4768 print "<td class=\"link\">";
4769 if ($action eq 'commitdiff') {
4770 # link to patch
4771 $patchno++;
4772 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4773 "patch") .
4774 " | ";
4775 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4776 # "commit" view and modified file (not onlu mode changed)
4777 print $cgi->a({-href => href(action=>"blobdiff",
4778 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4779 hash_base=>$hash, hash_parent_base=>$parent,
4780 file_name=>$diff->{'file'})},
4781 "diff") .
4782 " | ";
4784 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4785 hash_base=>$hash, file_name=>$diff->{'file'})},
4786 "blob") . " | ";
4787 if ($have_blame) {
4788 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4789 file_name=>$diff->{'file'})},
4790 "blame") . " | ";
4792 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4793 file_name=>$diff->{'file'})},
4794 "history");
4795 print "</td>\n";
4797 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4798 my %status_name = ('R' => 'moved', 'C' => 'copied');
4799 my $nstatus = $status_name{$diff->{'status'}};
4800 my $mode_chng = "";
4801 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4802 # mode also for directories, so we cannot use $to_mode_str
4803 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4805 print "<td>" .
4806 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4807 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4808 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4809 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4810 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4811 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4812 -class => "list"}, esc_path($diff->{'from_file'})) .
4813 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4814 "<td class=\"link\">";
4815 if ($action eq 'commitdiff') {
4816 # link to patch
4817 $patchno++;
4818 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4819 "patch") .
4820 " | ";
4821 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4822 # "commit" view and modified file (not only pure rename or copy)
4823 print $cgi->a({-href => href(action=>"blobdiff",
4824 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4825 hash_base=>$hash, hash_parent_base=>$parent,
4826 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4827 "diff") .
4828 " | ";
4830 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4831 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4832 "blob") . " | ";
4833 if ($have_blame) {
4834 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4835 file_name=>$diff->{'to_file'})},
4836 "blame") . " | ";
4838 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4839 file_name=>$diff->{'to_file'})},
4840 "history");
4841 print "</td>\n";
4843 } # we should not encounter Unmerged (U) or Unknown (X) status
4844 print "</tr>\n";
4846 print "</tbody>" if $has_header;
4847 print "</table>\n";
4850 sub git_patchset_body {
4851 my ($fd, $difftree, $hash, @hash_parents) = @_;
4852 my ($hash_parent) = $hash_parents[0];
4854 my $is_combined = (@hash_parents > 1);
4855 my $patch_idx = 0;
4856 my $patch_number = 0;
4857 my $patch_line;
4858 my $diffinfo;
4859 my $to_name;
4860 my (%from, %to);
4862 print "<div class=\"patchset\">\n";
4864 # skip to first patch
4865 while ($patch_line = <$fd>) {
4866 chomp $patch_line;
4868 last if ($patch_line =~ m/^diff /);
4871 PATCH:
4872 while ($patch_line) {
4874 # parse "git diff" header line
4875 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4876 # $1 is from_name, which we do not use
4877 $to_name = unquote($2);
4878 $to_name =~ s!^b/!!;
4879 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4880 # $1 is 'cc' or 'combined', which we do not use
4881 $to_name = unquote($2);
4882 } else {
4883 $to_name = undef;
4886 # check if current patch belong to current raw line
4887 # and parse raw git-diff line if needed
4888 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4889 # this is continuation of a split patch
4890 print "<div class=\"patch cont\">\n";
4891 } else {
4892 # advance raw git-diff output if needed
4893 $patch_idx++ if defined $diffinfo;
4895 # read and prepare patch information
4896 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4898 # compact combined diff output can have some patches skipped
4899 # find which patch (using pathname of result) we are at now;
4900 if ($is_combined) {
4901 while ($to_name ne $diffinfo->{'to_file'}) {
4902 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4903 format_diff_cc_simplified($diffinfo, @hash_parents) .
4904 "</div>\n"; # class="patch"
4906 $patch_idx++;
4907 $patch_number++;
4909 last if $patch_idx > $#$difftree;
4910 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4914 # modifies %from, %to hashes
4915 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4917 # this is first patch for raw difftree line with $patch_idx index
4918 # we index @$difftree array from 0, but number patches from 1
4919 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4922 # git diff header
4923 #assert($patch_line =~ m/^diff /) if DEBUG;
4924 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4925 $patch_number++;
4926 # print "git diff" header
4927 print format_git_diff_header_line($patch_line, $diffinfo,
4928 \%from, \%to);
4930 # print extended diff header
4931 print "<div class=\"diff extended_header\">\n";
4932 EXTENDED_HEADER:
4933 while ($patch_line = <$fd>) {
4934 chomp $patch_line;
4936 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4938 print format_extended_diff_header_line($patch_line, $diffinfo,
4939 \%from, \%to);
4941 print "</div>\n"; # class="diff extended_header"
4943 # from-file/to-file diff header
4944 if (! $patch_line) {
4945 print "</div>\n"; # class="patch"
4946 last PATCH;
4948 next PATCH if ($patch_line =~ m/^diff /);
4949 #assert($patch_line =~ m/^---/) if DEBUG;
4951 my $last_patch_line = $patch_line;
4952 $patch_line = <$fd>;
4953 chomp $patch_line;
4954 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4956 print format_diff_from_to_header($last_patch_line, $patch_line,
4957 $diffinfo, \%from, \%to,
4958 @hash_parents);
4960 # the patch itself
4961 LINE:
4962 while ($patch_line = <$fd>) {
4963 chomp $patch_line;
4965 next PATCH if ($patch_line =~ m/^diff /);
4967 print format_diff_line($patch_line, \%from, \%to);
4970 } continue {
4971 print "</div>\n"; # class="patch"
4974 # for compact combined (--cc) format, with chunk and patch simplification
4975 # the patchset might be empty, but there might be unprocessed raw lines
4976 for (++$patch_idx if $patch_number > 0;
4977 $patch_idx < @$difftree;
4978 ++$patch_idx) {
4979 # read and prepare patch information
4980 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4982 # generate anchor for "patch" links in difftree / whatchanged part
4983 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4984 format_diff_cc_simplified($diffinfo, @hash_parents) .
4985 "</div>\n"; # class="patch"
4987 $patch_number++;
4990 if ($patch_number == 0) {
4991 if (@hash_parents > 1) {
4992 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4993 } else {
4994 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4998 print "</div>\n"; # class="patchset"
5001 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5003 # fills project list info (age, description, owner, category, forks)
5004 # for each project in the list, removing invalid projects from
5005 # returned list
5006 # NOTE: modifies $projlist, but does not remove entries from it
5007 sub fill_project_list_info {
5008 my $projlist = shift;
5009 my @projects;
5011 my $show_ctags = gitweb_check_feature('ctags');
5012 PROJECT:
5013 foreach my $pr (@$projlist) {
5014 my (@activity) = git_get_last_activity($pr->{'path'});
5015 unless (@activity) {
5016 next PROJECT;
5018 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5019 if (!defined $pr->{'descr'}) {
5020 my $descr = git_get_project_description($pr->{'path'}) || "";
5021 $descr = to_utf8($descr);
5022 $pr->{'descr_long'} = $descr;
5023 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5025 if (!defined $pr->{'owner'}) {
5026 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5028 if ($show_ctags) {
5029 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5031 if ($projects_list_group_categories && !defined $pr->{'category'}) {
5032 my $cat = git_get_project_category($pr->{'path'}) ||
5033 $project_list_default_category;
5034 $pr->{'category'} = to_utf8($cat);
5037 push @projects, $pr;
5040 return @projects;
5043 sub sort_projects_list {
5044 my ($projlist, $order) = @_;
5045 my @projects;
5047 my %order_info = (
5048 project => { key => 'path', type => 'str' },
5049 descr => { key => 'descr_long', type => 'str' },
5050 owner => { key => 'owner', type => 'str' },
5051 age => { key => 'age', type => 'num' }
5053 my $oi = $order_info{$order};
5054 return @$projlist unless defined $oi;
5055 if ($oi->{'type'} eq 'str') {
5056 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @$projlist;
5057 } else {
5058 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @$projlist;
5061 return @projects;
5064 # returns a hash of categories, containing the list of project
5065 # belonging to each category
5066 sub build_projlist_by_category {
5067 my ($projlist, $from, $to) = @_;
5068 my %categories;
5070 $from = 0 unless defined $from;
5071 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5073 for (my $i = $from; $i <= $to; $i++) {
5074 my $pr = $projlist->[$i];
5075 push @{$categories{ $pr->{'category'} }}, $pr;
5078 return wantarray ? %categories : \%categories;
5081 # print 'sort by' <th> element, generating 'sort by $name' replay link
5082 # if that order is not selected
5083 sub print_sort_th {
5084 print format_sort_th(@_);
5087 sub format_sort_th {
5088 my ($name, $order, $header) = @_;
5089 my $sort_th = "";
5090 $header ||= ucfirst($name);
5092 if ($order eq $name) {
5093 $sort_th .= "<th>$header</th>\n";
5094 } else {
5095 $sort_th .= "<th>" .
5096 $cgi->a({-href => href(-replay=>1, order=>$name),
5097 -class => "header"}, $header) .
5098 "</th>\n";
5101 return $sort_th;
5104 sub git_project_list_rows {
5105 my ($projlist, $from, $to, $check_forks) = @_;
5107 $from = 0 unless defined $from;
5108 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5110 my $alternate = 1;
5111 for (my $i = $from; $i <= $to; $i++) {
5112 my $pr = $projlist->[$i];
5114 if ($alternate) {
5115 print "<tr class=\"dark\">\n";
5116 } else {
5117 print "<tr class=\"light\">\n";
5119 $alternate ^= 1;
5121 if ($check_forks) {
5122 print "<td>";
5123 if ($pr->{'forks'}) {
5124 my $nforks = scalar @{$pr->{'forks'}};
5125 if ($nforks > 0) {
5126 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5127 -title => "$nforks forks"}, "+");
5128 } else {
5129 print $cgi->span({-title => "$nforks forks"}, "+");
5132 print "</td>\n";
5134 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5135 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
5136 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5137 -class => "list", -title => $pr->{'descr_long'}},
5138 esc_html($pr->{'descr'})) . "</td>\n" .
5139 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5140 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5141 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
5142 "<td class=\"link\">" .
5143 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5144 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5145 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5146 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5147 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5148 "</td>\n" .
5149 "</tr>\n";
5153 sub git_project_list_body {
5154 # actually uses global variable $project
5155 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5156 my @projects = @$projlist;
5158 my $check_forks = gitweb_check_feature('forks');
5159 my $show_ctags = gitweb_check_feature('ctags');
5160 my $tagfilter = $show_ctags ? $cgi->param('by_tag') : undef;
5161 $check_forks = undef
5162 if ($tagfilter || $searchtext);
5164 # filtering out forks before filling info allows to do less work
5165 @projects = filter_forks_from_projects_list(\@projects)
5166 if ($check_forks);
5167 @projects = fill_project_list_info(\@projects);
5168 # searching projects require filling to be run before it
5169 @projects = search_projects_list(\@projects,
5170 'searchtext' => $searchtext,
5171 'tagfilter' => $tagfilter)
5172 if ($tagfilter || $searchtext);
5174 $order ||= $default_projects_order;
5175 $from = 0 unless defined $from;
5176 $to = $#projects if (!defined $to || $#projects < $to);
5178 # short circuit
5179 if ($from > $to) {
5180 print "<center>\n".
5181 "<b>No such projects found</b><br />\n".
5182 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5183 "</center>\n<br />\n";
5184 return;
5187 @projects = sort_projects_list(\@projects, $order);
5189 if ($show_ctags) {
5190 my $ctags = git_gather_all_ctags(\@projects);
5191 my $cloud = git_populate_project_tagcloud($ctags);
5192 print git_show_project_tagcloud($cloud, 64);
5195 print "<table class=\"project_list\">\n";
5196 unless ($no_header) {
5197 print "<tr>\n";
5198 if ($check_forks) {
5199 print "<th></th>\n";
5201 print_sort_th('project', $order, 'Project');
5202 print_sort_th('descr', $order, 'Description');
5203 print_sort_th('owner', $order, 'Owner');
5204 print_sort_th('age', $order, 'Last Change');
5205 print "<th></th>\n" . # for links
5206 "</tr>\n";
5209 if ($projects_list_group_categories) {
5210 # only display categories with projects in the $from-$to window
5211 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5212 my %categories = build_projlist_by_category(\@projects, $from, $to);
5213 foreach my $cat (sort keys %categories) {
5214 unless ($cat eq "") {
5215 print "<tr>\n";
5216 if ($check_forks) {
5217 print "<td></td>\n";
5219 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5220 print "</tr>\n";
5223 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5225 } else {
5226 git_project_list_rows(\@projects, $from, $to, $check_forks);
5229 if (defined $extra) {
5230 print "<tr>\n";
5231 if ($check_forks) {
5232 print "<td></td>\n";
5234 print "<td colspan=\"5\">$extra</td>\n" .
5235 "</tr>\n";
5237 print "</table>\n";
5240 sub git_log_body {
5241 # uses global variable $project
5242 my ($commitlist, $from, $to, $refs, $extra) = @_;
5244 $from = 0 unless defined $from;
5245 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5247 for (my $i = 0; $i <= $to; $i++) {
5248 my %co = %{$commitlist->[$i]};
5249 next if !%co;
5250 my $commit = $co{'id'};
5251 my $ref = format_ref_marker($refs, $commit);
5252 git_print_header_div('commit',
5253 "<span class=\"age\">$co{'age_string'}</span>" .
5254 esc_html($co{'title'}) . $ref,
5255 $commit);
5256 print "<div class=\"title_text\">\n" .
5257 "<div class=\"log_link\">\n" .
5258 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5259 " | " .
5260 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5261 " | " .
5262 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5263 "<br/>\n" .
5264 "</div>\n";
5265 git_print_authorship(\%co, -tag => 'span');
5266 print "<br/>\n</div>\n";
5268 print "<div class=\"log_body\">\n";
5269 git_print_log($co{'comment'}, -final_empty_line=> 1);
5270 print "</div>\n";
5272 if ($extra) {
5273 print "<div class=\"page_nav\">\n";
5274 print "$extra\n";
5275 print "</div>\n";
5279 sub git_shortlog_body {
5280 # uses global variable $project
5281 my ($commitlist, $from, $to, $refs, $extra) = @_;
5283 $from = 0 unless defined $from;
5284 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5286 print "<table class=\"shortlog\">\n";
5287 my $alternate = 1;
5288 for (my $i = $from; $i <= $to; $i++) {
5289 my %co = %{$commitlist->[$i]};
5290 my $commit = $co{'id'};
5291 my $ref = format_ref_marker($refs, $commit);
5292 if ($alternate) {
5293 print "<tr class=\"dark\">\n";
5294 } else {
5295 print "<tr class=\"light\">\n";
5297 $alternate ^= 1;
5298 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5299 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5300 format_author_html('td', \%co, 10) . "<td>";
5301 print format_subject_html($co{'title'}, $co{'title_short'},
5302 href(action=>"commit", hash=>$commit), $ref);
5303 print "</td>\n" .
5304 "<td class=\"link\">" .
5305 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5306 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5307 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5308 my $snapshot_links = format_snapshot_links($commit);
5309 if (defined $snapshot_links) {
5310 print " | " . $snapshot_links;
5312 print "</td>\n" .
5313 "</tr>\n";
5315 if (defined $extra) {
5316 print "<tr>\n" .
5317 "<td colspan=\"4\">$extra</td>\n" .
5318 "</tr>\n";
5320 print "</table>\n";
5323 sub git_history_body {
5324 # Warning: assumes constant type (blob or tree) during history
5325 my ($commitlist, $from, $to, $refs, $extra,
5326 $file_name, $file_hash, $ftype) = @_;
5328 $from = 0 unless defined $from;
5329 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5331 print "<table class=\"history\">\n";
5332 my $alternate = 1;
5333 for (my $i = $from; $i <= $to; $i++) {
5334 my %co = %{$commitlist->[$i]};
5335 if (!%co) {
5336 next;
5338 my $commit = $co{'id'};
5340 my $ref = format_ref_marker($refs, $commit);
5342 if ($alternate) {
5343 print "<tr class=\"dark\">\n";
5344 } else {
5345 print "<tr class=\"light\">\n";
5347 $alternate ^= 1;
5348 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5349 # shortlog: format_author_html('td', \%co, 10)
5350 format_author_html('td', \%co, 15, 3) . "<td>";
5351 # originally git_history used chop_str($co{'title'}, 50)
5352 print format_subject_html($co{'title'}, $co{'title_short'},
5353 href(action=>"commit", hash=>$commit), $ref);
5354 print "</td>\n" .
5355 "<td class=\"link\">" .
5356 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5357 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5359 if ($ftype eq 'blob') {
5360 my $blob_current = $file_hash;
5361 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5362 if (defined $blob_current && defined $blob_parent &&
5363 $blob_current ne $blob_parent) {
5364 print " | " .
5365 $cgi->a({-href => href(action=>"blobdiff",
5366 hash=>$blob_current, hash_parent=>$blob_parent,
5367 hash_base=>$hash_base, hash_parent_base=>$commit,
5368 file_name=>$file_name)},
5369 "diff to current");
5372 print "</td>\n" .
5373 "</tr>\n";
5375 if (defined $extra) {
5376 print "<tr>\n" .
5377 "<td colspan=\"4\">$extra</td>\n" .
5378 "</tr>\n";
5380 print "</table>\n";
5383 sub git_tags_body {
5384 # uses global variable $project
5385 my ($taglist, $from, $to, $extra) = @_;
5386 $from = 0 unless defined $from;
5387 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5389 print "<table class=\"tags\">\n";
5390 my $alternate = 1;
5391 for (my $i = $from; $i <= $to; $i++) {
5392 my $entry = $taglist->[$i];
5393 my %tag = %$entry;
5394 my $comment = $tag{'subject'};
5395 my $comment_short;
5396 if (defined $comment) {
5397 $comment_short = chop_str($comment, 30, 5);
5399 if ($alternate) {
5400 print "<tr class=\"dark\">\n";
5401 } else {
5402 print "<tr class=\"light\">\n";
5404 $alternate ^= 1;
5405 if (defined $tag{'age'}) {
5406 print "<td><i>$tag{'age'}</i></td>\n";
5407 } else {
5408 print "<td></td>\n";
5410 print "<td>" .
5411 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5412 -class => "list name"}, esc_html($tag{'name'})) .
5413 "</td>\n" .
5414 "<td>";
5415 if (defined $comment) {
5416 print format_subject_html($comment, $comment_short,
5417 href(action=>"tag", hash=>$tag{'id'}));
5419 print "</td>\n" .
5420 "<td class=\"selflink\">";
5421 if ($tag{'type'} eq "tag") {
5422 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5423 } else {
5424 print "&nbsp;";
5426 print "</td>\n" .
5427 "<td class=\"link\">" . " | " .
5428 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5429 if ($tag{'reftype'} eq "commit") {
5430 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5431 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5432 } elsif ($tag{'reftype'} eq "blob") {
5433 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5435 print "</td>\n" .
5436 "</tr>";
5438 if (defined $extra) {
5439 print "<tr>\n" .
5440 "<td colspan=\"5\">$extra</td>\n" .
5441 "</tr>\n";
5443 print "</table>\n";
5446 sub git_heads_body {
5447 # uses global variable $project
5448 my ($headlist, $head, $from, $to, $extra) = @_;
5449 $from = 0 unless defined $from;
5450 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5452 print "<table class=\"heads\">\n";
5453 my $alternate = 1;
5454 for (my $i = $from; $i <= $to; $i++) {
5455 my $entry = $headlist->[$i];
5456 my %ref = %$entry;
5457 my $curr = $ref{'id'} eq $head;
5458 if ($alternate) {
5459 print "<tr class=\"dark\">\n";
5460 } else {
5461 print "<tr class=\"light\">\n";
5463 $alternate ^= 1;
5464 print "<td><i>$ref{'age'}</i></td>\n" .
5465 ($curr ? "<td class=\"current_head\">" : "<td>") .
5466 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5467 -class => "list name"},esc_html($ref{'name'})) .
5468 "</td>\n" .
5469 "<td class=\"link\">" .
5470 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5471 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5472 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
5473 "</td>\n" .
5474 "</tr>";
5476 if (defined $extra) {
5477 print "<tr>\n" .
5478 "<td colspan=\"3\">$extra</td>\n" .
5479 "</tr>\n";
5481 print "</table>\n";
5484 # Display a single remote block
5485 sub git_remote_block {
5486 my ($remote, $rdata, $limit, $head) = @_;
5488 my $heads = $rdata->{'heads'};
5489 my $fetch = $rdata->{'fetch'};
5490 my $push = $rdata->{'push'};
5492 my $urls_table = "<table class=\"projects_list\">\n" ;
5494 if (defined $fetch) {
5495 if ($fetch eq $push) {
5496 $urls_table .= format_repo_url("URL", $fetch);
5497 } else {
5498 $urls_table .= format_repo_url("Fetch URL", $fetch);
5499 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
5501 } elsif (defined $push) {
5502 $urls_table .= format_repo_url("Push URL", $push);
5503 } else {
5504 $urls_table .= format_repo_url("", "No remote URL");
5507 $urls_table .= "</table>\n";
5509 my $dots;
5510 if (defined $limit && $limit < @$heads) {
5511 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
5514 print $urls_table;
5515 git_heads_body($heads, $head, 0, $limit, $dots);
5518 # Display a list of remote names with the respective fetch and push URLs
5519 sub git_remotes_list {
5520 my ($remotedata, $limit) = @_;
5521 print "<table class=\"heads\">\n";
5522 my $alternate = 1;
5523 my @remotes = sort keys %$remotedata;
5525 my $limited = $limit && $limit < @remotes;
5527 $#remotes = $limit - 1 if $limited;
5529 while (my $remote = shift @remotes) {
5530 my $rdata = $remotedata->{$remote};
5531 my $fetch = $rdata->{'fetch'};
5532 my $push = $rdata->{'push'};
5533 if ($alternate) {
5534 print "<tr class=\"dark\">\n";
5535 } else {
5536 print "<tr class=\"light\">\n";
5538 $alternate ^= 1;
5539 print "<td>" .
5540 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
5541 -class=> "list name"},esc_html($remote)) .
5542 "</td>";
5543 print "<td class=\"link\">" .
5544 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
5545 " | " .
5546 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
5547 "</td>";
5549 print "</tr>\n";
5552 if ($limited) {
5553 print "<tr>\n" .
5554 "<td colspan=\"3\">" .
5555 $cgi->a({-href => href(action=>"remotes")}, "...") .
5556 "</td>\n" . "</tr>\n";
5559 print "</table>";
5562 # Display remote heads grouped by remote, unless there are too many
5563 # remotes, in which case we only display the remote names
5564 sub git_remotes_body {
5565 my ($remotedata, $limit, $head) = @_;
5566 if ($limit and $limit < keys %$remotedata) {
5567 git_remotes_list($remotedata, $limit);
5568 } else {
5569 fill_remote_heads($remotedata);
5570 while (my ($remote, $rdata) = each %$remotedata) {
5571 git_print_section({-class=>"remote", -id=>$remote},
5572 ["remotes", $remote, $remote], sub {
5573 git_remote_block($remote, $rdata, $limit, $head);
5579 sub git_search_message {
5580 my %co = @_;
5582 my $greptype;
5583 if ($searchtype eq 'commit') {
5584 $greptype = "--grep=";
5585 } elsif ($searchtype eq 'author') {
5586 $greptype = "--author=";
5587 } elsif ($searchtype eq 'committer') {
5588 $greptype = "--committer=";
5590 $greptype .= $searchtext;
5591 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5592 $greptype, '--regexp-ignore-case',
5593 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5595 my $paging_nav = '';
5596 if ($page > 0) {
5597 $paging_nav .=
5598 $cgi->a({-href => href(-replay=>1, page=>undef)},
5599 "first") .
5600 " &sdot; " .
5601 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5602 -accesskey => "p", -title => "Alt-p"}, "prev");
5603 } else {
5604 $paging_nav .= "first &sdot; prev";
5606 my $next_link = '';
5607 if ($#commitlist >= 100) {
5608 $next_link =
5609 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5610 -accesskey => "n", -title => "Alt-n"}, "next");
5611 $paging_nav .= " &sdot; $next_link";
5612 } else {
5613 $paging_nav .= " &sdot; next";
5616 git_header_html();
5618 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5619 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5620 if ($page == 0 && !@commitlist) {
5621 print "<p>No match.</p>\n";
5622 } else {
5623 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5626 git_footer_html();
5629 sub git_search_changes {
5630 my %co = @_;
5632 local $/ = "\n";
5633 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5634 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5635 ($search_use_regexp ? '--pickaxe-regex' : ())
5636 or die_error(500, "Open git-log failed");
5638 git_header_html();
5640 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5641 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5643 print "<table class=\"pickaxe search\">\n";
5644 my $alternate = 1;
5645 undef %co;
5646 my @files;
5647 while (my $line = <$fd>) {
5648 chomp $line;
5649 next unless $line;
5651 my %set = parse_difftree_raw_line($line);
5652 if (defined $set{'commit'}) {
5653 # finish previous commit
5654 if (%co) {
5655 print "</td>\n" .
5656 "<td class=\"link\">" .
5657 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
5658 "commit") .
5659 " | " .
5660 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
5661 hash_base=>$co{'id'})},
5662 "tree") .
5663 "</td>\n" .
5664 "</tr>\n";
5667 if ($alternate) {
5668 print "<tr class=\"dark\">\n";
5669 } else {
5670 print "<tr class=\"light\">\n";
5672 $alternate ^= 1;
5673 %co = parse_commit($set{'commit'});
5674 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5675 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5676 "<td><i>$author</i></td>\n" .
5677 "<td>" .
5678 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5679 -class => "list subject"},
5680 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5681 } elsif (defined $set{'to_id'}) {
5682 next if ($set{'to_id'} =~ m/^0{40}$/);
5684 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5685 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5686 -class => "list"},
5687 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5688 "<br/>\n";
5691 close $fd;
5693 # finish last commit (warning: repetition!)
5694 if (%co) {
5695 print "</td>\n" .
5696 "<td class=\"link\">" .
5697 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
5698 "commit") .
5699 " | " .
5700 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
5701 hash_base=>$co{'id'})},
5702 "tree") .
5703 "</td>\n" .
5704 "</tr>\n";
5707 print "</table>\n";
5709 git_footer_html();
5712 sub git_search_files {
5713 my %co = @_;
5715 local $/ = "\n";
5716 open my $fd, "-|", git_cmd(), 'grep', '-n',
5717 $search_use_regexp ? ('-E', '-i') : '-F',
5718 $searchtext, $co{'tree'}
5719 or die_error(500, "Open git-grep failed");
5721 git_header_html();
5723 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5724 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5726 print "<table class=\"grep_search\">\n";
5727 my $alternate = 1;
5728 my $matches = 0;
5729 my $lastfile = '';
5730 while (my $line = <$fd>) {
5731 chomp $line;
5732 my ($file, $lno, $ltext, $binary);
5733 last if ($matches++ > 1000);
5734 if ($line =~ /^Binary file (.+) matches$/) {
5735 $file = $1;
5736 $binary = 1;
5737 } else {
5738 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5740 if ($file ne $lastfile) {
5741 $lastfile and print "</td></tr>\n";
5742 if ($alternate++) {
5743 print "<tr class=\"dark\">\n";
5744 } else {
5745 print "<tr class=\"light\">\n";
5747 print "<td class=\"list\">".
5748 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5749 file_name=>"$file"),
5750 -class => "list"}, esc_path($file));
5751 print "</td><td>\n";
5752 $lastfile = $file;
5754 if ($binary) {
5755 print "<div class=\"binary\">Binary file</div>\n";
5756 } else {
5757 $ltext = untabify($ltext);
5758 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5759 $ltext = esc_html($1, -nbsp=>1);
5760 $ltext .= '<span class="match">';
5761 $ltext .= esc_html($2, -nbsp=>1);
5762 $ltext .= '</span>';
5763 $ltext .= esc_html($3, -nbsp=>1);
5764 } else {
5765 $ltext = esc_html($ltext, -nbsp=>1);
5767 print "<div class=\"pre\">" .
5768 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5769 file_name=>"$file").'#l'.$lno,
5770 -class => "linenr"}, sprintf('%4i', $lno))
5771 . ' ' . $ltext . "</div>\n";
5774 if ($lastfile) {
5775 print "</td></tr>\n";
5776 if ($matches > 1000) {
5777 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5779 } else {
5780 print "<div class=\"diff nodifferences\">No matches found</div>\n";
5782 close $fd;
5784 print "</table>\n";
5786 git_footer_html();
5789 sub git_search_grep_body {
5790 my ($commitlist, $from, $to, $extra) = @_;
5791 $from = 0 unless defined $from;
5792 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5794 print "<table class=\"commit_search\">\n";
5795 my $alternate = 1;
5796 for (my $i = $from; $i <= $to; $i++) {
5797 my %co = %{$commitlist->[$i]};
5798 if (!%co) {
5799 next;
5801 my $commit = $co{'id'};
5802 if ($alternate) {
5803 print "<tr class=\"dark\">\n";
5804 } else {
5805 print "<tr class=\"light\">\n";
5807 $alternate ^= 1;
5808 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5809 format_author_html('td', \%co, 15, 5) .
5810 "<td>" .
5811 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5812 -class => "list subject"},
5813 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5814 my $comment = $co{'comment'};
5815 foreach my $line (@$comment) {
5816 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5817 my ($lead, $match, $trail) = ($1, $2, $3);
5818 $match = chop_str($match, 70, 5, 'center');
5819 my $contextlen = int((80 - length($match))/2);
5820 $contextlen = 30 if ($contextlen > 30);
5821 $lead = chop_str($lead, $contextlen, 10, 'left');
5822 $trail = chop_str($trail, $contextlen, 10, 'right');
5824 $lead = esc_html($lead);
5825 $match = esc_html($match);
5826 $trail = esc_html($trail);
5828 print "$lead<span class=\"match\">$match</span>$trail<br />";
5831 print "</td>\n" .
5832 "<td class=\"link\">" .
5833 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5834 " | " .
5835 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5836 " | " .
5837 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5838 print "</td>\n" .
5839 "</tr>\n";
5841 if (defined $extra) {
5842 print "<tr>\n" .
5843 "<td colspan=\"3\">$extra</td>\n" .
5844 "</tr>\n";
5846 print "</table>\n";
5849 ## ======================================================================
5850 ## ======================================================================
5851 ## actions
5853 sub git_project_list {
5854 my $order = $input_params{'order'};
5855 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5856 die_error(400, "Unknown order parameter");
5859 my @list = git_get_projects_list();
5860 if (!@list) {
5861 die_error(404, "No projects found");
5864 git_header_html();
5865 if (defined $home_text && -f $home_text) {
5866 print "<div class=\"index_include\">\n";
5867 insert_file($home_text);
5868 print "</div>\n";
5870 print $cgi->startform(-method => "get") .
5871 "<p class=\"projsearch\">Search:\n" .
5872 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5873 "</p>" .
5874 $cgi->end_form() . "\n";
5875 git_project_list_body(\@list, $order);
5876 git_footer_html();
5879 sub git_forks {
5880 my $order = $input_params{'order'};
5881 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5882 die_error(400, "Unknown order parameter");
5885 my @list = git_get_projects_list($project);
5886 if (!@list) {
5887 die_error(404, "No forks found");
5890 git_header_html();
5891 git_print_page_nav('','');
5892 git_print_header_div('summary', "$project forks");
5893 git_project_list_body(\@list, $order);
5894 git_footer_html();
5897 sub git_project_index {
5898 my @projects = git_get_projects_list();
5899 if (!@projects) {
5900 die_error(404, "No projects found");
5903 print $cgi->header(
5904 -type => 'text/plain',
5905 -charset => 'utf-8',
5906 -content_disposition => 'inline; filename="index.aux"');
5908 foreach my $pr (@projects) {
5909 if (!exists $pr->{'owner'}) {
5910 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5913 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5914 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5915 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5916 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5917 $path =~ s/ /\+/g;
5918 $owner =~ s/ /\+/g;
5920 print "$path $owner\n";
5924 sub git_summary {
5925 my $descr = git_get_project_description($project) || "none";
5926 my %co = parse_commit("HEAD");
5927 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5928 my $head = $co{'id'};
5929 my $remote_heads = gitweb_check_feature('remote_heads');
5931 my $owner = git_get_project_owner($project);
5933 my $refs = git_get_references();
5934 # These get_*_list functions return one more to allow us to see if
5935 # there are more ...
5936 my @taglist = git_get_tags_list(16);
5937 my @headlist = git_get_heads_list(16);
5938 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
5939 my @forklist;
5940 my $check_forks = gitweb_check_feature('forks');
5942 if ($check_forks) {
5943 # find forks of a project
5944 @forklist = git_get_projects_list($project);
5945 # filter out forks of forks
5946 @forklist = filter_forks_from_projects_list(\@forklist)
5947 if (@forklist);
5950 git_header_html();
5951 git_print_page_nav('summary','', $head);
5953 print "<div class=\"title\">&nbsp;</div>\n";
5954 print "<table class=\"projects_list\">\n" .
5955 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5956 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5957 if (defined $cd{'rfc2822'}) {
5958 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
5959 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
5962 # use per project git URL list in $projectroot/$project/cloneurl
5963 # or make project git URL from git base URL and project name
5964 my $url_tag = "URL";
5965 my @url_list = git_get_project_url_list($project);
5966 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5967 foreach my $git_url (@url_list) {
5968 next unless $git_url;
5969 print format_repo_url($url_tag, $git_url);
5970 $url_tag = "";
5973 # Tag cloud
5974 my $show_ctags = gitweb_check_feature('ctags');
5975 if ($show_ctags) {
5976 my $ctags = git_get_project_ctags($project);
5977 if (%$ctags) {
5978 # without ability to add tags, don't show if there are none
5979 my $cloud = git_populate_project_tagcloud($ctags);
5980 print "<tr id=\"metadata_ctags\">" .
5981 "<td>content tags</td>" .
5982 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
5983 "</tr>\n";
5987 print "</table>\n";
5989 # If XSS prevention is on, we don't include README.html.
5990 # TODO: Allow a readme in some safe format.
5991 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5992 print "<div class=\"title\">readme</div>\n" .
5993 "<div class=\"readme\">\n";
5994 insert_file("$projectroot/$project/README.html");
5995 print "\n</div>\n"; # class="readme"
5998 # we need to request one more than 16 (0..15) to check if
5999 # those 16 are all
6000 my @commitlist = $head ? parse_commits($head, 17) : ();
6001 if (@commitlist) {
6002 git_print_header_div('shortlog');
6003 git_shortlog_body(\@commitlist, 0, 15, $refs,
6004 $#commitlist <= 15 ? undef :
6005 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6008 if (@taglist) {
6009 git_print_header_div('tags');
6010 git_tags_body(\@taglist, 0, 15,
6011 $#taglist <= 15 ? undef :
6012 $cgi->a({-href => href(action=>"tags")}, "..."));
6015 if (@headlist) {
6016 git_print_header_div('heads');
6017 git_heads_body(\@headlist, $head, 0, 15,
6018 $#headlist <= 15 ? undef :
6019 $cgi->a({-href => href(action=>"heads")}, "..."));
6022 if (%remotedata) {
6023 git_print_header_div('remotes');
6024 git_remotes_body(\%remotedata, 15, $head);
6027 if (@forklist) {
6028 git_print_header_div('forks');
6029 git_project_list_body(\@forklist, 'age', 0, 15,
6030 $#forklist <= 15 ? undef :
6031 $cgi->a({-href => href(action=>"forks")}, "..."),
6032 'no_header');
6035 git_footer_html();
6038 sub git_tag {
6039 my %tag = parse_tag($hash);
6041 if (! %tag) {
6042 die_error(404, "Unknown tag object");
6045 my $head = git_get_head_hash($project);
6046 git_header_html();
6047 git_print_page_nav('','', $head,undef,$head);
6048 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6049 print "<div class=\"title_text\">\n" .
6050 "<table class=\"object_header\">\n" .
6051 "<tr>\n" .
6052 "<td>object</td>\n" .
6053 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6054 $tag{'object'}) . "</td>\n" .
6055 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6056 $tag{'type'}) . "</td>\n" .
6057 "</tr>\n";
6058 if (defined($tag{'author'})) {
6059 git_print_authorship_rows(\%tag, 'author');
6061 print "</table>\n\n" .
6062 "</div>\n";
6063 print "<div class=\"page_body\">";
6064 my $comment = $tag{'comment'};
6065 foreach my $line (@$comment) {
6066 chomp $line;
6067 print esc_html($line, -nbsp=>1) . "<br/>\n";
6069 print "</div>\n";
6070 git_footer_html();
6073 sub git_blame_common {
6074 my $format = shift || 'porcelain';
6075 if ($format eq 'porcelain' && $cgi->param('js')) {
6076 $format = 'incremental';
6077 $action = 'blame_incremental'; # for page title etc
6080 # permissions
6081 gitweb_check_feature('blame')
6082 or die_error(403, "Blame view not allowed");
6084 # error checking
6085 die_error(400, "No file name given") unless $file_name;
6086 $hash_base ||= git_get_head_hash($project);
6087 die_error(404, "Couldn't find base commit") unless $hash_base;
6088 my %co = parse_commit($hash_base)
6089 or die_error(404, "Commit not found");
6090 my $ftype = "blob";
6091 if (!defined $hash) {
6092 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6093 or die_error(404, "Error looking up file");
6094 } else {
6095 $ftype = git_get_type($hash);
6096 if ($ftype !~ "blob") {
6097 die_error(400, "Object is not a blob");
6101 my $fd;
6102 if ($format eq 'incremental') {
6103 # get file contents (as base)
6104 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6105 or die_error(500, "Open git-cat-file failed");
6106 } elsif ($format eq 'data') {
6107 # run git-blame --incremental
6108 open $fd, "-|", git_cmd(), "blame", "--incremental",
6109 $hash_base, "--", $file_name
6110 or die_error(500, "Open git-blame --incremental failed");
6111 } else {
6112 # run git-blame --porcelain
6113 open $fd, "-|", git_cmd(), "blame", '-p',
6114 $hash_base, '--', $file_name
6115 or die_error(500, "Open git-blame --porcelain failed");
6118 # incremental blame data returns early
6119 if ($format eq 'data') {
6120 print $cgi->header(
6121 -type=>"text/plain", -charset => "utf-8",
6122 -status=> "200 OK");
6123 local $| = 1; # output autoflush
6124 print while <$fd>;
6125 close $fd
6126 or print "ERROR $!\n";
6128 print 'END';
6129 if (defined $t0 && gitweb_check_feature('timed')) {
6130 print ' '.
6131 tv_interval($t0, [ gettimeofday() ]).
6132 ' '.$number_of_git_cmds;
6134 print "\n";
6136 return;
6139 # page header
6140 git_header_html();
6141 my $formats_nav =
6142 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6143 "blob") .
6144 " | ";
6145 if ($format eq 'incremental') {
6146 $formats_nav .=
6147 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6148 "blame") . " (non-incremental)";
6149 } else {
6150 $formats_nav .=
6151 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6152 "blame") . " (incremental)";
6154 $formats_nav .=
6155 " | " .
6156 $cgi->a({-href => href(action=>"history", -replay=>1)},
6157 "history") .
6158 " | " .
6159 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6160 "HEAD");
6161 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6162 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6163 git_print_page_path($file_name, $ftype, $hash_base);
6165 # page body
6166 if ($format eq 'incremental') {
6167 print "<noscript>\n<div class=\"error\"><center><b>\n".
6168 "This page requires JavaScript to run.\n Use ".
6169 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6170 'this page').
6171 " instead.\n".
6172 "</b></center></div>\n</noscript>\n";
6174 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6177 print qq!<div class="page_body">\n!;
6178 print qq!<div id="progress_info">... / ...</div>\n!
6179 if ($format eq 'incremental');
6180 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6181 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6182 qq!<thead>\n!.
6183 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6184 qq!</thead>\n!.
6185 qq!<tbody>\n!;
6187 my @rev_color = qw(light dark);
6188 my $num_colors = scalar(@rev_color);
6189 my $current_color = 0;
6191 if ($format eq 'incremental') {
6192 my $color_class = $rev_color[$current_color];
6194 #contents of a file
6195 my $linenr = 0;
6196 LINE:
6197 while (my $line = <$fd>) {
6198 chomp $line;
6199 $linenr++;
6201 print qq!<tr id="l$linenr" class="$color_class">!.
6202 qq!<td class="sha1"><a href=""> </a></td>!.
6203 qq!<td class="linenr">!.
6204 qq!<a class="linenr" href="">$linenr</a></td>!;
6205 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6206 print qq!</tr>\n!;
6209 } else { # porcelain, i.e. ordinary blame
6210 my %metainfo = (); # saves information about commits
6212 # blame data
6213 LINE:
6214 while (my $line = <$fd>) {
6215 chomp $line;
6216 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6217 # no <lines in group> for subsequent lines in group of lines
6218 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6219 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6220 if (!exists $metainfo{$full_rev}) {
6221 $metainfo{$full_rev} = { 'nprevious' => 0 };
6223 my $meta = $metainfo{$full_rev};
6224 my $data;
6225 while ($data = <$fd>) {
6226 chomp $data;
6227 last if ($data =~ s/^\t//); # contents of line
6228 if ($data =~ /^(\S+)(?: (.*))?$/) {
6229 $meta->{$1} = $2 unless exists $meta->{$1};
6231 if ($data =~ /^previous /) {
6232 $meta->{'nprevious'}++;
6235 my $short_rev = substr($full_rev, 0, 8);
6236 my $author = $meta->{'author'};
6237 my %date =
6238 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6239 my $date = $date{'iso-tz'};
6240 if ($group_size) {
6241 $current_color = ($current_color + 1) % $num_colors;
6243 my $tr_class = $rev_color[$current_color];
6244 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6245 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6246 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6247 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6248 if ($group_size) {
6249 print "<td class=\"sha1\"";
6250 print " title=\"". esc_html($author) . ", $date\"";
6251 print " rowspan=\"$group_size\"" if ($group_size > 1);
6252 print ">";
6253 print $cgi->a({-href => href(action=>"commit",
6254 hash=>$full_rev,
6255 file_name=>$file_name)},
6256 esc_html($short_rev));
6257 if ($group_size >= 2) {
6258 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6259 if (@author_initials) {
6260 print "<br />" .
6261 esc_html(join('', @author_initials));
6262 # or join('.', ...)
6265 print "</td>\n";
6267 # 'previous' <sha1 of parent commit> <filename at commit>
6268 if (exists $meta->{'previous'} &&
6269 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6270 $meta->{'parent'} = $1;
6271 $meta->{'file_parent'} = unquote($2);
6273 my $linenr_commit =
6274 exists($meta->{'parent'}) ?
6275 $meta->{'parent'} : $full_rev;
6276 my $linenr_filename =
6277 exists($meta->{'file_parent'}) ?
6278 $meta->{'file_parent'} : unquote($meta->{'filename'});
6279 my $blamed = href(action => 'blame',
6280 file_name => $linenr_filename,
6281 hash_base => $linenr_commit);
6282 print "<td class=\"linenr\">";
6283 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6284 -class => "linenr" },
6285 esc_html($lineno));
6286 print "</td>";
6287 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6288 print "</tr>\n";
6289 } # end while
6293 # footer
6294 print "</tbody>\n".
6295 "</table>\n"; # class="blame"
6296 print "</div>\n"; # class="blame_body"
6297 close $fd
6298 or print "Reading blob failed\n";
6300 git_footer_html();
6303 sub git_blame {
6304 git_blame_common();
6307 sub git_blame_incremental {
6308 git_blame_common('incremental');
6311 sub git_blame_data {
6312 git_blame_common('data');
6315 sub git_tags {
6316 my $head = git_get_head_hash($project);
6317 git_header_html();
6318 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6319 git_print_header_div('summary', $project);
6321 my @tagslist = git_get_tags_list();
6322 if (@tagslist) {
6323 git_tags_body(\@tagslist);
6325 git_footer_html();
6328 sub git_heads {
6329 my $head = git_get_head_hash($project);
6330 git_header_html();
6331 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6332 git_print_header_div('summary', $project);
6334 my @headslist = git_get_heads_list();
6335 if (@headslist) {
6336 git_heads_body(\@headslist, $head);
6338 git_footer_html();
6341 # used both for single remote view and for list of all the remotes
6342 sub git_remotes {
6343 gitweb_check_feature('remote_heads')
6344 or die_error(403, "Remote heads view is disabled");
6346 my $head = git_get_head_hash($project);
6347 my $remote = $input_params{'hash'};
6349 my $remotedata = git_get_remotes_list($remote);
6350 die_error(500, "Unable to get remote information") unless defined $remotedata;
6352 unless (%$remotedata) {
6353 die_error(404, defined $remote ?
6354 "Remote $remote not found" :
6355 "No remotes found");
6358 git_header_html(undef, undef, -action_extra => $remote);
6359 git_print_page_nav('', '', $head, undef, $head,
6360 format_ref_views($remote ? '' : 'remotes'));
6362 fill_remote_heads($remotedata);
6363 if (defined $remote) {
6364 git_print_header_div('remotes', "$remote remote for $project");
6365 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6366 } else {
6367 git_print_header_div('summary', "$project remotes");
6368 git_remotes_body($remotedata, undef, $head);
6371 git_footer_html();
6374 sub git_blob_plain {
6375 my $type = shift;
6376 my $expires;
6378 if (!defined $hash) {
6379 if (defined $file_name) {
6380 my $base = $hash_base || git_get_head_hash($project);
6381 $hash = git_get_hash_by_path($base, $file_name, "blob")
6382 or die_error(404, "Cannot find file");
6383 } else {
6384 die_error(400, "No file name defined");
6386 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6387 # blobs defined by non-textual hash id's can be cached
6388 $expires = "+1d";
6391 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6392 or die_error(500, "Open git-cat-file blob '$hash' failed");
6394 # content-type (can include charset)
6395 $type = blob_contenttype($fd, $file_name, $type);
6397 # "save as" filename, even when no $file_name is given
6398 my $save_as = "$hash";
6399 if (defined $file_name) {
6400 $save_as = $file_name;
6401 } elsif ($type =~ m/^text\//) {
6402 $save_as .= '.txt';
6405 # With XSS prevention on, blobs of all types except a few known safe
6406 # ones are served with "Content-Disposition: attachment" to make sure
6407 # they don't run in our security domain. For certain image types,
6408 # blob view writes an <img> tag referring to blob_plain view, and we
6409 # want to be sure not to break that by serving the image as an
6410 # attachment (though Firefox 3 doesn't seem to care).
6411 my $sandbox = $prevent_xss &&
6412 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
6414 # serve text/* as text/plain
6415 if ($prevent_xss &&
6416 ($type =~ m!^text/[a-z]+\b(.*)$! ||
6417 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
6418 my $rest = $1;
6419 $rest = defined $rest ? $rest : '';
6420 $type = "text/plain$rest";
6423 print $cgi->header(
6424 -type => $type,
6425 -expires => $expires,
6426 -content_disposition =>
6427 ($sandbox ? 'attachment' : 'inline')
6428 . '; filename="' . $save_as . '"');
6429 local $/ = undef;
6430 binmode STDOUT, ':raw';
6431 print <$fd>;
6432 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6433 close $fd;
6436 sub git_blob {
6437 my $expires;
6439 if (!defined $hash) {
6440 if (defined $file_name) {
6441 my $base = $hash_base || git_get_head_hash($project);
6442 $hash = git_get_hash_by_path($base, $file_name, "blob")
6443 or die_error(404, "Cannot find file");
6444 } else {
6445 die_error(400, "No file name defined");
6447 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6448 # blobs defined by non-textual hash id's can be cached
6449 $expires = "+1d";
6452 my $have_blame = gitweb_check_feature('blame');
6453 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6454 or die_error(500, "Couldn't cat $file_name, $hash");
6455 my $mimetype = blob_mimetype($fd, $file_name);
6456 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
6457 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
6458 close $fd;
6459 return git_blob_plain($mimetype);
6461 # we can have blame only for text/* mimetype
6462 $have_blame &&= ($mimetype =~ m!^text/!);
6464 my $highlight = gitweb_check_feature('highlight');
6465 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
6466 $fd = run_highlighter($fd, $highlight, $syntax)
6467 if $syntax;
6469 git_header_html(undef, $expires);
6470 my $formats_nav = '';
6471 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6472 if (defined $file_name) {
6473 if ($have_blame) {
6474 $formats_nav .=
6475 $cgi->a({-href => href(action=>"blame", -replay=>1)},
6476 "blame") .
6477 " | ";
6479 $formats_nav .=
6480 $cgi->a({-href => href(action=>"history", -replay=>1)},
6481 "history") .
6482 " | " .
6483 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6484 "raw") .
6485 " | " .
6486 $cgi->a({-href => href(action=>"blob",
6487 hash_base=>"HEAD", file_name=>$file_name)},
6488 "HEAD");
6489 } else {
6490 $formats_nav .=
6491 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6492 "raw");
6494 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6495 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6496 } else {
6497 print "<div class=\"page_nav\">\n" .
6498 "<br/><br/></div>\n" .
6499 "<div class=\"title\">".esc_html($hash)."</div>\n";
6501 git_print_page_path($file_name, "blob", $hash_base);
6502 print "<div class=\"page_body\">\n";
6503 if ($mimetype =~ m!^image/!) {
6504 print qq!<img type="!.esc_attr($mimetype).qq!"!;
6505 if ($file_name) {
6506 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
6508 print qq! src="! .
6509 href(action=>"blob_plain", hash=>$hash,
6510 hash_base=>$hash_base, file_name=>$file_name) .
6511 qq!" />\n!;
6512 } else {
6513 my $nr;
6514 while (my $line = <$fd>) {
6515 chomp $line;
6516 $nr++;
6517 $line = untabify($line);
6518 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
6519 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
6520 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
6523 close $fd
6524 or print "Reading blob failed.\n";
6525 print "</div>";
6526 git_footer_html();
6529 sub git_tree {
6530 if (!defined $hash_base) {
6531 $hash_base = "HEAD";
6533 if (!defined $hash) {
6534 if (defined $file_name) {
6535 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
6536 } else {
6537 $hash = $hash_base;
6540 die_error(404, "No such tree") unless defined($hash);
6542 my $show_sizes = gitweb_check_feature('show-sizes');
6543 my $have_blame = gitweb_check_feature('blame');
6545 my @entries = ();
6547 local $/ = "\0";
6548 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
6549 ($show_sizes ? '-l' : ()), @extra_options, $hash
6550 or die_error(500, "Open git-ls-tree failed");
6551 @entries = map { chomp; $_ } <$fd>;
6552 close $fd
6553 or die_error(404, "Reading tree failed");
6556 my $refs = git_get_references();
6557 my $ref = format_ref_marker($refs, $hash_base);
6558 git_header_html();
6559 my $basedir = '';
6560 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6561 my @views_nav = ();
6562 if (defined $file_name) {
6563 push @views_nav,
6564 $cgi->a({-href => href(action=>"history", -replay=>1)},
6565 "history"),
6566 $cgi->a({-href => href(action=>"tree",
6567 hash_base=>"HEAD", file_name=>$file_name)},
6568 "HEAD"),
6570 my $snapshot_links = format_snapshot_links($hash);
6571 if (defined $snapshot_links) {
6572 # FIXME: Should be available when we have no hash base as well.
6573 push @views_nav, $snapshot_links;
6575 git_print_page_nav('tree','', $hash_base, undef, undef,
6576 join(' | ', @views_nav));
6577 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
6578 } else {
6579 undef $hash_base;
6580 print "<div class=\"page_nav\">\n";
6581 print "<br/><br/></div>\n";
6582 print "<div class=\"title\">".esc_html($hash)."</div>\n";
6584 if (defined $file_name) {
6585 $basedir = $file_name;
6586 if ($basedir ne '' && substr($basedir, -1) ne '/') {
6587 $basedir .= '/';
6589 git_print_page_path($file_name, 'tree', $hash_base);
6591 print "<div class=\"page_body\">\n";
6592 print "<table class=\"tree\">\n";
6593 my $alternate = 1;
6594 # '..' (top directory) link if possible
6595 if (defined $hash_base &&
6596 defined $file_name && $file_name =~ m![^/]+$!) {
6597 if ($alternate) {
6598 print "<tr class=\"dark\">\n";
6599 } else {
6600 print "<tr class=\"light\">\n";
6602 $alternate ^= 1;
6604 my $up = $file_name;
6605 $up =~ s!/?[^/]+$!!;
6606 undef $up unless $up;
6607 # based on git_print_tree_entry
6608 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6609 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
6610 print '<td class="list">';
6611 print $cgi->a({-href => href(action=>"tree",
6612 hash_base=>$hash_base,
6613 file_name=>$up)},
6614 "..");
6615 print "</td>\n";
6616 print "<td class=\"link\"></td>\n";
6618 print "</tr>\n";
6620 foreach my $line (@entries) {
6621 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6623 if ($alternate) {
6624 print "<tr class=\"dark\">\n";
6625 } else {
6626 print "<tr class=\"light\">\n";
6628 $alternate ^= 1;
6630 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6632 print "</tr>\n";
6634 print "</table>\n" .
6635 "</div>";
6636 git_footer_html();
6639 sub snapshot_name {
6640 my ($project, $hash) = @_;
6642 # path/to/project.git -> project
6643 # path/to/project/.git -> project
6644 my $name = to_utf8($project);
6645 $name =~ s,([^/])/*\.git$,$1,;
6646 $name = basename($name);
6647 # sanitize name
6648 $name =~ s/[[:cntrl:]]/?/g;
6650 my $ver = $hash;
6651 if ($hash =~ /^[0-9a-fA-F]+$/) {
6652 # shorten SHA-1 hash
6653 my $full_hash = git_get_full_hash($project, $hash);
6654 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6655 $ver = git_get_short_hash($project, $hash);
6657 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6658 # tags don't need shortened SHA-1 hash
6659 $ver = $1;
6660 } else {
6661 # branches and other need shortened SHA-1 hash
6662 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6663 $ver = $1;
6665 $ver .= '-' . git_get_short_hash($project, $hash);
6667 # in case of hierarchical branch names
6668 $ver =~ s!/!.!g;
6670 # name = project-version_string
6671 $name = "$name-$ver";
6673 return wantarray ? ($name, $name) : $name;
6676 sub git_snapshot {
6677 my $format = $input_params{'snapshot_format'};
6678 if (!@snapshot_fmts) {
6679 die_error(403, "Snapshots not allowed");
6681 # default to first supported snapshot format
6682 $format ||= $snapshot_fmts[0];
6683 if ($format !~ m/^[a-z0-9]+$/) {
6684 die_error(400, "Invalid snapshot format parameter");
6685 } elsif (!exists($known_snapshot_formats{$format})) {
6686 die_error(400, "Unknown snapshot format");
6687 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6688 die_error(403, "Snapshot format not allowed");
6689 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6690 die_error(403, "Unsupported snapshot format");
6693 my $type = git_get_type("$hash^{}");
6694 if (!$type) {
6695 die_error(404, 'Object does not exist');
6696 } elsif ($type eq 'blob') {
6697 die_error(400, 'Object is not a tree-ish');
6700 my ($name, $prefix) = snapshot_name($project, $hash);
6701 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6702 my $cmd = quote_command(
6703 git_cmd(), 'archive',
6704 "--format=$known_snapshot_formats{$format}{'format'}",
6705 "--prefix=$prefix/", $hash);
6706 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6707 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6710 $filename =~ s/(["\\])/\\$1/g;
6711 print $cgi->header(
6712 -type => $known_snapshot_formats{$format}{'type'},
6713 -content_disposition => 'inline; filename="' . $filename . '"',
6714 -status => '200 OK');
6716 open my $fd, "-|", $cmd
6717 or die_error(500, "Execute git-archive failed");
6718 binmode STDOUT, ':raw';
6719 print <$fd>;
6720 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6721 close $fd;
6724 sub git_log_generic {
6725 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6727 my $head = git_get_head_hash($project);
6728 if (!defined $base) {
6729 $base = $head;
6731 if (!defined $page) {
6732 $page = 0;
6734 my $refs = git_get_references();
6736 my $commit_hash = $base;
6737 if (defined $parent) {
6738 $commit_hash = "$parent..$base";
6740 my @commitlist =
6741 parse_commits($commit_hash, 101, (100 * $page),
6742 defined $file_name ? ($file_name, "--full-history") : ());
6744 my $ftype;
6745 if (!defined $file_hash && defined $file_name) {
6746 # some commits could have deleted file in question,
6747 # and not have it in tree, but one of them has to have it
6748 for (my $i = 0; $i < @commitlist; $i++) {
6749 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6750 last if defined $file_hash;
6753 if (defined $file_hash) {
6754 $ftype = git_get_type($file_hash);
6756 if (defined $file_name && !defined $ftype) {
6757 die_error(500, "Unknown type of object");
6759 my %co;
6760 if (defined $file_name) {
6761 %co = parse_commit($base)
6762 or die_error(404, "Unknown commit object");
6766 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6767 my $next_link = '';
6768 if ($#commitlist >= 100) {
6769 $next_link =
6770 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6771 -accesskey => "n", -title => "Alt-n"}, "next");
6773 my $patch_max = gitweb_get_feature('patches');
6774 if ($patch_max && !defined $file_name) {
6775 if ($patch_max < 0 || @commitlist <= $patch_max) {
6776 $paging_nav .= " &sdot; " .
6777 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6778 "patches");
6782 git_header_html();
6783 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6784 if (defined $file_name) {
6785 git_print_header_div('commit', esc_html($co{'title'}), $base);
6786 } else {
6787 git_print_header_div('summary', $project)
6789 git_print_page_path($file_name, $ftype, $hash_base)
6790 if (defined $file_name);
6792 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6793 $file_name, $file_hash, $ftype);
6795 git_footer_html();
6798 sub git_log {
6799 git_log_generic('log', \&git_log_body,
6800 $hash, $hash_parent);
6803 sub git_commit {
6804 $hash ||= $hash_base || "HEAD";
6805 my %co = parse_commit($hash)
6806 or die_error(404, "Unknown commit object");
6808 my $parent = $co{'parent'};
6809 my $parents = $co{'parents'}; # listref
6811 # we need to prepare $formats_nav before any parameter munging
6812 my $formats_nav;
6813 if (!defined $parent) {
6814 # --root commitdiff
6815 $formats_nav .= '(initial)';
6816 } elsif (@$parents == 1) {
6817 # single parent commit
6818 $formats_nav .=
6819 '(parent: ' .
6820 $cgi->a({-href => href(action=>"commit",
6821 hash=>$parent)},
6822 esc_html(substr($parent, 0, 7))) .
6823 ')';
6824 } else {
6825 # merge commit
6826 $formats_nav .=
6827 '(merge: ' .
6828 join(' ', map {
6829 $cgi->a({-href => href(action=>"commit",
6830 hash=>$_)},
6831 esc_html(substr($_, 0, 7)));
6832 } @$parents ) .
6833 ')';
6835 if (gitweb_check_feature('patches') && @$parents <= 1) {
6836 $formats_nav .= " | " .
6837 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6838 "patch");
6841 if (!defined $parent) {
6842 $parent = "--root";
6844 my @difftree;
6845 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6846 @diff_opts,
6847 (@$parents <= 1 ? $parent : '-c'),
6848 $hash, "--"
6849 or die_error(500, "Open git-diff-tree failed");
6850 @difftree = map { chomp; $_ } <$fd>;
6851 close $fd or die_error(404, "Reading git-diff-tree failed");
6853 # non-textual hash id's can be cached
6854 my $expires;
6855 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6856 $expires = "+1d";
6858 my $refs = git_get_references();
6859 my $ref = format_ref_marker($refs, $co{'id'});
6861 git_header_html(undef, $expires);
6862 git_print_page_nav('commit', '',
6863 $hash, $co{'tree'}, $hash,
6864 $formats_nav);
6866 if (defined $co{'parent'}) {
6867 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6868 } else {
6869 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6871 print "<div class=\"title_text\">\n" .
6872 "<table class=\"object_header\">\n";
6873 git_print_authorship_rows(\%co);
6874 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6875 print "<tr>" .
6876 "<td>tree</td>" .
6877 "<td class=\"sha1\">" .
6878 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6879 class => "list"}, $co{'tree'}) .
6880 "</td>" .
6881 "<td class=\"link\">" .
6882 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6883 "tree");
6884 my $snapshot_links = format_snapshot_links($hash);
6885 if (defined $snapshot_links) {
6886 print " | " . $snapshot_links;
6888 print "</td>" .
6889 "</tr>\n";
6891 foreach my $par (@$parents) {
6892 print "<tr>" .
6893 "<td>parent</td>" .
6894 "<td class=\"sha1\">" .
6895 $cgi->a({-href => href(action=>"commit", hash=>$par),
6896 class => "list"}, $par) .
6897 "</td>" .
6898 "<td class=\"link\">" .
6899 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6900 " | " .
6901 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6902 "</td>" .
6903 "</tr>\n";
6905 print "</table>".
6906 "</div>\n";
6908 print "<div class=\"page_body\">\n";
6909 git_print_log($co{'comment'});
6910 print "</div>\n";
6912 git_difftree_body(\@difftree, $hash, @$parents);
6914 git_footer_html();
6917 sub git_object {
6918 # object is defined by:
6919 # - hash or hash_base alone
6920 # - hash_base and file_name
6921 my $type;
6923 # - hash or hash_base alone
6924 if ($hash || ($hash_base && !defined $file_name)) {
6925 my $object_id = $hash || $hash_base;
6927 open my $fd, "-|", quote_command(
6928 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6929 or die_error(404, "Object does not exist");
6930 $type = <$fd>;
6931 chomp $type;
6932 close $fd
6933 or die_error(404, "Object does not exist");
6935 # - hash_base and file_name
6936 } elsif ($hash_base && defined $file_name) {
6937 $file_name =~ s,/+$,,;
6939 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6940 or die_error(404, "Base object does not exist");
6942 # here errors should not hapen
6943 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6944 or die_error(500, "Open git-ls-tree failed");
6945 my $line = <$fd>;
6946 close $fd;
6948 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6949 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6950 die_error(404, "File or directory for given base does not exist");
6952 $type = $2;
6953 $hash = $3;
6954 } else {
6955 die_error(400, "Not enough information to find object");
6958 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6959 hash=>$hash, hash_base=>$hash_base,
6960 file_name=>$file_name),
6961 -status => '302 Found');
6964 sub git_blobdiff {
6965 my $format = shift || 'html';
6967 my $fd;
6968 my @difftree;
6969 my %diffinfo;
6970 my $expires;
6972 # preparing $fd and %diffinfo for git_patchset_body
6973 # new style URI
6974 if (defined $hash_base && defined $hash_parent_base) {
6975 if (defined $file_name) {
6976 # read raw output
6977 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6978 $hash_parent_base, $hash_base,
6979 "--", (defined $file_parent ? $file_parent : ()), $file_name
6980 or die_error(500, "Open git-diff-tree failed");
6981 @difftree = map { chomp; $_ } <$fd>;
6982 close $fd
6983 or die_error(404, "Reading git-diff-tree failed");
6984 @difftree
6985 or die_error(404, "Blob diff not found");
6987 } elsif (defined $hash &&
6988 $hash =~ /[0-9a-fA-F]{40}/) {
6989 # try to find filename from $hash
6991 # read filtered raw output
6992 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6993 $hash_parent_base, $hash_base, "--"
6994 or die_error(500, "Open git-diff-tree failed");
6995 @difftree =
6996 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6997 # $hash == to_id
6998 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6999 map { chomp; $_ } <$fd>;
7000 close $fd
7001 or die_error(404, "Reading git-diff-tree failed");
7002 @difftree
7003 or die_error(404, "Blob diff not found");
7005 } else {
7006 die_error(400, "Missing one of the blob diff parameters");
7009 if (@difftree > 1) {
7010 die_error(400, "Ambiguous blob diff specification");
7013 %diffinfo = parse_difftree_raw_line($difftree[0]);
7014 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7015 $file_name ||= $diffinfo{'to_file'};
7017 $hash_parent ||= $diffinfo{'from_id'};
7018 $hash ||= $diffinfo{'to_id'};
7020 # non-textual hash id's can be cached
7021 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7022 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7023 $expires = '+1d';
7026 # open patch output
7027 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7028 '-p', ($format eq 'html' ? "--full-index" : ()),
7029 $hash_parent_base, $hash_base,
7030 "--", (defined $file_parent ? $file_parent : ()), $file_name
7031 or die_error(500, "Open git-diff-tree failed");
7034 # old/legacy style URI -- not generated anymore since 1.4.3.
7035 if (!%diffinfo) {
7036 die_error('404 Not Found', "Missing one of the blob diff parameters")
7039 # header
7040 if ($format eq 'html') {
7041 my $formats_nav =
7042 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7043 "raw");
7044 git_header_html(undef, $expires);
7045 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7046 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7047 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7048 } else {
7049 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7050 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7052 if (defined $file_name) {
7053 git_print_page_path($file_name, "blob", $hash_base);
7054 } else {
7055 print "<div class=\"page_path\"></div>\n";
7058 } elsif ($format eq 'plain') {
7059 print $cgi->header(
7060 -type => 'text/plain',
7061 -charset => 'utf-8',
7062 -expires => $expires,
7063 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7065 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7067 } else {
7068 die_error(400, "Unknown blobdiff format");
7071 # patch
7072 if ($format eq 'html') {
7073 print "<div class=\"page_body\">\n";
7075 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
7076 close $fd;
7078 print "</div>\n"; # class="page_body"
7079 git_footer_html();
7081 } else {
7082 while (my $line = <$fd>) {
7083 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7084 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7086 print $line;
7088 last if $line =~ m!^\+\+\+!;
7090 local $/ = undef;
7091 print <$fd>;
7092 close $fd;
7096 sub git_blobdiff_plain {
7097 git_blobdiff('plain');
7100 sub git_commitdiff {
7101 my %params = @_;
7102 my $format = $params{-format} || 'html';
7104 my ($patch_max) = gitweb_get_feature('patches');
7105 if ($format eq 'patch') {
7106 die_error(403, "Patch view not allowed") unless $patch_max;
7109 $hash ||= $hash_base || "HEAD";
7110 my %co = parse_commit($hash)
7111 or die_error(404, "Unknown commit object");
7113 # choose format for commitdiff for merge
7114 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7115 $hash_parent = '--cc';
7117 # we need to prepare $formats_nav before almost any parameter munging
7118 my $formats_nav;
7119 if ($format eq 'html') {
7120 $formats_nav =
7121 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7122 "raw");
7123 if ($patch_max && @{$co{'parents'}} <= 1) {
7124 $formats_nav .= " | " .
7125 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7126 "patch");
7129 if (defined $hash_parent &&
7130 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7131 # commitdiff with two commits given
7132 my $hash_parent_short = $hash_parent;
7133 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7134 $hash_parent_short = substr($hash_parent, 0, 7);
7136 $formats_nav .=
7137 ' (from';
7138 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7139 if ($co{'parents'}[$i] eq $hash_parent) {
7140 $formats_nav .= ' parent ' . ($i+1);
7141 last;
7144 $formats_nav .= ': ' .
7145 $cgi->a({-href => href(action=>"commitdiff",
7146 hash=>$hash_parent)},
7147 esc_html($hash_parent_short)) .
7148 ')';
7149 } elsif (!$co{'parent'}) {
7150 # --root commitdiff
7151 $formats_nav .= ' (initial)';
7152 } elsif (scalar @{$co{'parents'}} == 1) {
7153 # single parent commit
7154 $formats_nav .=
7155 ' (parent: ' .
7156 $cgi->a({-href => href(action=>"commitdiff",
7157 hash=>$co{'parent'})},
7158 esc_html(substr($co{'parent'}, 0, 7))) .
7159 ')';
7160 } else {
7161 # merge commit
7162 if ($hash_parent eq '--cc') {
7163 $formats_nav .= ' | ' .
7164 $cgi->a({-href => href(action=>"commitdiff",
7165 hash=>$hash, hash_parent=>'-c')},
7166 'combined');
7167 } else { # $hash_parent eq '-c'
7168 $formats_nav .= ' | ' .
7169 $cgi->a({-href => href(action=>"commitdiff",
7170 hash=>$hash, hash_parent=>'--cc')},
7171 'compact');
7173 $formats_nav .=
7174 ' (merge: ' .
7175 join(' ', map {
7176 $cgi->a({-href => href(action=>"commitdiff",
7177 hash=>$_)},
7178 esc_html(substr($_, 0, 7)));
7179 } @{$co{'parents'}} ) .
7180 ')';
7184 my $hash_parent_param = $hash_parent;
7185 if (!defined $hash_parent_param) {
7186 # --cc for multiple parents, --root for parentless
7187 $hash_parent_param =
7188 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7191 # read commitdiff
7192 my $fd;
7193 my @difftree;
7194 if ($format eq 'html') {
7195 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7196 "--no-commit-id", "--patch-with-raw", "--full-index",
7197 $hash_parent_param, $hash, "--"
7198 or die_error(500, "Open git-diff-tree failed");
7200 while (my $line = <$fd>) {
7201 chomp $line;
7202 # empty line ends raw part of diff-tree output
7203 last unless $line;
7204 push @difftree, scalar parse_difftree_raw_line($line);
7207 } elsif ($format eq 'plain') {
7208 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7209 '-p', $hash_parent_param, $hash, "--"
7210 or die_error(500, "Open git-diff-tree failed");
7211 } elsif ($format eq 'patch') {
7212 # For commit ranges, we limit the output to the number of
7213 # patches specified in the 'patches' feature.
7214 # For single commits, we limit the output to a single patch,
7215 # diverging from the git-format-patch default.
7216 my @commit_spec = ();
7217 if ($hash_parent) {
7218 if ($patch_max > 0) {
7219 push @commit_spec, "-$patch_max";
7221 push @commit_spec, '-n', "$hash_parent..$hash";
7222 } else {
7223 if ($params{-single}) {
7224 push @commit_spec, '-1';
7225 } else {
7226 if ($patch_max > 0) {
7227 push @commit_spec, "-$patch_max";
7229 push @commit_spec, "-n";
7231 push @commit_spec, '--root', $hash;
7233 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7234 '--encoding=utf8', '--stdout', @commit_spec
7235 or die_error(500, "Open git-format-patch failed");
7236 } else {
7237 die_error(400, "Unknown commitdiff format");
7240 # non-textual hash id's can be cached
7241 my $expires;
7242 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7243 $expires = "+1d";
7246 # write commit message
7247 if ($format eq 'html') {
7248 my $refs = git_get_references();
7249 my $ref = format_ref_marker($refs, $co{'id'});
7251 git_header_html(undef, $expires);
7252 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7253 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7254 print "<div class=\"title_text\">\n" .
7255 "<table class=\"object_header\">\n";
7256 git_print_authorship_rows(\%co);
7257 print "</table>".
7258 "</div>\n";
7259 print "<div class=\"page_body\">\n";
7260 if (@{$co{'comment'}} > 1) {
7261 print "<div class=\"log\">\n";
7262 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7263 print "</div>\n"; # class="log"
7266 } elsif ($format eq 'plain') {
7267 my $refs = git_get_references("tags");
7268 my $tagname = git_get_rev_name_tags($hash);
7269 my $filename = basename($project) . "-$hash.patch";
7271 print $cgi->header(
7272 -type => 'text/plain',
7273 -charset => 'utf-8',
7274 -expires => $expires,
7275 -content_disposition => 'inline; filename="' . "$filename" . '"');
7276 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7277 print "From: " . to_utf8($co{'author'}) . "\n";
7278 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7279 print "Subject: " . to_utf8($co{'title'}) . "\n";
7281 print "X-Git-Tag: $tagname\n" if $tagname;
7282 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7284 foreach my $line (@{$co{'comment'}}) {
7285 print to_utf8($line) . "\n";
7287 print "---\n\n";
7288 } elsif ($format eq 'patch') {
7289 my $filename = basename($project) . "-$hash.patch";
7291 print $cgi->header(
7292 -type => 'text/plain',
7293 -charset => 'utf-8',
7294 -expires => $expires,
7295 -content_disposition => 'inline; filename="' . "$filename" . '"');
7298 # write patch
7299 if ($format eq 'html') {
7300 my $use_parents = !defined $hash_parent ||
7301 $hash_parent eq '-c' || $hash_parent eq '--cc';
7302 git_difftree_body(\@difftree, $hash,
7303 $use_parents ? @{$co{'parents'}} : $hash_parent);
7304 print "<br/>\n";
7306 git_patchset_body($fd, \@difftree, $hash,
7307 $use_parents ? @{$co{'parents'}} : $hash_parent);
7308 close $fd;
7309 print "</div>\n"; # class="page_body"
7310 git_footer_html();
7312 } elsif ($format eq 'plain') {
7313 local $/ = undef;
7314 print <$fd>;
7315 close $fd
7316 or print "Reading git-diff-tree failed\n";
7317 } elsif ($format eq 'patch') {
7318 local $/ = undef;
7319 print <$fd>;
7320 close $fd
7321 or print "Reading git-format-patch failed\n";
7325 sub git_commitdiff_plain {
7326 git_commitdiff(-format => 'plain');
7329 # format-patch-style patches
7330 sub git_patch {
7331 git_commitdiff(-format => 'patch', -single => 1);
7334 sub git_patches {
7335 git_commitdiff(-format => 'patch');
7338 sub git_history {
7339 git_log_generic('history', \&git_history_body,
7340 $hash_base, $hash_parent_base,
7341 $file_name, $hash);
7344 sub git_search {
7345 $searchtype ||= 'commit';
7347 # check if appropriate features are enabled
7348 gitweb_check_feature('search')
7349 or die_error(403, "Search is disabled");
7350 if ($searchtype eq 'pickaxe') {
7351 # pickaxe may take all resources of your box and run for several minutes
7352 # with every query - so decide by yourself how public you make this feature
7353 gitweb_check_feature('pickaxe')
7354 or die_error(403, "Pickaxe search is disabled");
7356 if ($searchtype eq 'grep') {
7357 # grep search might be potentially CPU-intensive, too
7358 gitweb_check_feature('grep')
7359 or die_error(403, "Grep search is disabled");
7362 if (!defined $searchtext) {
7363 die_error(400, "Text field is empty");
7365 if (!defined $hash) {
7366 $hash = git_get_head_hash($project);
7368 my %co = parse_commit($hash);
7369 if (!%co) {
7370 die_error(404, "Unknown commit object");
7372 if (!defined $page) {
7373 $page = 0;
7376 if ($searchtype eq 'commit' ||
7377 $searchtype eq 'author' ||
7378 $searchtype eq 'committer') {
7379 git_search_message(%co);
7380 } elsif ($searchtype eq 'pickaxe') {
7381 git_search_changes(%co);
7382 } elsif ($searchtype eq 'grep') {
7383 git_search_files(%co);
7384 } else {
7385 die_error(400, "Unknown search type");
7389 sub git_search_help {
7390 git_header_html();
7391 git_print_page_nav('','', $hash,$hash,$hash);
7392 print <<EOT;
7393 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7394 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7395 the pattern entered is recognized as the POSIX extended
7396 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7397 insensitive).</p>
7398 <dl>
7399 <dt><b>commit</b></dt>
7400 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7402 my $have_grep = gitweb_check_feature('grep');
7403 if ($have_grep) {
7404 print <<EOT;
7405 <dt><b>grep</b></dt>
7406 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7407 a different one) are searched for the given pattern. On large trees, this search can take
7408 a while and put some strain on the server, so please use it with some consideration. Note that
7409 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7410 case-sensitive.</dd>
7413 print <<EOT;
7414 <dt><b>author</b></dt>
7415 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7416 <dt><b>committer</b></dt>
7417 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7419 my $have_pickaxe = gitweb_check_feature('pickaxe');
7420 if ($have_pickaxe) {
7421 print <<EOT;
7422 <dt><b>pickaxe</b></dt>
7423 <dd>All commits that caused the string to appear or disappear from any file (changes that
7424 added, removed or "modified" the string) will be listed. This search can take a while and
7425 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7426 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7429 print "</dl>\n";
7430 git_footer_html();
7433 sub git_shortlog {
7434 git_log_generic('shortlog', \&git_shortlog_body,
7435 $hash, $hash_parent);
7438 ## ......................................................................
7439 ## feeds (RSS, Atom; OPML)
7441 sub git_feed {
7442 my $format = shift || 'atom';
7443 my $have_blame = gitweb_check_feature('blame');
7445 # Atom: http://www.atomenabled.org/developers/syndication/
7446 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7447 if ($format ne 'rss' && $format ne 'atom') {
7448 die_error(400, "Unknown web feed format");
7451 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7452 my $head = $hash || 'HEAD';
7453 my @commitlist = parse_commits($head, 150, 0, $file_name);
7455 my %latest_commit;
7456 my %latest_date;
7457 my $content_type = "application/$format+xml";
7458 if (defined $cgi->http('HTTP_ACCEPT') &&
7459 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7460 # browser (feed reader) prefers text/xml
7461 $content_type = 'text/xml';
7463 if (defined($commitlist[0])) {
7464 %latest_commit = %{$commitlist[0]};
7465 my $latest_epoch = $latest_commit{'committer_epoch'};
7466 %latest_date = parse_date($latest_epoch, $latest_commit{'comitter_tz'});
7467 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7468 if (defined $if_modified) {
7469 my $since;
7470 if (eval { require HTTP::Date; 1; }) {
7471 $since = HTTP::Date::str2time($if_modified);
7472 } elsif (eval { require Time::ParseDate; 1; }) {
7473 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7475 if (defined $since && $latest_epoch <= $since) {
7476 print $cgi->header(
7477 -type => $content_type,
7478 -charset => 'utf-8',
7479 -last_modified => $latest_date{'rfc2822'},
7480 -status => '304 Not Modified');
7481 return;
7484 print $cgi->header(
7485 -type => $content_type,
7486 -charset => 'utf-8',
7487 -last_modified => $latest_date{'rfc2822'});
7488 } else {
7489 print $cgi->header(
7490 -type => $content_type,
7491 -charset => 'utf-8');
7494 # Optimization: skip generating the body if client asks only
7495 # for Last-Modified date.
7496 return if ($cgi->request_method() eq 'HEAD');
7498 # header variables
7499 my $title = "$site_name - $project/$action";
7500 my $feed_type = 'log';
7501 if (defined $hash) {
7502 $title .= " - '$hash'";
7503 $feed_type = 'branch log';
7504 if (defined $file_name) {
7505 $title .= " :: $file_name";
7506 $feed_type = 'history';
7508 } elsif (defined $file_name) {
7509 $title .= " - $file_name";
7510 $feed_type = 'history';
7512 $title .= " $feed_type";
7513 my $descr = git_get_project_description($project);
7514 if (defined $descr) {
7515 $descr = esc_html($descr);
7516 } else {
7517 $descr = "$project " .
7518 ($format eq 'rss' ? 'RSS' : 'Atom') .
7519 " feed";
7521 my $owner = git_get_project_owner($project);
7522 $owner = esc_html($owner);
7524 #header
7525 my $alt_url;
7526 if (defined $file_name) {
7527 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7528 } elsif (defined $hash) {
7529 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7530 } else {
7531 $alt_url = href(-full=>1, action=>"summary");
7533 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7534 if ($format eq 'rss') {
7535 print <<XML;
7536 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7537 <channel>
7539 print "<title>$title</title>\n" .
7540 "<link>$alt_url</link>\n" .
7541 "<description>$descr</description>\n" .
7542 "<language>en</language>\n" .
7543 # project owner is responsible for 'editorial' content
7544 "<managingEditor>$owner</managingEditor>\n";
7545 if (defined $logo || defined $favicon) {
7546 # prefer the logo to the favicon, since RSS
7547 # doesn't allow both
7548 my $img = esc_url($logo || $favicon);
7549 print "<image>\n" .
7550 "<url>$img</url>\n" .
7551 "<title>$title</title>\n" .
7552 "<link>$alt_url</link>\n" .
7553 "</image>\n";
7555 if (%latest_date) {
7556 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7557 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7559 print "<generator>gitweb v.$version/$git_version</generator>\n";
7560 } elsif ($format eq 'atom') {
7561 print <<XML;
7562 <feed xmlns="http://www.w3.org/2005/Atom">
7564 print "<title>$title</title>\n" .
7565 "<subtitle>$descr</subtitle>\n" .
7566 '<link rel="alternate" type="text/html" href="' .
7567 $alt_url . '" />' . "\n" .
7568 '<link rel="self" type="' . $content_type . '" href="' .
7569 $cgi->self_url() . '" />' . "\n" .
7570 "<id>" . href(-full=>1) . "</id>\n" .
7571 # use project owner for feed author
7572 "<author><name>$owner</name></author>\n";
7573 if (defined $favicon) {
7574 print "<icon>" . esc_url($favicon) . "</icon>\n";
7576 if (defined $logo) {
7577 # not twice as wide as tall: 72 x 27 pixels
7578 print "<logo>" . esc_url($logo) . "</logo>\n";
7580 if (! %latest_date) {
7581 # dummy date to keep the feed valid until commits trickle in:
7582 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7583 } else {
7584 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7586 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7589 # contents
7590 for (my $i = 0; $i <= $#commitlist; $i++) {
7591 my %co = %{$commitlist[$i]};
7592 my $commit = $co{'id'};
7593 # we read 150, we always show 30 and the ones more recent than 48 hours
7594 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7595 last;
7597 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
7599 # get list of changed files
7600 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7601 $co{'parent'} || "--root",
7602 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7603 or next;
7604 my @difftree = map { chomp; $_ } <$fd>;
7605 close $fd
7606 or next;
7608 # print element (entry, item)
7609 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7610 if ($format eq 'rss') {
7611 print "<item>\n" .
7612 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7613 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7614 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7615 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7616 "<link>$co_url</link>\n" .
7617 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7618 "<content:encoded>" .
7619 "<![CDATA[\n";
7620 } elsif ($format eq 'atom') {
7621 print "<entry>\n" .
7622 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7623 "<updated>$cd{'iso-8601'}</updated>\n" .
7624 "<author>\n" .
7625 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7626 if ($co{'author_email'}) {
7627 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7629 print "</author>\n" .
7630 # use committer for contributor
7631 "<contributor>\n" .
7632 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7633 if ($co{'committer_email'}) {
7634 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7636 print "</contributor>\n" .
7637 "<published>$cd{'iso-8601'}</published>\n" .
7638 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7639 "<id>$co_url</id>\n" .
7640 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7641 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7643 my $comment = $co{'comment'};
7644 print "<pre>\n";
7645 foreach my $line (@$comment) {
7646 $line = esc_html($line);
7647 print "$line\n";
7649 print "</pre><ul>\n";
7650 foreach my $difftree_line (@difftree) {
7651 my %difftree = parse_difftree_raw_line($difftree_line);
7652 next if !$difftree{'from_id'};
7654 my $file = $difftree{'file'} || $difftree{'to_file'};
7656 print "<li>" .
7657 "[" .
7658 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7659 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7660 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7661 file_name=>$file, file_parent=>$difftree{'from_file'}),
7662 -title => "diff"}, 'D');
7663 if ($have_blame) {
7664 print $cgi->a({-href => href(-full=>1, action=>"blame",
7665 file_name=>$file, hash_base=>$commit),
7666 -title => "blame"}, 'B');
7668 # if this is not a feed of a file history
7669 if (!defined $file_name || $file_name ne $file) {
7670 print $cgi->a({-href => href(-full=>1, action=>"history",
7671 file_name=>$file, hash=>$commit),
7672 -title => "history"}, 'H');
7674 $file = esc_path($file);
7675 print "] ".
7676 "$file</li>\n";
7678 if ($format eq 'rss') {
7679 print "</ul>]]>\n" .
7680 "</content:encoded>\n" .
7681 "</item>\n";
7682 } elsif ($format eq 'atom') {
7683 print "</ul>\n</div>\n" .
7684 "</content>\n" .
7685 "</entry>\n";
7689 # end of feed
7690 if ($format eq 'rss') {
7691 print "</channel>\n</rss>\n";
7692 } elsif ($format eq 'atom') {
7693 print "</feed>\n";
7697 sub git_rss {
7698 git_feed('rss');
7701 sub git_atom {
7702 git_feed('atom');
7705 sub git_opml {
7706 my @list = git_get_projects_list();
7707 if (!@list) {
7708 die_error(404, "No projects found");
7711 print $cgi->header(
7712 -type => 'text/xml',
7713 -charset => 'utf-8',
7714 -content_disposition => 'inline; filename="opml.xml"');
7716 print <<XML;
7717 <?xml version="1.0" encoding="utf-8"?>
7718 <opml version="1.0">
7719 <head>
7720 <title>$site_name OPML Export</title>
7721 </head>
7722 <body>
7723 <outline text="git RSS feeds">
7726 foreach my $pr (@list) {
7727 my %proj = %$pr;
7728 my $head = git_get_head_hash($proj{'path'});
7729 if (!defined $head) {
7730 next;
7732 $git_dir = "$projectroot/$proj{'path'}";
7733 my %co = parse_commit($head);
7734 if (!%co) {
7735 next;
7738 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7739 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7740 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7741 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7743 print <<XML;
7744 </outline>
7745 </body>
7746 </opml>